id
stringlengths
11
116
type
stringclasses
1 value
granularity
stringclasses
4 values
content
stringlengths
16
477k
metadata
dict
file_diesel_models_-7434313067708698207
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/payment_attempt.rs // Contains: 12 structs, 3 enums #[cfg(feature = "v2")] use common_types::payments as common_payments_types; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, OvercaptureEnabledBool, RequestExtendedAuthorizationBool, }; use common_utils::{ id_type, pii, types::{ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::enums as storage_enums; #[cfg(feature = "v1")] use crate::schema::payment_attempt; #[cfg(feature = "v2")] use crate::{schema_v2::payment_attempt, RequiredFromNullable}; common_utils::impl_to_sql_from_sql_json!(ConnectorMandateReferenceId); #[derive( Clone, Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq, diesel::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct ConnectorMandateReferenceId { pub connector_mandate_id: Option<String>, pub payment_method_id: Option<String>, pub mandate_metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } } common_utils::impl_to_sql_from_sql_json!(NetworkDetails); #[derive( Clone, Default, Debug, serde::Deserialize, Eq, PartialEq, serde::Serialize, diesel::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct NetworkDetails { pub network_advice_code: Option<String>, } #[cfg(feature = "v2")] #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable, )] #[diesel(table_name = payment_attempt, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct PaymentAttempt { pub payment_id: id_type::GlobalPaymentId, pub merchant_id: id_type::MerchantId, pub status: storage_enums::AttemptStatus, pub connector: Option<String>, pub error_message: Option<String>, pub surcharge_amount: Option<MinorUnit>, pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, #[diesel(deserialize_as = RequiredFromNullable<storage_enums::AuthenticationType>)] pub authentication_type: storage_enums::AuthenticationType, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, pub browser_info: Option<common_utils::types::BrowserInformation>, pub error_code: Option<String>, pub payment_token: Option<String>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_data: Option<pii::SecretSerdeValue>, pub preprocessing_step_id: Option<String>, pub error_reason: Option<String>, pub multiple_capture_count: Option<i16>, pub connector_response_reference_id: Option<String>, pub amount_capturable: MinorUnit, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub encoded_data: Option<masking::Secret<String>>, pub unified_code: Option<String>, pub unified_message: Option<String>, #[diesel(deserialize_as = RequiredFromNullable<MinorUnit>)] pub net_amount: MinorUnit, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<id_type::AuthenticationId>, pub fingerprint_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<masking::Secret<common_payments_types::CustomerAcceptance>>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub card_network: Option<String>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<storage_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub processor_merchant_id: Option<id_type::MerchantId>, pub created_by: Option<String>, pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub is_overcapture_enabled: Option<OvercaptureEnabledBool>, pub network_details: Option<NetworkDetails>, pub is_stored_credential: Option<bool>, /// stores the authorized amount in case of partial authorization pub authorized_amount: Option<MinorUnit>, #[diesel(deserialize_as = RequiredFromNullable<storage_enums::PaymentMethod>)] pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, pub payment_method_subtype: storage_enums::PaymentMethodType, pub routing_result: Option<serde_json::Value>, pub authentication_applied: Option<common_enums::AuthenticationType>, pub external_reference_id: Option<String>, pub tax_on_surcharge: Option<MinorUnit>, pub payment_method_billing_address: Option<common_utils::encryption::Encryption>, pub redirection_data: Option<RedirectForm>, pub connector_payment_data: Option<String>, pub connector_token_details: Option<ConnectorTokenDetails>, pub id: id_type::GlobalAttemptId, pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, /// A string indicating the group of the payment attempt. Used in split payments flow pub attempts_group_id: Option<String>, } #[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable, )] #[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentAttempt { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, pub offer_amount: Option<MinorUnit>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<ConnectorTransactionId>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub error_code: Option<String>, pub payment_token: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_data: Option<serde_json::Value>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, // providing a location to store mandate details intermediately for transaction pub mandate_details: Option<storage_enums::MandateDataType>, pub error_reason: Option<String>, pub multiple_capture_count: Option<i16>, // reference to the payment at connector side pub connector_response_reference_id: Option<String>, pub amount_capturable: MinorUnit, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub net_amount: Option<MinorUnit>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<id_type::AuthenticationId>, pub mandate_data: Option<storage_enums::MandateDetails>, pub fingerprint_id: Option<String>, pub payment_method_billing_address_id: Option<String>, pub charge_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub card_network: Option<String>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, /// INFO: This field is deprecated and replaced by processor_transaction_data pub connector_transaction_data: Option<String>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub processor_transaction_data: Option<String>, pub card_discovery: Option<storage_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub issuer_error_code: Option<String>, pub issuer_error_message: Option<String>, pub processor_merchant_id: Option<id_type::MerchantId>, pub created_by: Option<String>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub is_overcapture_enabled: Option<OvercaptureEnabledBool>, pub network_details: Option<NetworkDetails>, pub is_stored_credential: Option<bool>, /// stores the authorized amount in case of partial authorization pub authorized_amount: Option<MinorUnit>, } #[cfg(feature = "v1")] impl ConnectorTransactionIdTrait for PaymentAttempt { fn get_optional_connector_transaction_id(&self) -> Option<&String> { match self .connector_transaction_id .as_ref() .map(|txn_id| txn_id.get_txn_id(self.processor_transaction_data.as_ref())) .transpose() { Ok(txn_id) => txn_id, // In case hashed data is missing from DB, use the hashed ID as connector transaction ID Err(_) => self .connector_transaction_id .as_ref() .map(|txn_id| txn_id.get_id()), } } } #[cfg(feature = "v2")] impl ConnectorTransactionIdTrait for PaymentAttempt { fn get_optional_connector_transaction_id(&self) -> Option<&String> { match self .connector_payment_id .as_ref() .map(|txn_id| txn_id.get_txn_id(self.connector_payment_data.as_ref())) .transpose() { Ok(txn_id) => txn_id, // In case hashed data is missing from DB, use the hashed ID as connector payment ID Err(_) => self .connector_payment_id .as_ref() .map(|txn_id| txn_id.get_id()), } } } #[cfg(feature = "v2")] #[derive( Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize, diesel::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct ConnectorTokenDetails { pub connector_mandate_id: Option<String>, pub connector_token_request_reference_id: Option<String>, } #[cfg(feature = "v2")] common_utils::impl_to_sql_from_sql_json!(ConnectorTokenDetails); #[cfg(feature = "v2")] impl ConnectorTokenDetails { pub fn get_connector_token_request_reference_id(&self) -> Option<String> { self.connector_token_request_reference_id.clone() } } #[derive(Clone, Debug, Eq, PartialEq, Queryable, Serialize, Deserialize)] pub struct PaymentListFilters { pub connector: Vec<String>, pub currency: Vec<storage_enums::Currency>, pub status: Vec<storage_enums::IntentStatus>, pub payment_method: Vec<storage_enums::PaymentMethod>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptNew { pub payment_id: id_type::GlobalPaymentId, pub merchant_id: id_type::MerchantId, pub attempts_group_id: Option<String>, pub status: storage_enums::AttemptStatus, pub error_message: Option<String>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, pub authentication_type: storage_enums::AuthenticationType, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, pub browser_info: Option<common_utils::types::BrowserInformation>, pub payment_token: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_data: Option<pii::SecretSerdeValue>, pub preprocessing_step_id: Option<String>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub network_details: Option<NetworkDetails>, pub is_stored_credential: Option<bool>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub redirection_data: Option<RedirectForm>, pub encoded_data: Option<masking::Secret<String>>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub net_amount: MinorUnit, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<id_type::AuthenticationId>, pub fingerprint_id: Option<String>, pub payment_method_billing_address: Option<common_utils::encryption::Encryption>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<masking::Secret<common_payments_types::CustomerAcceptance>>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub card_network: Option<String>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, pub payment_method_subtype: storage_enums::PaymentMethodType, pub id: id_type::GlobalAttemptId, pub connector_token_details: Option<ConnectorTokenDetails>, pub card_discovery: Option<storage_enums::CardDiscovery>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub connector: Option<String>, pub network_decline_code: Option<String>, pub network_advice_code: Option<String>, pub network_error_message: Option<String>, pub processor_merchant_id: Option<id_type::MerchantId>, pub created_by: Option<String>, pub connector_request_reference_id: Option<String>, pub authorized_amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptNew { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub attempt_id: String, pub status: storage_enums::AttemptStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, // pub auto_capture: Option<bool>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, pub offer_amount: Option<MinorUnit>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub payment_token: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_data: Option<serde_json::Value>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, pub mandate_details: Option<storage_enums::MandateDataType>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub net_amount: Option<MinorUnit>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<id_type::AuthenticationId>, pub mandate_data: Option<storage_enums::MandateDetails>, pub fingerprint_id: Option<String>, pub payment_method_billing_address_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub card_network: Option<String>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<storage_enums::CardDiscovery>, pub processor_merchant_id: Option<id_type::MerchantId>, pub created_by: Option<String>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub network_details: Option<NetworkDetails>, pub is_stored_credential: Option<bool>, pub authorized_amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentAttemptUpdate { Update { amount: MinorUnit, currency: storage_enums::Currency, status: storage_enums::AttemptStatus, authentication_type: Option<storage_enums::AuthenticationType>, payment_method: Option<storage_enums::PaymentMethod>, payment_token: Option<String>, payment_method_data: Option<serde_json::Value>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_experience: Option<storage_enums::PaymentExperience>, business_sub_label: Option<String>, amount_to_capture: Option<MinorUnit>, capture_method: Option<storage_enums::CaptureMethod>, surcharge_amount: Option<MinorUnit>, tax_amount: Option<MinorUnit>, fingerprint_id: Option<String>, payment_method_billing_address_id: Option<String>, network_transaction_id: Option<String>, updated_by: String, }, UpdateTrackers { payment_token: Option<String>, connector: Option<String>, straight_through_algorithm: Option<serde_json::Value>, amount_capturable: Option<MinorUnit>, surcharge_amount: Option<MinorUnit>, tax_amount: Option<MinorUnit>, updated_by: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, routing_approach: Option<storage_enums::RoutingApproach>, is_stored_credential: Option<bool>, }, AuthenticationTypeUpdate { authentication_type: storage_enums::AuthenticationType, updated_by: String, }, ConfirmUpdate { amount: MinorUnit, currency: storage_enums::Currency, status: storage_enums::AttemptStatus, authentication_type: Option<storage_enums::AuthenticationType>, capture_method: Option<storage_enums::CaptureMethod>, payment_method: Option<storage_enums::PaymentMethod>, browser_info: Option<serde_json::Value>, connector: Option<String>, payment_token: Option<String>, payment_method_data: Option<serde_json::Value>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_experience: Option<storage_enums::PaymentExperience>, business_sub_label: Option<String>, straight_through_algorithm: Option<serde_json::Value>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, surcharge_amount: Option<MinorUnit>, tax_amount: Option<MinorUnit>, fingerprint_id: Option<String>, updated_by: String, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, payment_method_id: Option<String>, external_three_ds_authentication_attempted: Option<bool>, authentication_connector: Option<String>, authentication_id: Option<id_type::AuthenticationId>, payment_method_billing_address_id: Option<String>, client_source: Option<String>, client_version: Option<String>, customer_acceptance: Option<pii::SecretSerdeValue>, shipping_cost: Option<MinorUnit>, order_tax_amount: Option<MinorUnit>, connector_mandate_detail: Option<ConnectorMandateReferenceId>, card_discovery: Option<storage_enums::CardDiscovery>, routing_approach: Option<storage_enums::RoutingApproach>, connector_request_reference_id: Option<String>, network_transaction_id: Option<String>, is_stored_credential: Option<bool>, request_extended_authorization: Option<RequestExtendedAuthorizationBool>, }, VoidUpdate { status: storage_enums::AttemptStatus, cancellation_reason: Option<String>, updated_by: String, }, PaymentMethodDetailsUpdate { payment_method_id: Option<String>, updated_by: String, }, ConnectorMandateDetailUpdate { connector_mandate_detail: Option<ConnectorMandateReferenceId>, updated_by: String, }, BlocklistUpdate { status: storage_enums::AttemptStatus, error_code: Option<Option<String>>, error_message: Option<Option<String>>, updated_by: String, }, RejectUpdate { status: storage_enums::AttemptStatus, error_code: Option<Option<String>>, error_message: Option<Option<String>>, updated_by: String, }, ResponseUpdate { status: storage_enums::AttemptStatus, connector: Option<String>, connector_transaction_id: Option<String>, authentication_type: Option<storage_enums::AuthenticationType>, network_transaction_id: Option<String>, payment_method_id: Option<String>, mandate_id: Option<String>, connector_metadata: Option<serde_json::Value>, payment_token: Option<String>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, connector_response_reference_id: Option<String>, amount_capturable: Option<MinorUnit>, updated_by: String, authentication_data: Option<serde_json::Value>, encoded_data: Option<String>, unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, capture_before: Option<PrimitiveDateTime>, extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, payment_method_data: Option<serde_json::Value>, connector_mandate_detail: Option<ConnectorMandateReferenceId>, charges: Option<common_types::payments::ConnectorChargeResponseData>, setup_future_usage_applied: Option<storage_enums::FutureUsage>, is_overcapture_enabled: Option<OvercaptureEnabledBool>, authorized_amount: Option<MinorUnit>, }, UnresolvedResponseUpdate { status: storage_enums::AttemptStatus, connector: Option<String>, connector_transaction_id: Option<String>, payment_method_id: Option<String>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, connector_response_reference_id: Option<String>, updated_by: String, }, StatusUpdate { status: storage_enums::AttemptStatus, updated_by: String, }, ErrorUpdate { connector: Option<String>, status: storage_enums::AttemptStatus, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, amount_capturable: Option<MinorUnit>, updated_by: String, unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, connector_transaction_id: Option<String>, payment_method_data: Option<serde_json::Value>, authentication_type: Option<storage_enums::AuthenticationType>, issuer_error_code: Option<String>, issuer_error_message: Option<String>, network_details: Option<NetworkDetails>, }, CaptureUpdate { amount_to_capture: Option<MinorUnit>, multiple_capture_count: Option<i16>, updated_by: String, }, AmountToCaptureUpdate { status: storage_enums::AttemptStatus, amount_capturable: MinorUnit, updated_by: String, }, PreprocessingUpdate { status: storage_enums::AttemptStatus, payment_method_id: Option<String>, connector_metadata: Option<serde_json::Value>, preprocessing_step_id: Option<String>, connector_transaction_id: Option<String>, connector_response_reference_id: Option<String>, updated_by: String, }, ConnectorResponse { authentication_data: Option<serde_json::Value>, encoded_data: Option<String>, connector_transaction_id: Option<String>, connector: Option<String>, charges: Option<common_types::payments::ConnectorChargeResponseData>, updated_by: String, }, IncrementalAuthorizationAmountUpdate { amount: MinorUnit, amount_capturable: MinorUnit, }, AuthenticationUpdate { status: storage_enums::AttemptStatus, external_three_ds_authentication_attempted: Option<bool>, authentication_connector: Option<String>, authentication_id: Option<id_type::AuthenticationId>, updated_by: String, }, ManualUpdate { status: Option<storage_enums::AttemptStatus>, error_code: Option<String>, error_message: Option<String>, error_reason: Option<String>, updated_by: String, unified_code: Option<String>, unified_message: Option<String>, connector_transaction_id: Option<String>, }, PostSessionTokensUpdate { updated_by: String, connector_metadata: Option<serde_json::Value>, }, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentAttemptUpdate { // Update { // amount: MinorUnit, // currency: storage_enums::Currency, // status: storage_enums::AttemptStatus, // authentication_type: Option<storage_enums::AuthenticationType>, // payment_method: Option<storage_enums::PaymentMethod>, // payment_token: Option<String>, // payment_method_data: Option<serde_json::Value>, // payment_method_type: Option<storage_enums::PaymentMethodType>, // payment_experience: Option<storage_enums::PaymentExperience>, // business_sub_label: Option<String>, // amount_to_capture: Option<MinorUnit>, // capture_method: Option<storage_enums::CaptureMethod>, // surcharge_amount: Option<MinorUnit>, // tax_amount: Option<MinorUnit>, // fingerprint_id: Option<String>, // payment_method_billing_address_id: Option<String>, // updated_by: String, // }, // UpdateTrackers { // payment_token: Option<String>, // connector: Option<String>, // straight_through_algorithm: Option<serde_json::Value>, // amount_capturable: Option<MinorUnit>, // surcharge_amount: Option<MinorUnit>, // tax_amount: Option<MinorUnit>, // updated_by: String, // merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, // }, // AuthenticationTypeUpdate { // authentication_type: storage_enums::AuthenticationType, // updated_by: String, // }, // ConfirmUpdate { // amount: MinorUnit, // currency: storage_enums::Currency, // status: storage_enums::AttemptStatus, // authentication_type: Option<storage_enums::AuthenticationType>, // capture_method: Option<storage_enums::CaptureMethod>, // payment_method: Option<storage_enums::PaymentMethod>, // browser_info: Option<serde_json::Value>, // connector: Option<String>, // payment_token: Option<String>, // payment_method_data: Option<serde_json::Value>, // payment_method_type: Option<storage_enums::PaymentMethodType>, // payment_experience: Option<storage_enums::PaymentExperience>, // business_sub_label: Option<String>, // straight_through_algorithm: Option<serde_json::Value>, // error_code: Option<Option<String>>, // error_message: Option<Option<String>>, // amount_capturable: Option<MinorUnit>, // surcharge_amount: Option<MinorUnit>, // tax_amount: Option<MinorUnit>, // fingerprint_id: Option<String>, // updated_by: String, // merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, // payment_method_id: Option<String>, // external_three_ds_authentication_attempted: Option<bool>, // authentication_connector: Option<String>, // authentication_id: Option<String>, // payment_method_billing_address_id: Option<String>, // client_source: Option<String>, // client_version: Option<String>, // customer_acceptance: Option<pii::SecretSerdeValue>, // }, // VoidUpdate { // status: storage_enums::AttemptStatus, // cancellation_reason: Option<String>, // updated_by: String, // }, // PaymentMethodDetailsUpdate { // payment_method_id: Option<String>, // updated_by: String, // }, // ConnectorMandateDetailUpdate { // connector_mandate_detail: Option<ConnectorMandateReferenceId>, // updated_by: String, // } // BlocklistUpdate { // status: storage_enums::AttemptStatus, // error_code: Option<Option<String>>, // error_message: Option<Option<String>>, // updated_by: String, // }, // RejectUpdate { // status: storage_enums::AttemptStatus, // error_code: Option<Option<String>>, // error_message: Option<Option<String>>, // updated_by: String, // }, ResponseUpdate { status: storage_enums::AttemptStatus, connector: Option<String>, connector_payment_id: Option<String>, authentication_type: Option<storage_enums::AuthenticationType>, payment_method_id: Option<id_type::GlobalPaymentMethodId>, connector_metadata: Option<pii::SecretSerdeValue>, payment_token: Option<String>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, connector_response_reference_id: Option<String>, amount_capturable: Option<MinorUnit>, updated_by: String, unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, }, UnresolvedResponseUpdate { status: storage_enums::AttemptStatus, connector: Option<String>, connector_payment_id: Option<String>, payment_method_id: Option<id_type::GlobalPaymentMethodId>, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, connector_response_reference_id: Option<String>, updated_by: String, }, // StatusUpdate { // status: storage_enums::AttemptStatus, // updated_by: String, // }, ErrorUpdate { connector: Option<String>, status: storage_enums::AttemptStatus, error_code: Option<Option<String>>, error_message: Option<Option<String>>, error_reason: Option<Option<String>>, amount_capturable: Option<MinorUnit>, updated_by: String, unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, connector_payment_id: Option<String>, authentication_type: Option<storage_enums::AuthenticationType>, }, // CaptureUpdate { // amount_to_capture: Option<MinorUnit>, // multiple_capture_count: Option<MinorUnit>, // updated_by: String, // }, // AmountToCaptureUpdate { // status: storage_enums::AttemptStatus, // amount_capturable: MinorUnit, // updated_by: String, // }, PreprocessingUpdate { status: storage_enums::AttemptStatus, payment_method_id: Option<id_type::GlobalPaymentMethodId>, connector_metadata: Option<pii::SecretSerdeValue>, preprocessing_step_id: Option<String>, connector_payment_id: Option<String>, connector_response_reference_id: Option<String>, updated_by: String, }, ConnectorResponse { connector_payment_id: Option<String>, connector: Option<String>, updated_by: String, }, // IncrementalAuthorizationAmountUpdate { // amount: MinorUnit, // amount_capturable: MinorUnit, // }, // AuthenticationUpdate { // status: storage_enums::AttemptStatus, // external_three_ds_authentication_attempted: Option<bool>, // authentication_connector: Option<String>, // authentication_id: Option<String>, // updated_by: String, // }, ManualUpdate { status: Option<storage_enums::AttemptStatus>, error_code: Option<String>, error_message: Option<String>, error_reason: Option<String>, updated_by: String, unified_code: Option<String>, unified_message: Option<String>, connector_payment_id: Option<String>, }, } // TODO: uncomment fields as and when required #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptUpdateInternal { pub status: Option<storage_enums::AttemptStatus>, pub authentication_type: Option<storage_enums::AuthenticationType>, pub error_message: Option<String>, pub connector_payment_id: Option<ConnectorTransactionId>, pub connector_payment_data: Option<String>, pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, pub cancellation_reason: Option<String>, pub modified_at: PrimitiveDateTime, pub browser_info: Option<serde_json::Value>, // payment_token: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<pii::SecretSerdeValue>, // payment_method_data: Option<serde_json::Value>, // payment_experience: Option<storage_enums::PaymentExperience>, // preprocessing_step_id: Option<String>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, // multiple_capture_count: Option<i16>, // pub surcharge_amount: Option<MinorUnit>, // tax_on_surcharge: Option<MinorUnit>, pub amount_capturable: Option<MinorUnit>, pub amount_to_capture: Option<MinorUnit>, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub connector: Option<String>, pub redirection_data: Option<RedirectForm>, // encoded_data: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, // external_three_ds_authentication_attempted: Option<bool>, // authentication_connector: Option<String>, // authentication_id: Option<String>, // fingerprint_id: Option<String>, // charge_id: Option<String>, // client_source: Option<String>, // client_version: Option<String>, // customer_acceptance: Option<pii::SecretSerdeValue>, // card_network: Option<String>, pub connector_token_details: Option<ConnectorTokenDetails>, pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, pub network_decline_code: Option<String>, pub network_advice_code: Option<String>, pub network_error_message: Option<String>, pub connector_request_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentAttemptUpdateInternal { pub fn apply_changeset(self, source: PaymentAttempt) -> PaymentAttempt { let Self { status, authentication_type, error_message, connector_payment_id, connector_payment_data, modified_at, browser_info, error_code, cancellation_reason, connector_metadata, error_reason, amount_capturable, amount_to_capture, updated_by, merchant_connector_id, connector, redirection_data, unified_code, unified_message, connector_token_details, feature_metadata, network_decline_code, network_advice_code, network_error_message, payment_method_id, connector_request_reference_id, connector_response_reference_id, } = self; PaymentAttempt { payment_id: source.payment_id, merchant_id: source.merchant_id, status: status.unwrap_or(source.status), connector: connector.or(source.connector), error_message: error_message.or(source.error_message), surcharge_amount: source.surcharge_amount, payment_method_id: payment_method_id.or(source.payment_method_id), authentication_type: authentication_type.unwrap_or(source.authentication_type), created_at: source.created_at, modified_at: common_utils::date_time::now(), last_synced: source.last_synced, cancellation_reason: source.cancellation_reason, amount_to_capture: amount_to_capture.or(source.amount_to_capture), browser_info: browser_info .and_then(|val| { serde_json::from_value::<common_utils::types::BrowserInformation>(val).ok() }) .or(source.browser_info), error_code: error_code.or(source.error_code), payment_token: source.payment_token, connector_metadata: connector_metadata.or(source.connector_metadata), payment_experience: source.payment_experience, payment_method_data: source.payment_method_data, preprocessing_step_id: source.preprocessing_step_id, error_reason: error_reason.or(source.error_reason), multiple_capture_count: source.multiple_capture_count, connector_response_reference_id: connector_response_reference_id .or(source.connector_response_reference_id), amount_capturable: amount_capturable.unwrap_or(source.amount_capturable), updated_by, merchant_connector_id: merchant_connector_id.or(source.merchant_connector_id), encoded_data: source.encoded_data, unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), net_amount: source.net_amount, external_three_ds_authentication_attempted: source .external_three_ds_authentication_attempted, authentication_connector: source.authentication_connector, authentication_id: source.authentication_id, fingerprint_id: source.fingerprint_id, client_source: source.client_source, client_version: source.client_version, customer_acceptance: source.customer_acceptance, profile_id: source.profile_id, organization_id: source.organization_id, card_network: source.card_network, shipping_cost: source.shipping_cost, order_tax_amount: source.order_tax_amount, request_extended_authorization: source.request_extended_authorization, extended_authorization_applied: source.extended_authorization_applied, capture_before: source.capture_before, card_discovery: source.card_discovery, charges: source.charges, processor_merchant_id: source.processor_merchant_id, created_by: source.created_by, payment_method_type_v2: source.payment_method_type_v2, network_transaction_id: source.network_transaction_id, connector_payment_id: connector_payment_id.or(source.connector_payment_id), payment_method_subtype: source.payment_method_subtype, routing_result: source.routing_result, authentication_applied: source.authentication_applied, external_reference_id: source.external_reference_id, tax_on_surcharge: source.tax_on_surcharge, payment_method_billing_address: source.payment_method_billing_address, redirection_data: redirection_data.or(source.redirection_data), connector_payment_data: connector_payment_data.or(source.connector_payment_data), connector_token_details: connector_token_details.or(source.connector_token_details), id: source.id, feature_metadata: feature_metadata.or(source.feature_metadata), network_advice_code: network_advice_code.or(source.network_advice_code), network_decline_code: network_decline_code.or(source.network_decline_code), network_error_message: network_error_message.or(source.network_error_message), connector_request_reference_id: connector_request_reference_id .or(source.connector_request_reference_id), is_overcapture_enabled: source.is_overcapture_enabled, network_details: source.network_details, attempts_group_id: source.attempts_group_id, is_stored_credential: source.is_stored_credential, authorized_amount: source.authorized_amount, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptUpdateInternal { pub amount: Option<MinorUnit>, pub net_amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub status: Option<storage_enums::AttemptStatus>, pub connector_transaction_id: Option<ConnectorTransactionId>, pub amount_to_capture: Option<MinorUnit>, pub connector: Option<Option<String>>, pub authentication_type: Option<storage_enums::AuthenticationType>, pub payment_method: Option<storage_enums::PaymentMethod>, pub error_message: Option<Option<String>>, pub payment_method_id: Option<String>, pub cancellation_reason: Option<String>, pub modified_at: PrimitiveDateTime, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub payment_token: Option<String>, pub error_code: Option<Option<String>>, pub connector_metadata: Option<serde_json::Value>, pub payment_method_data: Option<serde_json::Value>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, pub error_reason: Option<Option<String>>, pub capture_method: Option<storage_enums::CaptureMethod>, pub connector_response_reference_id: Option<String>, pub multiple_capture_count: Option<i16>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub amount_capturable: Option<MinorUnit>, pub updated_by: String, pub merchant_connector_id: Option<Option<id_type::MerchantConnectorAccountId>>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub unified_code: Option<Option<String>>, pub unified_message: Option<Option<String>>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<id_type::AuthenticationId>, pub fingerprint_id: Option<String>, pub payment_method_billing_address_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub card_network: Option<String>, pub capture_before: Option<PrimitiveDateTime>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub processor_transaction_data: Option<String>, pub card_discovery: Option<common_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub issuer_error_code: Option<String>, pub issuer_error_message: Option<String>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub is_overcapture_enabled: Option<OvercaptureEnabledBool>, pub network_details: Option<NetworkDetails>, pub is_stored_credential: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub authorized_amount: Option<MinorUnit>, } #[cfg(feature = "v1")] impl PaymentAttemptUpdateInternal { pub fn populate_derived_fields(self, source: &PaymentAttempt) -> Self { let mut update_internal = self; update_internal.net_amount = Some( update_internal.amount.unwrap_or(source.amount) + update_internal .surcharge_amount .or(source.surcharge_amount) .unwrap_or(MinorUnit::new(0)) + update_internal .tax_amount .or(source.tax_amount) .unwrap_or(MinorUnit::new(0)) + update_internal .shipping_cost .or(source.shipping_cost) .unwrap_or(MinorUnit::new(0)) + update_internal .order_tax_amount .or(source.order_tax_amount) .unwrap_or(MinorUnit::new(0)), ); update_internal.card_network = update_internal .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()); update_internal } } #[cfg(feature = "v2")] impl PaymentAttemptUpdate { pub fn apply_changeset(self, _source: PaymentAttempt) -> PaymentAttempt { todo!() // let PaymentAttemptUpdateInternal { // net_amount, // status, // authentication_type, // error_message, // payment_method_id, // cancellation_reason, // modified_at: _, // browser_info, // payment_token, // error_code, // connector_metadata, // payment_method_data, // payment_experience, // straight_through_algorithm, // preprocessing_step_id, // error_reason, // connector_response_reference_id, // multiple_capture_count, // surcharge_amount, // tax_amount, // amount_capturable, // updated_by, // merchant_connector_id, // authentication_data, // encoded_data, // unified_code, // unified_message, // external_three_ds_authentication_attempted, // authentication_connector, // authentication_id, // payment_method_billing_address_id, // fingerprint_id, // charge_id, // client_source, // client_version, // customer_acceptance, // card_network, // } = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source); // PaymentAttempt { // net_amount: net_amount.or(source.net_amount), // status: status.unwrap_or(source.status), // authentication_type: authentication_type.or(source.authentication_type), // error_message: error_message.unwrap_or(source.error_message), // payment_method_id: payment_method_id.or(source.payment_method_id), // cancellation_reason: cancellation_reason.or(source.cancellation_reason), // modified_at: common_utils::date_time::now(), // browser_info: browser_info.or(source.browser_info), // payment_token: payment_token.or(source.payment_token), // error_code: error_code.unwrap_or(source.error_code), // connector_metadata: connector_metadata.or(source.connector_metadata), // payment_method_data: payment_method_data.or(source.payment_method_data), // payment_experience: payment_experience.or(source.payment_experience), // straight_through_algorithm: straight_through_algorithm // .or(source.straight_through_algorithm), // preprocessing_step_id: preprocessing_step_id.or(source.preprocessing_step_id), // error_reason: error_reason.unwrap_or(source.error_reason), // connector_response_reference_id: connector_response_reference_id // .or(source.connector_response_reference_id), // multiple_capture_count: multiple_capture_count.or(source.multiple_capture_count), // surcharge_amount: surcharge_amount.or(source.surcharge_amount), // tax_amount: tax_amount.or(source.tax_amount), // amount_capturable: amount_capturable.unwrap_or(source.amount_capturable), // updated_by, // merchant_connector_id: merchant_connector_id.unwrap_or(source.merchant_connector_id), // authentication_data: authentication_data.or(source.authentication_data), // encoded_data: encoded_data.or(source.encoded_data), // unified_code: unified_code.unwrap_or(source.unified_code), // unified_message: unified_message.unwrap_or(source.unified_message), // external_three_ds_authentication_attempted: external_three_ds_authentication_attempted // .or(source.external_three_ds_authentication_attempted), // authentication_connector: authentication_connector.or(source.authentication_connector), // authentication_id: authentication_id.or(source.authentication_id), // payment_method_billing_address_id: payment_method_billing_address_id // .or(source.payment_method_billing_address_id), // fingerprint_id: fingerprint_id.or(source.fingerprint_id), // charge_id: charge_id.or(source.charge_id), // client_source: client_source.or(source.client_source), // client_version: client_version.or(source.client_version), // customer_acceptance: customer_acceptance.or(source.customer_acceptance), // card_network: card_network.or(source.card_network), // ..source // } } } #[cfg(feature = "v1")] impl PaymentAttemptUpdate { pub fn apply_changeset(self, source: PaymentAttempt) -> PaymentAttempt { let PaymentAttemptUpdateInternal { amount, net_amount, currency, status, connector_transaction_id, amount_to_capture, connector, authentication_type, payment_method, error_message, payment_method_id, cancellation_reason, modified_at: _, mandate_id, browser_info, payment_token, error_code, connector_metadata, payment_method_data, payment_method_type, payment_experience, business_sub_label, straight_through_algorithm, preprocessing_step_id, error_reason, capture_method, connector_response_reference_id, multiple_capture_count, surcharge_amount, tax_amount, amount_capturable, updated_by, merchant_connector_id, authentication_data, encoded_data, unified_code, unified_message, external_three_ds_authentication_attempted, authentication_connector, authentication_id, payment_method_billing_address_id, fingerprint_id, client_source, client_version, customer_acceptance, card_network, shipping_cost, order_tax_amount, processor_transaction_data, connector_mandate_detail, capture_before, extended_authorization_applied, card_discovery, charges, issuer_error_code, issuer_error_message, setup_future_usage_applied, routing_approach, connector_request_reference_id, network_transaction_id, is_overcapture_enabled, network_details, is_stored_credential, request_extended_authorization, authorized_amount, } = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source); PaymentAttempt { amount: amount.unwrap_or(source.amount), net_amount: net_amount.or(source.net_amount), currency: currency.or(source.currency), status: status.unwrap_or(source.status), connector_transaction_id: connector_transaction_id.or(source.connector_transaction_id), amount_to_capture: amount_to_capture.or(source.amount_to_capture), connector: connector.unwrap_or(source.connector), authentication_type: authentication_type.or(source.authentication_type), payment_method: payment_method.or(source.payment_method), error_message: error_message.unwrap_or(source.error_message), payment_method_id: payment_method_id.or(source.payment_method_id), cancellation_reason: cancellation_reason.or(source.cancellation_reason), modified_at: common_utils::date_time::now(), mandate_id: mandate_id.or(source.mandate_id), browser_info: browser_info.or(source.browser_info), payment_token: payment_token.or(source.payment_token), error_code: error_code.unwrap_or(source.error_code), connector_metadata: connector_metadata.or(source.connector_metadata), payment_method_data: payment_method_data.or(source.payment_method_data), payment_method_type: payment_method_type.or(source.payment_method_type), payment_experience: payment_experience.or(source.payment_experience), business_sub_label: business_sub_label.or(source.business_sub_label), straight_through_algorithm: straight_through_algorithm .or(source.straight_through_algorithm), preprocessing_step_id: preprocessing_step_id.or(source.preprocessing_step_id), error_reason: error_reason.unwrap_or(source.error_reason), capture_method: capture_method.or(source.capture_method), connector_response_reference_id: connector_response_reference_id .or(source.connector_response_reference_id), multiple_capture_count: multiple_capture_count.or(source.multiple_capture_count), surcharge_amount: surcharge_amount.or(source.surcharge_amount), tax_amount: tax_amount.or(source.tax_amount), amount_capturable: amount_capturable.unwrap_or(source.amount_capturable), updated_by, merchant_connector_id: merchant_connector_id.unwrap_or(source.merchant_connector_id), authentication_data: authentication_data.or(source.authentication_data), encoded_data: encoded_data.or(source.encoded_data), unified_code: unified_code.unwrap_or(source.unified_code), unified_message: unified_message.unwrap_or(source.unified_message), external_three_ds_authentication_attempted: external_three_ds_authentication_attempted .or(source.external_three_ds_authentication_attempted), authentication_connector: authentication_connector.or(source.authentication_connector), authentication_id: authentication_id.or(source.authentication_id), payment_method_billing_address_id: payment_method_billing_address_id .or(source.payment_method_billing_address_id), fingerprint_id: fingerprint_id.or(source.fingerprint_id), client_source: client_source.or(source.client_source), client_version: client_version.or(source.client_version), customer_acceptance: customer_acceptance.or(source.customer_acceptance), card_network: card_network.or(source.card_network), shipping_cost: shipping_cost.or(source.shipping_cost), order_tax_amount: order_tax_amount.or(source.order_tax_amount), processor_transaction_data: processor_transaction_data .or(source.processor_transaction_data), connector_mandate_detail: connector_mandate_detail.or(source.connector_mandate_detail), capture_before: capture_before.or(source.capture_before), extended_authorization_applied: extended_authorization_applied .or(source.extended_authorization_applied), card_discovery: card_discovery.or(source.card_discovery), charges: charges.or(source.charges), issuer_error_code: issuer_error_code.or(source.issuer_error_code), issuer_error_message: issuer_error_message.or(source.issuer_error_message), setup_future_usage_applied: setup_future_usage_applied .or(source.setup_future_usage_applied), routing_approach: routing_approach.or(source.routing_approach), connector_request_reference_id: connector_request_reference_id .or(source.connector_request_reference_id), network_transaction_id: network_transaction_id.or(source.network_transaction_id), is_overcapture_enabled: is_overcapture_enabled.or(source.is_overcapture_enabled), network_details: network_details.or(source.network_details), is_stored_credential: is_stored_credential.or(source.is_stored_credential), request_extended_authorization: request_extended_authorization .or(source.request_extended_authorization), authorized_amount: authorized_amount.or(source.authorized_amount), ..source } } } #[cfg(feature = "v2")] impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { fn from(payment_attempt_update: PaymentAttemptUpdate) -> Self { match payment_attempt_update { PaymentAttemptUpdate::ResponseUpdate { status, connector, connector_payment_id, authentication_type, payment_method_id, connector_metadata, payment_token, error_code, error_message, error_reason, connector_response_reference_id, amount_capturable, updated_by, unified_code, unified_message, } => { let (connector_payment_id, connector_payment_data) = connector_payment_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { status: Some(status), connector, connector_payment_id, connector_payment_data, authentication_type, payment_method_id, connector_metadata, error_code: error_code.flatten(), error_message: error_message.flatten(), error_reason: error_reason.flatten(), connector_response_reference_id, amount_capturable, updated_by, unified_code: unified_code.flatten(), unified_message: unified_message.flatten(), modified_at: common_utils::date_time::now(), browser_info: None, amount_to_capture: None, merchant_connector_id: None, redirection_data: None, connector_token_details: None, feature_metadata: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_request_reference_id: None, cancellation_reason: None, } } PaymentAttemptUpdate::ErrorUpdate { connector, status, error_code, error_message, error_reason, amount_capturable, updated_by, unified_code, unified_message, connector_payment_id, authentication_type, } => { let (connector_payment_id, connector_payment_data) = connector_payment_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { connector, status: Some(status), error_code: error_code.flatten(), error_message: error_message.flatten(), error_reason: error_reason.flatten(), amount_capturable, updated_by, unified_code: unified_code.flatten(), unified_message: unified_message.flatten(), connector_payment_id, connector_payment_data, authentication_type, modified_at: common_utils::date_time::now(), payment_method_id: None, browser_info: None, connector_metadata: None, amount_to_capture: None, merchant_connector_id: None, redirection_data: None, connector_token_details: None, feature_metadata: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, cancellation_reason: None, } } PaymentAttemptUpdate::UnresolvedResponseUpdate { status, connector, connector_payment_id, payment_method_id, error_code, error_message, error_reason, connector_response_reference_id, updated_by, } => { let (connector_payment_id, connector_payment_data) = connector_payment_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { status: Some(status), connector, connector_payment_id, connector_payment_data, payment_method_id, error_code: error_code.flatten(), error_message: error_message.flatten(), error_reason: error_reason.flatten(), connector_response_reference_id, updated_by, modified_at: common_utils::date_time::now(), authentication_type: None, browser_info: None, connector_metadata: None, amount_capturable: None, amount_to_capture: None, merchant_connector_id: None, redirection_data: None, unified_code: None, unified_message: None, connector_token_details: None, feature_metadata: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_request_reference_id: None, cancellation_reason: None, } } PaymentAttemptUpdate::PreprocessingUpdate { status, payment_method_id, connector_metadata, preprocessing_step_id, connector_payment_id, connector_response_reference_id, updated_by, } => { let (connector_payment_id, connector_payment_data) = connector_payment_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { status: Some(status), payment_method_id, connector_metadata, connector_payment_id, connector_payment_data, connector_response_reference_id, updated_by, modified_at: common_utils::date_time::now(), authentication_type: None, error_message: None, browser_info: None, error_code: None, error_reason: None, amount_capturable: None, amount_to_capture: None, merchant_connector_id: None, connector: None, redirection_data: None, unified_code: None, unified_message: None, connector_token_details: None, feature_metadata: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_request_reference_id: None, cancellation_reason: None, } } PaymentAttemptUpdate::ConnectorResponse { connector_payment_id, connector, updated_by, } => { let (connector_payment_id, connector_payment_data) = connector_payment_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { connector_payment_id, connector_payment_data, connector, updated_by, modified_at: common_utils::date_time::now(), status: None, authentication_type: None, error_message: None, payment_method_id: None, browser_info: None, error_code: None, connector_metadata: None, error_reason: None, amount_capturable: None, amount_to_capture: None, merchant_connector_id: None, redirection_data: None, unified_code: None, unified_message: None, connector_token_details: None, feature_metadata: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, cancellation_reason: None, } } PaymentAttemptUpdate::ManualUpdate { status, error_code, error_message, error_reason, updated_by, unified_code, unified_message, connector_payment_id, } => { let (connector_payment_id, connector_payment_data) = connector_payment_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { status, error_code, error_message, error_reason, updated_by, unified_code, unified_message, connector_payment_id, connector_payment_data, modified_at: common_utils::date_time::now(), authentication_type: None, payment_method_id: None, browser_info: None, connector_metadata: None, amount_capturable: None, amount_to_capture: None, merchant_connector_id: None, connector: None, redirection_data: None, connector_token_details: None, feature_metadata: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, cancellation_reason: None, } } } // match payment_attempt_update { // PaymentAttemptUpdate::Update { // amount, // currency, // status, // // connector_transaction_id, // authentication_type, // payment_method, // payment_token, // payment_method_data, // payment_method_type, // payment_experience, // business_sub_label, // amount_to_capture, // capture_method, // surcharge_amount, // tax_amount, // fingerprint_id, // updated_by, // payment_method_billing_address_id, // } => Self { // status: Some(status), // // connector_transaction_id, // authentication_type, // payment_token, // modified_at: common_utils::date_time::now(), // payment_method_data, // payment_experience, // surcharge_amount, // tax_amount, // fingerprint_id, // payment_method_billing_address_id, // updated_by, // net_amount: None, // error_message: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // error_code: None, // connector_metadata: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::AuthenticationTypeUpdate { // authentication_type, // updated_by, // } => Self { // authentication_type: Some(authentication_type), // modified_at: common_utils::date_time::now(), // updated_by, // net_amount: None, // status: None, // error_message: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // error_code: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::ConfirmUpdate { // amount, // currency, // authentication_type, // capture_method, // status, // payment_method, // browser_info, // connector, // payment_token, // payment_method_data, // payment_method_type, // payment_experience, // business_sub_label, // straight_through_algorithm, // error_code, // error_message, // amount_capturable, // updated_by, // merchant_connector_id, // surcharge_amount, // tax_amount, // external_three_ds_authentication_attempted, // authentication_connector, // authentication_id, // payment_method_billing_address_id, // fingerprint_id, // payment_method_id, // client_source, // client_version, // customer_acceptance, // } => Self { // authentication_type, // status: Some(status), // modified_at: common_utils::date_time::now(), // browser_info, // payment_token, // payment_method_data, // payment_experience, // straight_through_algorithm, // error_code, // error_message, // amount_capturable, // updated_by, // merchant_connector_id: merchant_connector_id.map(Some), // surcharge_amount, // tax_amount, // external_three_ds_authentication_attempted, // authentication_connector, // authentication_id, // payment_method_billing_address_id, // fingerprint_id, // payment_method_id, // client_source, // client_version, // customer_acceptance, // net_amount: None, // cancellation_reason: None, // connector_metadata: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // charge_id: None, // card_network: None, // }, // PaymentAttemptUpdate::VoidUpdate { // status, // cancellation_reason, // updated_by, // } => Self { // status: Some(status), // cancellation_reason, // modified_at: common_utils::date_time::now(), // updated_by, // net_amount: None, // authentication_type: None, // error_message: None, // payment_method_id: None, // browser_info: None, // payment_token: None, // error_code: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::RejectUpdate { // status, // error_code, // error_message, // updated_by, // } => Self { // status: Some(status), // modified_at: common_utils::date_time::now(), // error_code, // error_message, // updated_by, // net_amount: None, // authentication_type: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::BlocklistUpdate { // status, // error_code, // error_message, // updated_by, // } => Self { // status: Some(status), // modified_at: common_utils::date_time::now(), // error_code, // error_message, // updated_by, // merchant_connector_id: Some(None), // net_amount: None, // authentication_type: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::ConnectorMandateDetailUpdate { // connector_mandate_detail, // updated_by, // } => Self { // payment_method_id: None, // modified_at: common_utils::date_time::now(), // updated_by, // amount: None, // net_amount: None, // currency: None, // status: None, // connector_transaction_id: None, // amount_to_capture: None, // connector: None, // authentication_type: None, // payment_method: None, // error_message: None, // cancellation_reason: None, // mandate_id: None, // browser_info: None, // payment_token: None, // error_code: None, // connector_metadata: None, // payment_method_data: None, // payment_method_type: None, // payment_experience: None, // business_sub_label: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // capture_method: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // shipping_cost: None, // order_tax_amount: None, // processor_transaction_data: None, // connector_mandate_detail, // }, // PaymentAttemptUpdate::ConnectorMandateDetailUpdate { // payment_method_id, // updated_by, // } => Self { // payment_method_id, // modified_at: common_utils::date_time::now(), // updated_by, // net_amount: None, // status: None, // authentication_type: None, // error_message: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // error_code: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::ResponseUpdate { // status, // connector, // connector_transaction_id, // authentication_type, // payment_method_id, // mandate_id, // connector_metadata, // payment_token, // error_code, // error_message, // error_reason, // connector_response_reference_id, // amount_capturable, // updated_by, // authentication_data, // encoded_data, // unified_code, // unified_message, // payment_method_data, // charge_id, // } => Self { // status: Some(status), // authentication_type, // payment_method_id, // modified_at: common_utils::date_time::now(), // connector_metadata, // error_code, // error_message, // payment_token, // error_reason, // connector_response_reference_id, // amount_capturable, // updated_by, // authentication_data, // encoded_data, // unified_code, // unified_message, // payment_method_data, // charge_id, // net_amount: None, // cancellation_reason: None, // browser_info: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // merchant_connector_id: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::ErrorUpdate { // connector, // status, // error_code, // error_message, // error_reason, // amount_capturable, // updated_by, // unified_code, // unified_message, // connector_transaction_id, // payment_method_data, // authentication_type, // } => Self { // status: Some(status), // error_message, // error_code, // modified_at: common_utils::date_time::now(), // error_reason, // amount_capturable, // updated_by, // unified_code, // unified_message, // payment_method_data, // authentication_type, // net_amount: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // connector_metadata: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self { // status: Some(status), // modified_at: common_utils::date_time::now(), // updated_by, // net_amount: None, // authentication_type: None, // error_message: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // error_code: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::UpdateTrackers { // payment_token, // connector, // straight_through_algorithm, // amount_capturable, // surcharge_amount, // tax_amount, // updated_by, // merchant_connector_id, // } => Self { // payment_token, // modified_at: common_utils::date_time::now(), // straight_through_algorithm, // amount_capturable, // surcharge_amount, // tax_amount, // updated_by, // merchant_connector_id: merchant_connector_id.map(Some), // net_amount: None, // status: None, // authentication_type: None, // error_message: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // error_code: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::UnresolvedResponseUpdate { // status, // connector, // connector_transaction_id, // payment_method_id, // error_code, // error_message, // error_reason, // connector_response_reference_id, // updated_by, // } => Self { // status: Some(status), // payment_method_id, // modified_at: common_utils::date_time::now(), // error_code, // error_message, // error_reason, // connector_response_reference_id, // updated_by, // net_amount: None, // authentication_type: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::PreprocessingUpdate { // status, // payment_method_id, // connector_metadata, // preprocessing_step_id, // connector_transaction_id, // connector_response_reference_id, // updated_by, // } => Self { // status: Some(status), // payment_method_id, // modified_at: common_utils::date_time::now(), // connector_metadata, // preprocessing_step_id, // connector_response_reference_id, // updated_by, // net_amount: None, // authentication_type: None, // error_message: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // error_code: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // error_reason: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::CaptureUpdate { // multiple_capture_count, // updated_by, // amount_to_capture, // } => Self { // multiple_capture_count, // modified_at: common_utils::date_time::now(), // updated_by, // net_amount: None, // status: None, // authentication_type: None, // error_message: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // error_code: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::AmountToCaptureUpdate { // status, // amount_capturable, // updated_by, // } => Self { // status: Some(status), // modified_at: common_utils::date_time::now(), // amount_capturable: Some(amount_capturable), // updated_by, // net_amount: None, // authentication_type: None, // error_message: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // error_code: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::ConnectorResponse { // authentication_data, // encoded_data, // connector_transaction_id, // connector, // updated_by, // charge_id, // } => Self { // authentication_data, // encoded_data, // modified_at: common_utils::date_time::now(), // updated_by, // charge_id, // net_amount: None, // status: None, // authentication_type: None, // error_message: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // error_code: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { // amount, // amount_capturable, // } => Self { // modified_at: common_utils::date_time::now(), // amount_capturable: Some(amount_capturable), // net_amount: None, // status: None, // authentication_type: None, // error_message: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // error_code: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // updated_by: String::default(), // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::AuthenticationUpdate { // status, // external_three_ds_authentication_attempted, // authentication_connector, // authentication_id, // updated_by, // } => Self { // status: Some(status), // modified_at: common_utils::date_time::now(), // external_three_ds_authentication_attempted, // authentication_connector, // authentication_id, // updated_by, // net_amount: None, // authentication_type: None, // error_message: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // error_code: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // error_reason: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // unified_code: None, // unified_message: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // PaymentAttemptUpdate::ManualUpdate { // status, // error_code, // error_message, // error_reason, // updated_by, // unified_code, // unified_message, // connector_transaction_id, // } => Self { // status, // error_code: error_code.map(Some), // modified_at: common_utils::date_time::now(), // error_message: error_message.map(Some), // error_reason: error_reason.map(Some), // updated_by, // unified_code: unified_code.map(Some), // unified_message: unified_message.map(Some), // net_amount: None, // authentication_type: None, // payment_method_id: None, // cancellation_reason: None, // browser_info: None, // payment_token: None, // connector_metadata: None, // payment_method_data: None, // payment_experience: None, // straight_through_algorithm: None, // preprocessing_step_id: None, // connector_response_reference_id: None, // multiple_capture_count: None, // surcharge_amount: None, // tax_amount: None, // amount_capturable: None, // merchant_connector_id: None, // authentication_data: None, // encoded_data: None, // external_three_ds_authentication_attempted: None, // authentication_connector: None, // authentication_id: None, // fingerprint_id: None, // payment_method_billing_address_id: None, // charge_id: None, // client_source: None, // client_version: None, // customer_acceptance: None, // card_network: None, // }, // } } } #[cfg(feature = "v1")] impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { fn from(payment_attempt_update: PaymentAttemptUpdate) -> Self { match payment_attempt_update { PaymentAttemptUpdate::Update { amount, currency, status, // connector_transaction_id, authentication_type, payment_method, payment_token, payment_method_data, payment_method_type, payment_experience, business_sub_label, amount_to_capture, capture_method, surcharge_amount, tax_amount, fingerprint_id, updated_by, payment_method_billing_address_id, network_transaction_id, } => Self { amount: Some(amount), currency: Some(currency), status: Some(status), // connector_transaction_id, authentication_type, payment_method, payment_token, modified_at: common_utils::date_time::now(), payment_method_data, payment_method_type, payment_experience, business_sub_label, amount_to_capture, capture_method, surcharge_amount, tax_amount, fingerprint_id, payment_method_billing_address_id, updated_by, net_amount: None, connector_transaction_id: None, connector: None, error_message: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, error_code: None, connector_metadata: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, connector_response_reference_id: None, multiple_capture_count: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, capture_before: None, extended_authorization_applied: None, order_tax_amount: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::AuthenticationTypeUpdate { authentication_type, updated_by, } => Self { authentication_type: Some(authentication_type), modified_at: common_utils::date_time::now(), updated_by, amount: None, net_amount: None, currency: None, status: None, connector_transaction_id: None, amount_to_capture: None, connector: None, payment_method: None, error_message: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, error_code: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, order_tax_amount: None, capture_before: None, extended_authorization_applied: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::ConfirmUpdate { amount, currency, authentication_type, capture_method, status, payment_method, browser_info, connector, payment_token, payment_method_data, payment_method_type, payment_experience, business_sub_label, straight_through_algorithm, error_code, error_message, updated_by, merchant_connector_id, surcharge_amount, tax_amount, external_three_ds_authentication_attempted, authentication_connector, authentication_id, payment_method_billing_address_id, fingerprint_id, payment_method_id, client_source, client_version, customer_acceptance, shipping_cost, order_tax_amount, connector_mandate_detail, card_discovery, routing_approach, connector_request_reference_id, network_transaction_id, is_stored_credential, request_extended_authorization, } => Self { amount: Some(amount), currency: Some(currency), authentication_type, status: Some(status), payment_method, modified_at: common_utils::date_time::now(), browser_info, connector: connector.map(Some), payment_token, payment_method_data, payment_method_type, payment_experience, business_sub_label, straight_through_algorithm, error_code, error_message, amount_capturable: None, updated_by, merchant_connector_id: merchant_connector_id.map(Some), surcharge_amount, tax_amount, external_three_ds_authentication_attempted, authentication_connector, authentication_id, payment_method_billing_address_id, fingerprint_id, payment_method_id, capture_method, client_source, client_version, customer_acceptance, net_amount: None, connector_transaction_id: None, amount_to_capture: None, cancellation_reason: None, mandate_id: None, connector_metadata: None, preprocessing_step_id: None, error_reason: None, connector_response_reference_id: None, multiple_capture_count: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, card_network: None, shipping_cost, order_tax_amount, capture_before: None, extended_authorization_applied: None, processor_transaction_data: None, connector_mandate_detail, card_discovery, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach, connector_request_reference_id, network_transaction_id, is_overcapture_enabled: None, network_details: None, is_stored_credential, request_extended_authorization, authorized_amount: None, }, PaymentAttemptUpdate::VoidUpdate { status, cancellation_reason, updated_by, } => Self { status: Some(status), cancellation_reason, modified_at: common_utils::date_time::now(), updated_by, amount: None, net_amount: None, currency: None, connector_transaction_id: None, amount_to_capture: None, connector: None, authentication_type: None, payment_method: None, error_message: None, payment_method_id: None, mandate_id: None, browser_info: None, payment_token: None, error_code: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, order_tax_amount: None, capture_before: None, extended_authorization_applied: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::RejectUpdate { status, error_code, error_message, updated_by, } => Self { status: Some(status), modified_at: common_utils::date_time::now(), error_code, error_message, updated_by, amount: None, net_amount: None, currency: None, connector_transaction_id: None, amount_to_capture: None, connector: None, authentication_type: None, payment_method: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, order_tax_amount: None, capture_before: None, extended_authorization_applied: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::BlocklistUpdate { status, error_code, error_message, updated_by, } => Self { status: Some(status), modified_at: common_utils::date_time::now(), error_code, connector: Some(None), error_message, updated_by, merchant_connector_id: Some(None), amount: None, net_amount: None, currency: None, connector_transaction_id: None, amount_to_capture: None, authentication_type: None, payment_method: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, order_tax_amount: None, capture_before: None, extended_authorization_applied: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::ConnectorMandateDetailUpdate { connector_mandate_detail, updated_by, } => Self { payment_method_id: None, modified_at: common_utils::date_time::now(), updated_by, amount: None, net_amount: None, currency: None, status: None, connector_transaction_id: None, amount_to_capture: None, connector: None, authentication_type: None, payment_method: None, error_message: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, error_code: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, order_tax_amount: None, capture_before: None, extended_authorization_applied: None, processor_transaction_data: None, connector_mandate_detail, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::PaymentMethodDetailsUpdate { payment_method_id, updated_by, } => Self { payment_method_id, modified_at: common_utils::date_time::now(), updated_by, amount: None, net_amount: None, currency: None, status: None, connector_transaction_id: None, amount_to_capture: None, connector: None, authentication_type: None, payment_method: None, error_message: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, error_code: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, order_tax_amount: None, capture_before: None, extended_authorization_applied: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::ResponseUpdate { status, connector, connector_transaction_id, authentication_type, payment_method_id, mandate_id, connector_metadata, payment_token, error_code, error_message, error_reason, connector_response_reference_id, amount_capturable, updated_by, authentication_data, encoded_data, unified_code, unified_message, capture_before, extended_authorization_applied, payment_method_data, connector_mandate_detail, charges, setup_future_usage_applied, network_transaction_id, is_overcapture_enabled, authorized_amount, } => { let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { status: Some(status), connector: connector.map(Some), connector_transaction_id, authentication_type, payment_method_id, modified_at: common_utils::date_time::now(), mandate_id, connector_metadata, error_code, error_message, payment_token, error_reason, connector_response_reference_id, amount_capturable, updated_by, authentication_data, encoded_data, unified_code, unified_message, payment_method_data, processor_transaction_data, connector_mandate_detail, charges, amount: None, net_amount: None, currency: None, amount_to_capture: None, payment_method: None, cancellation_reason: None, browser_info: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, capture_method: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, merchant_connector_id: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, capture_before, extended_authorization_applied, shipping_cost: None, order_tax_amount: None, card_discovery: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied, routing_approach: None, connector_request_reference_id: None, network_transaction_id, is_overcapture_enabled, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount, } } PaymentAttemptUpdate::ErrorUpdate { connector, status, error_code, error_message, error_reason, amount_capturable, updated_by, unified_code, unified_message, connector_transaction_id, payment_method_data, authentication_type, issuer_error_code, issuer_error_message, network_details, } => { let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { connector: connector.map(Some), status: Some(status), error_message, error_code, modified_at: common_utils::date_time::now(), error_reason, amount_capturable, updated_by, unified_code, unified_message, connector_transaction_id, payment_method_data, authentication_type, processor_transaction_data, issuer_error_code, issuer_error_message, amount: None, net_amount: None, currency: None, amount_to_capture: None, payment_method: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, connector_metadata: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, capture_before: None, extended_authorization_applied: None, shipping_cost: None, order_tax_amount: None, connector_mandate_detail: None, card_discovery: None, charges: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, } } PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self { status: Some(status), modified_at: common_utils::date_time::now(), updated_by, amount: None, net_amount: None, currency: None, connector_transaction_id: None, amount_to_capture: None, connector: None, authentication_type: None, payment_method: None, error_message: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, error_code: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, capture_before: None, extended_authorization_applied: None, order_tax_amount: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::UpdateTrackers { payment_token, connector, straight_through_algorithm, amount_capturable, surcharge_amount, tax_amount, updated_by, merchant_connector_id, routing_approach, is_stored_credential, } => Self { payment_token, modified_at: common_utils::date_time::now(), connector: connector.map(Some), straight_through_algorithm, amount_capturable, surcharge_amount, tax_amount, updated_by, merchant_connector_id: merchant_connector_id.map(Some), amount: None, net_amount: None, currency: None, status: None, connector_transaction_id: None, amount_to_capture: None, authentication_type: None, payment_method: None, error_message: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, error_code: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, capture_before: None, extended_authorization_applied: None, order_tax_amount: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::UnresolvedResponseUpdate { status, connector, connector_transaction_id, payment_method_id, error_code, error_message, error_reason, connector_response_reference_id, updated_by, } => { let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { status: Some(status), connector: connector.map(Some), connector_transaction_id, payment_method_id, modified_at: common_utils::date_time::now(), error_code, error_message, error_reason, connector_response_reference_id, updated_by, processor_transaction_data, amount: None, net_amount: None, currency: None, amount_to_capture: None, authentication_type: None, payment_method: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, capture_method: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, capture_before: None, extended_authorization_applied: None, order_tax_amount: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, } } PaymentAttemptUpdate::PreprocessingUpdate { status, payment_method_id, connector_metadata, preprocessing_step_id, connector_transaction_id, connector_response_reference_id, updated_by, } => { let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { status: Some(status), payment_method_id, modified_at: common_utils::date_time::now(), connector_metadata, preprocessing_step_id, connector_transaction_id, connector_response_reference_id, updated_by, processor_transaction_data, amount: None, net_amount: None, currency: None, amount_to_capture: None, connector: None, authentication_type: None, payment_method: None, error_message: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, error_code: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, error_reason: None, capture_method: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, capture_before: None, extended_authorization_applied: None, shipping_cost: None, order_tax_amount: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, } } PaymentAttemptUpdate::CaptureUpdate { multiple_capture_count, updated_by, amount_to_capture, } => Self { multiple_capture_count, modified_at: common_utils::date_time::now(), updated_by, amount_to_capture, amount: None, net_amount: None, currency: None, status: None, connector_transaction_id: None, connector: None, authentication_type: None, payment_method: None, error_message: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, error_code: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, order_tax_amount: None, capture_before: None, extended_authorization_applied: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::AmountToCaptureUpdate { status, amount_capturable, updated_by, } => Self { status: Some(status), modified_at: common_utils::date_time::now(), amount_capturable: Some(amount_capturable), updated_by, amount: None, net_amount: None, currency: None, connector_transaction_id: None, amount_to_capture: None, connector: None, authentication_type: None, payment_method: None, error_message: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, error_code: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, capture_before: None, extended_authorization_applied: None, order_tax_amount: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::ConnectorResponse { authentication_data, encoded_data, connector_transaction_id, connector, updated_by, charges, } => { let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { authentication_data, encoded_data, connector_transaction_id, connector: connector.map(Some), modified_at: common_utils::date_time::now(), updated_by, processor_transaction_data, charges, amount: None, net_amount: None, currency: None, status: None, amount_to_capture: None, authentication_type: None, payment_method: None, error_message: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, error_code: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, capture_before: None, extended_authorization_applied: None, order_tax_amount: None, connector_mandate_detail: None, card_discovery: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, } } PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { amount, amount_capturable, } => Self { amount: Some(amount), modified_at: common_utils::date_time::now(), amount_capturable: Some(amount_capturable), net_amount: None, currency: None, status: None, connector_transaction_id: None, amount_to_capture: None, connector: None, authentication_type: None, payment_method: None, error_message: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, error_code: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, updated_by: String::default(), merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, order_tax_amount: None, capture_before: None, extended_authorization_applied: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::AuthenticationUpdate { status, external_three_ds_authentication_attempted, authentication_connector, authentication_id, updated_by, } => Self { status: Some(status), modified_at: common_utils::date_time::now(), external_three_ds_authentication_attempted, authentication_connector, authentication_id, updated_by, amount: None, net_amount: None, currency: None, connector_transaction_id: None, amount_to_capture: None, connector: None, authentication_type: None, payment_method: None, error_message: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, error_code: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, order_tax_amount: None, capture_before: None, extended_authorization_applied: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, PaymentAttemptUpdate::ManualUpdate { status, error_code, error_message, error_reason, updated_by, unified_code, unified_message, connector_transaction_id, } => { let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { status, error_code: error_code.map(Some), modified_at: common_utils::date_time::now(), error_message: error_message.map(Some), error_reason: error_reason.map(Some), updated_by, unified_code: unified_code.map(Some), unified_message: unified_message.map(Some), connector_transaction_id, processor_transaction_data, amount: None, net_amount: None, currency: None, amount_to_capture: None, connector: None, authentication_type: None, payment_method: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, connector_metadata: None, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, capture_before: None, extended_authorization_applied: None, order_tax_amount: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, } } PaymentAttemptUpdate::PostSessionTokensUpdate { updated_by, connector_metadata, } => Self { status: None, error_code: None, modified_at: common_utils::date_time::now(), error_message: None, error_reason: None, updated_by, unified_code: None, unified_message: None, amount: None, net_amount: None, currency: None, connector_transaction_id: None, amount_to_capture: None, connector: None, authentication_type: None, payment_method: None, payment_method_id: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, connector_metadata, payment_method_data: None, payment_method_type: None, payment_experience: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, capture_method: None, connector_response_reference_id: None, multiple_capture_count: None, surcharge_amount: None, tax_amount: None, amount_capturable: None, merchant_connector_id: None, authentication_data: None, encoded_data: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, fingerprint_id: None, payment_method_billing_address_id: None, client_source: None, client_version: None, customer_acceptance: None, card_network: None, shipping_cost: None, order_tax_amount: None, capture_before: None, extended_authorization_applied: None, processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, issuer_error_code: None, issuer_error_message: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, is_overcapture_enabled: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, authorized_amount: None, }, } } } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub enum RedirectForm { Form { endpoint: String, method: common_utils::request::Method, form_fields: std::collections::HashMap<String, String>, }, Html { html_data: String, }, BarclaycardAuthSetup { access_token: String, ddc_url: String, reference_id: String, }, BarclaycardConsumerAuth { access_token: String, step_up_url: String, }, BlueSnap { payment_fields_token: String, }, CybersourceAuthSetup { access_token: String, ddc_url: String, reference_id: String, }, CybersourceConsumerAuth { access_token: String, step_up_url: String, }, DeutschebankThreeDSChallengeFlow { acs_url: String, creq: String, }, Payme, Braintree { client_token: String, card_token: String, bin: String, acs_url: String, }, Nmi { amount: String, currency: common_enums::Currency, public_key: masking::Secret<String>, customer_vault_id: String, order_id: String, }, Mifinity { initialization_token: String, }, WorldpayDDCForm { endpoint: common_utils::types::Url, method: common_utils::request::Method, form_fields: std::collections::HashMap<String, String>, collection_id: Option<String>, }, } common_utils::impl_to_sql_from_sql_json!(RedirectForm); #[cfg(feature = "v2")] #[derive( Clone, Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq, diesel::AsExpression, )] #[diesel(sql_type = diesel::pg::sql_types::Jsonb)] pub struct PaymentAttemptFeatureMetadata { pub revenue_recovery: Option<PaymentAttemptRecoveryData>, } #[cfg(feature = "v2")] #[derive( Clone, Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq, diesel::AsExpression, )] #[diesel(sql_type = diesel::pg::sql_types::Jsonb)] pub struct PaymentAttemptRecoveryData { pub attempt_triggered_by: common_enums::TriggeredBy, // stripe specific field used to identify duplicate attempts. pub charge_id: Option<String>, } #[cfg(feature = "v2")] common_utils::impl_to_sql_from_sql_json!(PaymentAttemptFeatureMetadata); mod tests { #[test] fn test_backwards_compatibility() { let serialized_payment_attempt = r#"{ "payment_id": "PMT123456789", "merchant_id": "M123456789", "attempt_id": "ATMPT123456789", "status": "pending", "amount": 10000, "currency": "USD", "save_to_locker": true, "connector": "stripe", "error_message": null, "offer_amount": 9500, "surcharge_amount": 500, "tax_amount": 800, "payment_method_id": "CRD123456789", "payment_method": "card", "connector_transaction_id": "CNTR123456789", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "confirm": false, "authentication_type": "no_three_ds", "created_at": "2024-02-26T12:00:00Z", "modified_at": "2024-02-26T12:00:00Z", "last_synced": null, "cancellation_reason": null, "amount_to_capture": 10000, "mandate_id": null, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "error_code": null, "payment_token": "TOKEN123456789", "connector_metadata": null, "payment_experience": "redirect_to_url", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_cvc": "123", "card_exp_year": "2024", "card_holder_name": "John Doe" } }, "business_sub_label": "Premium", "straight_through_algorithm": null, "preprocessing_step_id": null, "mandate_details": null, "error_reason": null, "multiple_capture_count": 0, "connector_response_reference_id": null, "amount_capturable": 10000, "updated_by": "redis_kv", "merchant_connector_id": "MCN123456789", "authentication_data": null, "encoded_data": null, "unified_code": null, "unified_message": null, "net_amount": 10200, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "single_use": { "amount": 6540, "currency": "USD" } } }, "fingerprint_id": null }"#; let deserialized = serde_json::from_str::<super::PaymentAttempt>(serialized_payment_attempt); assert!(deserialized.is_ok()); } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/payment_attempt.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 12, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-3624515359449711328
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/events.rs // Contains: 3 structs, 1 enums use common_utils::{custom_serde, encryption::Encryption}; use diesel::{ expression::AsExpression, AsChangeset, Identifiable, Insertable, Queryable, Selectable, }; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::events}; #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = events)] pub struct EventNew { pub event_id: String, pub event_type: storage_enums::EventType, pub event_class: storage_enums::EventClass, pub is_webhook_notified: bool, pub primary_object_id: String, pub primary_object_type: storage_enums::EventObjectType, pub created_at: PrimitiveDateTime, pub merchant_id: Option<common_utils::id_type::MerchantId>, pub business_profile_id: Option<common_utils::id_type::ProfileId>, pub primary_object_created_at: Option<PrimitiveDateTime>, pub idempotent_event_id: Option<String>, pub initial_attempt_id: Option<String>, pub request: Option<Encryption>, pub response: Option<Encryption>, pub delivery_attempt: Option<storage_enums::WebhookDeliveryAttempt>, pub metadata: Option<EventMetadata>, pub is_overall_delivery_successful: Option<bool>, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = events)] pub struct EventUpdateInternal { pub is_webhook_notified: Option<bool>, pub response: Option<Encryption>, pub is_overall_delivery_successful: Option<bool>, } #[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable, Selectable)] #[diesel(table_name = events, primary_key(event_id), check_for_backend(diesel::pg::Pg))] pub struct Event { pub event_id: String, pub event_type: storage_enums::EventType, pub event_class: storage_enums::EventClass, pub is_webhook_notified: bool, pub primary_object_id: String, pub primary_object_type: storage_enums::EventObjectType, #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, pub merchant_id: Option<common_utils::id_type::MerchantId>, pub business_profile_id: Option<common_utils::id_type::ProfileId>, // This column can be used to partition the database table, so that all events related to a // single object would reside in the same partition pub primary_object_created_at: Option<PrimitiveDateTime>, pub idempotent_event_id: Option<String>, pub initial_attempt_id: Option<String>, pub request: Option<Encryption>, pub response: Option<Encryption>, pub delivery_attempt: Option<storage_enums::WebhookDeliveryAttempt>, pub metadata: Option<EventMetadata>, pub is_overall_delivery_successful: Option<bool>, } #[derive(Clone, Debug, Deserialize, Serialize, AsExpression, diesel::FromSqlRow)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub enum EventMetadata { #[cfg(feature = "v1")] Payment { payment_id: common_utils::id_type::PaymentId, }, #[cfg(feature = "v2")] Payment { payment_id: common_utils::id_type::GlobalPaymentId, }, Payout { payout_id: common_utils::id_type::PayoutId, }, #[cfg(feature = "v1")] Refund { payment_id: common_utils::id_type::PaymentId, refund_id: String, }, #[cfg(feature = "v2")] Refund { payment_id: common_utils::id_type::GlobalPaymentId, refund_id: common_utils::id_type::GlobalRefundId, }, #[cfg(feature = "v1")] Dispute { payment_id: common_utils::id_type::PaymentId, attempt_id: String, dispute_id: String, }, #[cfg(feature = "v2")] Dispute { payment_id: common_utils::id_type::GlobalPaymentId, attempt_id: String, dispute_id: String, }, Mandate { payment_method_id: String, mandate_id: String, }, } common_utils::impl_to_sql_from_sql_json!(EventMetadata);
{ "crate": "diesel_models", "file": "crates/diesel_models/src/events.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_5431206795419590751
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/organization.rs // Contains: 6 structs, 0 enums use common_utils::{id_type, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; #[cfg(feature = "v1")] use crate::schema::organization; #[cfg(feature = "v2")] use crate::schema_v2::organization; pub trait OrganizationBridge { fn get_organization_id(&self) -> id_type::OrganizationId; fn get_organization_name(&self) -> Option<String>; fn set_organization_name(&mut self, organization_name: String); } #[cfg(feature = "v1")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel( table_name = organization, primary_key(org_id), check_for_backend(diesel::pg::Pg) )] pub struct Organization { org_id: id_type::OrganizationId, org_name: Option<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, #[allow(dead_code)] id: Option<id_type::OrganizationId>, #[allow(dead_code)] organization_name: Option<String>, pub version: common_enums::ApiVersion, pub organization_type: Option<common_enums::OrganizationType>, pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel( table_name = organization, primary_key(id), check_for_backend(diesel::pg::Pg) )] pub struct Organization { pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, id: id_type::OrganizationId, organization_name: Option<String>, pub version: common_enums::ApiVersion, pub organization_type: Option<common_enums::OrganizationType>, pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] impl Organization { pub fn new(org_new: OrganizationNew) -> Self { let OrganizationNew { org_id, org_name, organization_details, metadata, created_at, modified_at, id: _, organization_name: _, version, organization_type, platform_merchant_id, } = org_new; Self { id: Some(org_id.clone()), organization_name: org_name.clone(), org_id, org_name, organization_details, metadata, created_at, modified_at, version, organization_type: Some(organization_type), platform_merchant_id, } } pub fn get_organization_type(&self) -> common_enums::OrganizationType { self.organization_type.unwrap_or_default() } } #[cfg(feature = "v2")] impl Organization { pub fn new(org_new: OrganizationNew) -> Self { let OrganizationNew { id, organization_name, organization_details, metadata, created_at, modified_at, version, organization_type, platform_merchant_id, } = org_new; Self { id, organization_name, organization_details, metadata, created_at, modified_at, version, organization_type: Some(organization_type), platform_merchant_id, } } pub fn get_organization_type(&self) -> common_enums::OrganizationType { self.organization_type.unwrap_or_default() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable)] #[diesel(table_name = organization, primary_key(org_id))] pub struct OrganizationNew { org_id: id_type::OrganizationId, org_name: Option<String>, id: id_type::OrganizationId, organization_name: Option<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub version: common_enums::ApiVersion, pub organization_type: common_enums::OrganizationType, pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable)] #[diesel(table_name = organization, primary_key(id))] pub struct OrganizationNew { id: id_type::OrganizationId, organization_name: Option<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub version: common_enums::ApiVersion, pub organization_type: common_enums::OrganizationType, pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] impl OrganizationNew { pub fn new( id: id_type::OrganizationId, organization_type: common_enums::OrganizationType, organization_name: Option<String>, ) -> Self { Self { org_id: id.clone(), org_name: organization_name.clone(), id, organization_name, organization_details: None, metadata: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), version: common_types::consts::API_VERSION, organization_type, platform_merchant_id: None, } } } #[cfg(feature = "v2")] impl OrganizationNew { pub fn new( id: id_type::OrganizationId, organization_type: common_enums::OrganizationType, organization_name: Option<String>, ) -> Self { Self { id, organization_name, organization_details: None, metadata: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), version: common_types::consts::API_VERSION, organization_type, platform_merchant_id: None, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset)] #[diesel(table_name = organization)] pub struct OrganizationUpdateInternal { org_name: Option<String>, organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, modified_at: time::PrimitiveDateTime, platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset)] #[diesel(table_name = organization)] pub struct OrganizationUpdateInternal { organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, modified_at: time::PrimitiveDateTime, platform_merchant_id: Option<id_type::MerchantId>, } pub enum OrganizationUpdate { Update { organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, platform_merchant_id: Option<id_type::MerchantId>, }, } #[cfg(feature = "v1")] impl From<OrganizationUpdate> for OrganizationUpdateInternal { fn from(value: OrganizationUpdate) -> Self { match value { OrganizationUpdate::Update { organization_name, organization_details, metadata, platform_merchant_id, } => Self { org_name: organization_name.clone(), organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), platform_merchant_id, }, } } } #[cfg(feature = "v2")] impl From<OrganizationUpdate> for OrganizationUpdateInternal { fn from(value: OrganizationUpdate) -> Self { match value { OrganizationUpdate::Update { organization_name, organization_details, metadata, platform_merchant_id, } => Self { organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), platform_merchant_id, }, } } } #[cfg(feature = "v1")] impl OrganizationBridge for Organization { fn get_organization_id(&self) -> id_type::OrganizationId { self.org_id.clone() } fn get_organization_name(&self) -> Option<String> { self.org_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.org_name = Some(organization_name); } } #[cfg(feature = "v1")] impl OrganizationBridge for OrganizationNew { fn get_organization_id(&self) -> id_type::OrganizationId { self.org_id.clone() } fn get_organization_name(&self) -> Option<String> { self.org_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.org_name = Some(organization_name); } } #[cfg(feature = "v2")] impl OrganizationBridge for Organization { fn get_organization_id(&self) -> id_type::OrganizationId { self.id.clone() } fn get_organization_name(&self) -> Option<String> { self.organization_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.organization_name = Some(organization_name); } } #[cfg(feature = "v2")] impl OrganizationBridge for OrganizationNew { fn get_organization_id(&self) -> id_type::OrganizationId { self.id.clone() } fn get_organization_name(&self) -> Option<String> { self.organization_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.organization_name = Some(organization_name); } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/organization.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-649364747495017461
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/merchant_account.rs // Contains: 6 structs, 0 enums use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::enums as storage_enums; #[cfg(feature = "v1")] use crate::schema::merchant_account; #[cfg(feature = "v2")] use crate::schema_v2::merchant_account; /// Note: The order of fields in the struct is important. /// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile /// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged #[cfg(feature = "v1")] #[derive( Clone, Debug, serde::Deserialize, Identifiable, serde::Serialize, Queryable, Selectable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_account, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantAccount { merchant_id: common_utils::id_type::MerchantId, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: storage_enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub id: Option<common_utils::id_type::MerchantId>, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: Option<common_enums::MerchantAccountType>, } #[cfg(feature = "v1")] pub struct MerchantAccountSetter { pub merchant_id: common_utils::id_type::MerchantId, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: storage_enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { Self { id: Some(item.merchant_id.clone()), merchant_id: item.merchant_id, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item.merchant_name, merchant_details: item.merchant_details, webhook_details: item.webhook_details, sub_merchants_enabled: item.sub_merchants_enabled, parent_merchant_id: item.parent_merchant_id, publishable_key: item.publishable_key, storage_scheme: item.storage_scheme, locker_id: item.locker_id, metadata: item.metadata, routing_algorithm: item.routing_algorithm, primary_business_details: item.primary_business_details, intent_fulfillment_time: item.intent_fulfillment_time, created_at: item.created_at, modified_at: item.modified_at, frm_routing_algorithm: item.frm_routing_algorithm, payout_routing_algorithm: item.payout_routing_algorithm, organization_id: item.organization_id, is_recon_enabled: item.is_recon_enabled, default_profile: item.default_profile, recon_status: item.recon_status, payment_link_config: item.payment_link_config, pm_collect_link_config: item.pm_collect_link_config, version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, merchant_account_type: Some(item.merchant_account_type), } } } /// Note: The order of fields in the struct is important. /// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile /// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged #[cfg(feature = "v2")] #[derive( Clone, Debug, serde::Deserialize, Identifiable, serde::Serialize, Queryable, router_derive::DebugAsDisplay, Selectable, )] #[diesel(table_name = merchant_account, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct MerchantAccount { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: storage_enums::ReconStatus, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub id: common_utils::id_type::MerchantId, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: Option<common_enums::MerchantAccountType>, } #[cfg(feature = "v2")] impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { Self { id: item.id, merchant_name: item.merchant_name, merchant_details: item.merchant_details, publishable_key: item.publishable_key, storage_scheme: item.storage_scheme, metadata: item.metadata, created_at: item.created_at, modified_at: item.modified_at, organization_id: item.organization_id, recon_status: item.recon_status, version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, merchant_account_type: Some(item.merchant_account_type), } } } #[cfg(feature = "v2")] pub struct MerchantAccountSetter { pub id: common_utils::id_type::MerchantId, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: storage_enums::ReconStatus, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } impl MerchantAccount { #[cfg(feature = "v1")] /// Get the unique identifier of MerchantAccount pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.merchant_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.id } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountNew { pub merchant_id: common_utils::id_type::MerchantId, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub return_url: Option<String>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub publishable_key: Option<String>, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: storage_enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub id: Option<common_utils::id_type::MerchantId>, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountNew { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: storage_enums::ReconStatus, pub id: common_utils::id_type::MerchantId, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountUpdateInternal { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub storage_scheme: Option<storage_enums::MerchantStorageScheme>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: time::PrimitiveDateTime, pub organization_id: Option<common_utils::id_type::OrganizationId>, pub recon_status: Option<storage_enums::ReconStatus>, pub is_platform_account: Option<bool>, pub product_type: Option<common_enums::MerchantProductType>, } #[cfg(feature = "v2")] impl MerchantAccountUpdateInternal { pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount { let Self { merchant_name, merchant_details, publishable_key, storage_scheme, metadata, modified_at, organization_id, recon_status, is_platform_account, product_type, } = self; MerchantAccount { merchant_name: merchant_name.or(source.merchant_name), merchant_details: merchant_details.or(source.merchant_details), publishable_key: publishable_key.or(source.publishable_key), storage_scheme: storage_scheme.unwrap_or(source.storage_scheme), metadata: metadata.or(source.metadata), created_at: source.created_at, modified_at, organization_id: organization_id.unwrap_or(source.organization_id), recon_status: recon_status.unwrap_or(source.recon_status), version: source.version, id: source.id, is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), product_type: product_type.or(source.product_type), merchant_account_type: source.merchant_account_type, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountUpdateInternal { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub return_url: Option<String>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub publishable_key: Option<String>, pub storage_scheme: Option<storage_enums::MerchantStorageScheme>, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: Option<serde_json::Value>, pub modified_at: time::PrimitiveDateTime, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: Option<common_utils::id_type::OrganizationId>, pub is_recon_enabled: Option<bool>, pub default_profile: Option<Option<common_utils::id_type::ProfileId>>, pub recon_status: Option<storage_enums::ReconStatus>, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub is_platform_account: Option<bool>, pub product_type: Option<common_enums::MerchantProductType>, } #[cfg(feature = "v1")] impl MerchantAccountUpdateInternal { pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount { let Self { merchant_name, merchant_details, return_url, webhook_details, sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, publishable_key, storage_scheme, locker_id, metadata, routing_algorithm, primary_business_details, modified_at, intent_fulfillment_time, frm_routing_algorithm, payout_routing_algorithm, organization_id, is_recon_enabled, default_profile, recon_status, payment_link_config, pm_collect_link_config, is_platform_account, product_type, } = self; MerchantAccount { merchant_id: source.merchant_id, return_url: return_url.or(source.return_url), enable_payment_response_hash: enable_payment_response_hash .unwrap_or(source.enable_payment_response_hash), payment_response_hash_key: payment_response_hash_key .or(source.payment_response_hash_key), redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post .unwrap_or(source.redirect_to_merchant_with_http_post), merchant_name: merchant_name.or(source.merchant_name), merchant_details: merchant_details.or(source.merchant_details), webhook_details: webhook_details.or(source.webhook_details), sub_merchants_enabled: sub_merchants_enabled.or(source.sub_merchants_enabled), parent_merchant_id: parent_merchant_id.or(source.parent_merchant_id), publishable_key: publishable_key.or(source.publishable_key), storage_scheme: storage_scheme.unwrap_or(source.storage_scheme), locker_id: locker_id.or(source.locker_id), metadata: metadata.or(source.metadata), routing_algorithm: routing_algorithm.or(source.routing_algorithm), primary_business_details: primary_business_details .unwrap_or(source.primary_business_details), intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time), created_at: source.created_at, modified_at, frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm), payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm), organization_id: organization_id.unwrap_or(source.organization_id), is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), default_profile: default_profile.unwrap_or(source.default_profile), recon_status: recon_status.unwrap_or(source.recon_status), payment_link_config: payment_link_config.or(source.payment_link_config), pm_collect_link_config: pm_collect_link_config.or(source.pm_collect_link_config), version: source.version, is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), id: source.id, product_type: product_type.or(source.product_type), merchant_account_type: source.merchant_account_type, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/merchant_account.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_5278618629835479565
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/payouts.rs // Contains: 3 structs, 1 enums use common_utils::{pii, types::MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::payouts}; // Payouts #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = payouts, primary_key(payout_id), check_for_backend(diesel::pg::Pg))] pub struct Payouts { pub payout_id: common_utils::id_type::PayoutId, pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub address_id: Option<String>, pub payout_type: Option<storage_enums::PayoutType>, pub payout_method_id: Option<String>, pub amount: MinorUnit, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub description: Option<String>, pub recurring: bool, pub auto_fulfill: bool, pub return_url: Option<String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, pub attempt_count: i16, pub profile_id: common_utils::id_type::ProfileId, pub status: storage_enums::PayoutStatus, pub confirm: Option<bool>, pub payout_link_id: Option<String>, pub client_secret: Option<String>, pub priority: Option<storage_enums::PayoutSendPriority>, } #[derive( Clone, Debug, Eq, PartialEq, Insertable, serde::Serialize, serde::Deserialize, router_derive::DebugAsDisplay, router_derive::Setter, )] #[diesel(table_name = payouts)] pub struct PayoutsNew { pub payout_id: common_utils::id_type::PayoutId, pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub address_id: Option<String>, pub payout_type: Option<storage_enums::PayoutType>, pub payout_method_id: Option<String>, pub amount: MinorUnit, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub description: Option<String>, pub recurring: bool, pub auto_fulfill: bool, pub return_url: Option<String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, pub attempt_count: i16, pub profile_id: common_utils::id_type::ProfileId, pub status: storage_enums::PayoutStatus, pub confirm: Option<bool>, pub payout_link_id: Option<String>, pub client_secret: Option<String>, pub priority: Option<storage_enums::PayoutSendPriority>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PayoutsUpdate { Update { amount: MinorUnit, destination_currency: storage_enums::Currency, source_currency: storage_enums::Currency, description: Option<String>, recurring: bool, auto_fulfill: bool, return_url: Option<String>, entity_type: storage_enums::PayoutEntityType, metadata: Option<pii::SecretSerdeValue>, profile_id: Option<common_utils::id_type::ProfileId>, status: Option<storage_enums::PayoutStatus>, confirm: Option<bool>, payout_type: Option<storage_enums::PayoutType>, address_id: Option<String>, customer_id: Option<common_utils::id_type::CustomerId>, }, PayoutMethodIdUpdate { payout_method_id: String, }, RecurringUpdate { recurring: bool, }, AttemptCountUpdate { attempt_count: i16, }, StatusUpdate { status: storage_enums::PayoutStatus, }, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payouts)] pub struct PayoutsUpdateInternal { pub amount: Option<MinorUnit>, pub destination_currency: Option<storage_enums::Currency>, pub source_currency: Option<storage_enums::Currency>, pub description: Option<String>, pub recurring: Option<bool>, pub auto_fulfill: Option<bool>, pub return_url: Option<String>, pub entity_type: Option<storage_enums::PayoutEntityType>, pub metadata: Option<pii::SecretSerdeValue>, pub payout_method_id: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub status: Option<storage_enums::PayoutStatus>, pub last_modified_at: PrimitiveDateTime, pub attempt_count: Option<i16>, pub confirm: Option<bool>, pub payout_type: Option<common_enums::PayoutType>, pub address_id: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, } impl Default for PayoutsUpdateInternal { fn default() -> Self { Self { amount: None, destination_currency: None, source_currency: None, description: None, recurring: None, auto_fulfill: None, return_url: None, entity_type: None, metadata: None, payout_method_id: None, profile_id: None, status: None, last_modified_at: common_utils::date_time::now(), attempt_count: None, confirm: None, payout_type: None, address_id: None, customer_id: None, } } } impl From<PayoutsUpdate> for PayoutsUpdateInternal { fn from(payout_update: PayoutsUpdate) -> Self { match payout_update { PayoutsUpdate::Update { amount, destination_currency, source_currency, description, recurring, auto_fulfill, return_url, entity_type, metadata, profile_id, status, confirm, payout_type, address_id, customer_id, } => Self { amount: Some(amount), destination_currency: Some(destination_currency), source_currency: Some(source_currency), description, recurring: Some(recurring), auto_fulfill: Some(auto_fulfill), return_url, entity_type: Some(entity_type), metadata, profile_id, status, confirm, payout_type, address_id, customer_id, ..Default::default() }, PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } => Self { payout_method_id: Some(payout_method_id), ..Default::default() }, PayoutsUpdate::RecurringUpdate { recurring } => Self { recurring: Some(recurring), ..Default::default() }, PayoutsUpdate::AttemptCountUpdate { attempt_count } => Self { attempt_count: Some(attempt_count), ..Default::default() }, PayoutsUpdate::StatusUpdate { status } => Self { status: Some(status), ..Default::default() }, } } } impl PayoutsUpdate { pub fn apply_changeset(self, source: Payouts) -> Payouts { let PayoutsUpdateInternal { amount, destination_currency, source_currency, description, recurring, auto_fulfill, return_url, entity_type, metadata, payout_method_id, profile_id, status, last_modified_at, attempt_count, confirm, payout_type, address_id, customer_id, } = self.into(); Payouts { amount: amount.unwrap_or(source.amount), destination_currency: destination_currency.unwrap_or(source.destination_currency), source_currency: source_currency.unwrap_or(source.source_currency), description: description.or(source.description), recurring: recurring.unwrap_or(source.recurring), auto_fulfill: auto_fulfill.unwrap_or(source.auto_fulfill), return_url: return_url.or(source.return_url), entity_type: entity_type.unwrap_or(source.entity_type), metadata: metadata.or(source.metadata), payout_method_id: payout_method_id.or(source.payout_method_id), profile_id: profile_id.unwrap_or(source.profile_id), status: status.unwrap_or(source.status), last_modified_at, attempt_count: attempt_count.unwrap_or(source.attempt_count), confirm: confirm.or(source.confirm), payout_type: payout_type.or(source.payout_type), address_id: address_id.or(source.address_id), customer_id: customer_id.or(source.customer_id), ..source } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/payouts.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_2198813788028434005
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/fraud_check.rs // Contains: 3 structs, 1 enums use common_enums as storage_enums; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, schema::fraud_check, }; #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = fraud_check, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct FraudCheck { pub frm_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub created_at: PrimitiveDateTime, pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: FraudCheckType, pub frm_status: FraudCheckStatus, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, pub modified_at: PrimitiveDateTime, pub last_step: FraudCheckLastStep, pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision. } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = fraud_check)] pub struct FraudCheckNew { pub frm_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub created_at: PrimitiveDateTime, pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: FraudCheckType, pub frm_status: FraudCheckStatus, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, pub modified_at: PrimitiveDateTime, pub last_step: FraudCheckLastStep, pub payment_capture_method: Option<storage_enums::CaptureMethod>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum FraudCheckUpdate { //Refer PaymentAttemptUpdate for other variants implementations ResponseUpdate { frm_status: FraudCheckStatus, frm_transaction_id: Option<String>, frm_reason: Option<serde_json::Value>, frm_score: Option<i32>, metadata: Option<serde_json::Value>, modified_at: PrimitiveDateTime, last_step: FraudCheckLastStep, payment_capture_method: Option<storage_enums::CaptureMethod>, }, ErrorUpdate { status: FraudCheckStatus, error_message: Option<Option<String>>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = fraud_check)] pub struct FraudCheckUpdateInternal { frm_status: Option<FraudCheckStatus>, frm_transaction_id: Option<String>, frm_reason: Option<serde_json::Value>, frm_score: Option<i32>, frm_error: Option<Option<String>>, metadata: Option<serde_json::Value>, last_step: FraudCheckLastStep, payment_capture_method: Option<storage_enums::CaptureMethod>, } impl From<FraudCheckUpdate> for FraudCheckUpdateInternal { fn from(fraud_check_update: FraudCheckUpdate) -> Self { match fraud_check_update { FraudCheckUpdate::ResponseUpdate { frm_status, frm_transaction_id, frm_reason, frm_score, metadata, modified_at: _, last_step, payment_capture_method, } => Self { frm_status: Some(frm_status), frm_transaction_id, frm_reason, frm_score, metadata, last_step, payment_capture_method, ..Default::default() }, FraudCheckUpdate::ErrorUpdate { status, error_message, } => Self { frm_status: Some(status), frm_error: error_message, ..Default::default() }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/fraud_check.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-4922530386436596062
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/cards_info.rs // Contains: 2 structs, 0 enums use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::cards_info}; #[derive( Clone, Debug, Queryable, Identifiable, Selectable, serde::Deserialize, serde::Serialize, Insertable, )] #[diesel(table_name = cards_info, primary_key(card_iin), check_for_backend(diesel::pg::Pg))] pub struct CardInfo { pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<storage_enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub date_created: PrimitiveDateTime, pub last_updated: Option<PrimitiveDateTime>, pub last_updated_provider: Option<String>, } #[derive( Clone, Debug, PartialEq, Eq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, )] #[diesel(table_name = cards_info)] pub struct UpdateCardInfo { pub card_issuer: Option<String>, pub card_network: Option<storage_enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub last_updated: Option<PrimitiveDateTime>, pub last_updated_provider: Option<String>, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/cards_info.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_700700902727061395
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/payment_method.rs // Contains: 15 structs, 2 enums use std::collections::HashMap; use common_enums::MerchantStorageScheme; use common_utils::{ encryption::Encryption, errors::{CustomResult, ParsingError}, pii, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use error_stack::ResultExt; #[cfg(feature = "v1")] use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::{enums as storage_enums, schema::payment_methods}; #[cfg(feature = "v2")] use crate::{enums as storage_enums, schema_v2::payment_methods}; #[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = payment_methods, primary_key(payment_method_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentMethod { pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_method_id: String, #[diesel(deserialize_as = super::OptionalDieselArray<storage_enums::Currency>)] pub accepted_currency: Option<Vec<storage_enums::Currency>>, pub scheme: Option<String>, pub token: Option<String>, pub cardholder_name: Option<Secret<String>>, pub issuer_name: Option<String>, pub issuer_country: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub payer_country: Option<Vec<String>>, pub is_stored: Option<bool>, pub swift_code: Option<String>, pub direct_debit_token: Option<String>, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method: Option<storage_enums::PaymentMethod>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_issuer: Option<String>, pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, pub vault_type: Option<storage_enums::VaultType>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = payment_methods, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct PaymentMethod { pub customer_id: common_utils::id_type::GlobalCustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<CommonMandateReference>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, pub vault_type: Option<storage_enums::VaultType>, pub locker_fingerprint_id: Option<String>, pub payment_method_type_v2: Option<storage_enums::PaymentMethod>, pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub id: common_utils::id_type::GlobalPaymentMethodId, pub external_vault_token_data: Option<Encryption>, } impl PaymentMethod { #[cfg(feature = "v1")] pub fn get_id(&self) -> &String { &self.payment_method_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId { &self.id } } #[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_methods)] pub struct PaymentMethodNew { pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_method_id: String, pub payment_method: Option<storage_enums::PaymentMethod>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_issuer: Option<String>, pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>, pub accepted_currency: Option<Vec<storage_enums::Currency>>, pub scheme: Option<String>, pub token: Option<String>, pub cardholder_name: Option<Secret<String>>, pub issuer_name: Option<String>, pub issuer_country: Option<String>, pub payer_country: Option<Vec<String>>, pub is_stored: Option<bool>, pub swift_code: Option<String>, pub direct_debit_token: Option<String>, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, pub vault_type: Option<storage_enums::VaultType>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_methods)] pub struct PaymentMethodNew { pub customer_id: common_utils::id_type::GlobalCustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<CommonMandateReference>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_token_data: Option<Encryption>, pub locker_fingerprint_id: Option<String>, pub payment_method_type_v2: Option<storage_enums::PaymentMethod>, pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub id: common_utils::id_type::GlobalPaymentMethodId, pub vault_type: Option<storage_enums::VaultType>, } impl PaymentMethodNew { pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } #[cfg(feature = "v1")] pub fn get_id(&self) -> &String { &self.payment_method_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId { &self.id } } #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct TokenizeCoreWorkflow { pub lookup_key: String, pub pm: storage_enums::PaymentMethod, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub enum PaymentMethodUpdate { MetadataUpdateAndLastUsed { metadata: Option<serde_json::Value>, last_used_at: PrimitiveDateTime, }, UpdatePaymentMethodDataAndLastUsed { payment_method_data: Option<Encryption>, scheme: Option<String>, last_used_at: PrimitiveDateTime, }, PaymentMethodDataUpdate { payment_method_data: Option<Encryption>, }, LastUsedUpdate { last_used_at: PrimitiveDateTime, }, NetworkTransactionIdAndStatusUpdate { network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, }, StatusUpdate { status: Option<storage_enums::PaymentMethodStatus>, }, AdditionalDataUpdate { payment_method_data: Option<Encryption>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, payment_method: Option<storage_enums::PaymentMethod>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_method_issuer: Option<String>, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, }, ConnectorMandateDetailsUpdate { connector_mandate_details: Option<serde_json::Value>, }, NetworkTokenDataUpdate { network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, }, ConnectorNetworkTransactionIdAndMandateDetailsUpdate { connector_mandate_details: Option<pii::SecretSerdeValue>, network_transaction_id: Option<Secret<String>>, }, PaymentMethodBatchUpdate { connector_mandate_details: Option<pii::SecretSerdeValue>, network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, payment_method_data: Option<Encryption>, }, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize)] pub enum PaymentMethodUpdate { UpdatePaymentMethodDataAndLastUsed { payment_method_data: Option<Encryption>, scheme: Option<String>, last_used_at: PrimitiveDateTime, }, PaymentMethodDataUpdate { payment_method_data: Option<Encryption>, }, LastUsedUpdate { last_used_at: PrimitiveDateTime, }, NetworkTransactionIdAndStatusUpdate { network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, }, StatusUpdate { status: Option<storage_enums::PaymentMethodStatus>, }, GenericUpdate { payment_method_data: Option<Encryption>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, payment_method_type_v2: Option<storage_enums::PaymentMethod>, payment_method_subtype: Option<storage_enums::PaymentMethodType>, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, locker_fingerprint_id: Option<String>, connector_mandate_details: Option<CommonMandateReference>, external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, }, ConnectorMandateDetailsUpdate { connector_mandate_details: Option<CommonMandateReference>, }, } impl PaymentMethodUpdate { pub fn convert_to_payment_method_update( self, storage_scheme: MerchantStorageScheme, ) -> PaymentMethodUpdateInternal { let mut update_internal: PaymentMethodUpdateInternal = self.into(); update_internal.updated_by = Some(storage_scheme.to_string()); update_internal } } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_methods)] pub struct PaymentMethodUpdateInternal { payment_method_data: Option<Encryption>, last_used_at: Option<PrimitiveDateTime>, network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, payment_method_type_v2: Option<storage_enums::PaymentMethod>, connector_mandate_details: Option<CommonMandateReference>, updated_by: Option<String>, payment_method_subtype: Option<storage_enums::PaymentMethodType>, last_modified: PrimitiveDateTime, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, locker_fingerprint_id: Option<String>, external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] impl PaymentMethodUpdateInternal { pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod { let Self { payment_method_data, last_used_at, network_transaction_id, status, locker_id, payment_method_type_v2, connector_mandate_details, updated_by, payment_method_subtype, last_modified, network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, locker_fingerprint_id, external_vault_source, } = self; PaymentMethod { customer_id: source.customer_id, merchant_id: source.merchant_id, created_at: source.created_at, last_modified, payment_method_data: payment_method_data.or(source.payment_method_data), locker_id: locker_id.or(source.locker_id), last_used_at: last_used_at.unwrap_or(source.last_used_at), connector_mandate_details: connector_mandate_details .or(source.connector_mandate_details), customer_acceptance: source.customer_acceptance, status: status.unwrap_or(source.status), network_transaction_id: network_transaction_id.or(source.network_transaction_id), client_secret: source.client_secret, payment_method_billing_address: source.payment_method_billing_address, updated_by: updated_by.or(source.updated_by), locker_fingerprint_id: locker_fingerprint_id.or(source.locker_fingerprint_id), payment_method_type_v2: payment_method_type_v2.or(source.payment_method_type_v2), payment_method_subtype: payment_method_subtype.or(source.payment_method_subtype), id: source.id, version: source.version, network_token_requestor_reference_id: network_token_requestor_reference_id .or(source.network_token_requestor_reference_id), network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id), network_token_payment_method_data: network_token_payment_method_data .or(source.network_token_payment_method_data), external_vault_source: external_vault_source.or(source.external_vault_source), external_vault_token_data: source.external_vault_token_data, vault_type: source.vault_type, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_methods)] pub struct PaymentMethodUpdateInternal { metadata: Option<serde_json::Value>, payment_method_data: Option<Encryption>, last_used_at: Option<PrimitiveDateTime>, network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, network_token_requestor_reference_id: Option<String>, payment_method: Option<storage_enums::PaymentMethod>, connector_mandate_details: Option<serde_json::Value>, updated_by: Option<String>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_method_issuer: Option<String>, last_modified: PrimitiveDateTime, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, scheme: Option<String>, } #[cfg(feature = "v1")] impl PaymentMethodUpdateInternal { pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod { let Self { metadata, payment_method_data, last_used_at, network_transaction_id, status, locker_id, network_token_requestor_reference_id, payment_method, connector_mandate_details, updated_by, payment_method_type, payment_method_issuer, last_modified, network_token_locker_id, network_token_payment_method_data, scheme, } = self; PaymentMethod { customer_id: source.customer_id, merchant_id: source.merchant_id, payment_method_id: source.payment_method_id, accepted_currency: source.accepted_currency, scheme: scheme.or(source.scheme), token: source.token, cardholder_name: source.cardholder_name, issuer_name: source.issuer_name, issuer_country: source.issuer_country, payer_country: source.payer_country, is_stored: source.is_stored, swift_code: source.swift_code, direct_debit_token: source.direct_debit_token, created_at: source.created_at, last_modified, payment_method: payment_method.or(source.payment_method), payment_method_type: payment_method_type.or(source.payment_method_type), payment_method_issuer: payment_method_issuer.or(source.payment_method_issuer), payment_method_issuer_code: source.payment_method_issuer_code, metadata: metadata.map_or(source.metadata, |v| Some(v.into())), payment_method_data: payment_method_data.or(source.payment_method_data), locker_id: locker_id.or(source.locker_id), last_used_at: last_used_at.unwrap_or(source.last_used_at), connector_mandate_details: connector_mandate_details .or(source.connector_mandate_details), customer_acceptance: source.customer_acceptance, status: status.unwrap_or(source.status), network_transaction_id: network_transaction_id.or(source.network_transaction_id), client_secret: source.client_secret, payment_method_billing_address: source.payment_method_billing_address, updated_by: updated_by.or(source.updated_by), version: source.version, network_token_requestor_reference_id: network_token_requestor_reference_id .or(source.network_token_requestor_reference_id), network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id), network_token_payment_method_data: network_token_payment_method_data .or(source.network_token_payment_method_data), external_vault_source: source.external_vault_source, vault_type: source.vault_type, } } } #[cfg(feature = "v1")] impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { fn from(payment_method_update: PaymentMethodUpdate) -> Self { match payment_method_update { PaymentMethodUpdate::MetadataUpdateAndLastUsed { metadata, last_used_at, } => Self { metadata, payment_method_data: None, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data, } => Self { metadata: None, payment_method_data, last_used_at: None, network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self { metadata: None, payment_method_data: None, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed { payment_method_data, scheme, last_used_at, } => Self { metadata: None, payment_method_data, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme, }, PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status, } => Self { metadata: None, payment_method_data: None, last_used_at: None, network_transaction_id, status, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::StatusUpdate { status } => Self { metadata: None, payment_method_data: None, last_used_at: None, network_transaction_id: None, status, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::AdditionalDataUpdate { payment_method_data, status, locker_id, network_token_requestor_reference_id, payment_method, payment_method_type, payment_method_issuer, network_token_locker_id, network_token_payment_method_data, } => Self { metadata: None, payment_method_data, last_used_at: None, network_transaction_id: None, status, locker_id, network_token_requestor_reference_id, payment_method, connector_mandate_details: None, updated_by: None, payment_method_issuer, payment_method_type, last_modified: common_utils::date_time::now(), network_token_locker_id, network_token_payment_method_data, scheme: None, }, PaymentMethodUpdate::ConnectorMandateDetailsUpdate { connector_mandate_details, } => Self { metadata: None, payment_method_data: None, last_used_at: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details, network_transaction_id: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::NetworkTokenDataUpdate { network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, } => Self { metadata: None, payment_method_data: None, last_used_at: None, status: None, locker_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_transaction_id: None, network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, scheme: None, }, PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate { connector_mandate_details, network_transaction_id, } => Self { connector_mandate_details: connector_mandate_details .map(|mandate_details| mandate_details.expose()), network_transaction_id: network_transaction_id.map(|txn_id| txn_id.expose()), last_modified: common_utils::date_time::now(), status: None, metadata: None, payment_method_data: None, last_used_at: None, locker_id: None, payment_method: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::PaymentMethodBatchUpdate { connector_mandate_details, network_transaction_id, status, payment_method_data, } => Self { metadata: None, last_used_at: None, status, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: connector_mandate_details .map(|mandate_details| mandate_details.expose()), network_transaction_id, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, payment_method_data, }, } } } #[cfg(feature = "v2")] impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { fn from(payment_method_update: PaymentMethodUpdate) -> Self { match payment_method_update { PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data, } => Self { payment_method_data, last_used_at: None, network_transaction_id: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self { payment_method_data: None, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed { payment_method_data, last_used_at, .. } => Self { payment_method_data, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status, } => Self { payment_method_data: None, last_used_at: None, network_transaction_id, status, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::StatusUpdate { status } => Self { payment_method_data: None, last_used_at: None, network_transaction_id: None, status, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::GenericUpdate { payment_method_data, status, locker_id, payment_method_type_v2, payment_method_subtype, network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, locker_fingerprint_id, connector_mandate_details, external_vault_source, } => Self { payment_method_data, last_used_at: None, network_transaction_id: None, status, locker_id, payment_method_type_v2, connector_mandate_details, updated_by: None, payment_method_subtype, last_modified: common_utils::date_time::now(), network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, locker_fingerprint_id, external_vault_source, }, PaymentMethodUpdate::ConnectorMandateDetailsUpdate { connector_mandate_details, } => Self { payment_method_data: None, last_used_at: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details, network_transaction_id: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, } } } #[cfg(feature = "v1")] impl From<&PaymentMethodNew> for PaymentMethod { fn from(payment_method_new: &PaymentMethodNew) -> Self { Self { customer_id: payment_method_new.customer_id.clone(), merchant_id: payment_method_new.merchant_id.clone(), payment_method_id: payment_method_new.payment_method_id.clone(), locker_id: payment_method_new.locker_id.clone(), network_token_requestor_reference_id: payment_method_new .network_token_requestor_reference_id .clone(), accepted_currency: payment_method_new.accepted_currency.clone(), scheme: payment_method_new.scheme.clone(), token: payment_method_new.token.clone(), cardholder_name: payment_method_new.cardholder_name.clone(), issuer_name: payment_method_new.issuer_name.clone(), issuer_country: payment_method_new.issuer_country.clone(), payer_country: payment_method_new.payer_country.clone(), is_stored: payment_method_new.is_stored, swift_code: payment_method_new.swift_code.clone(), direct_debit_token: payment_method_new.direct_debit_token.clone(), created_at: payment_method_new.created_at, last_modified: payment_method_new.last_modified, payment_method: payment_method_new.payment_method, payment_method_type: payment_method_new.payment_method_type, payment_method_issuer: payment_method_new.payment_method_issuer.clone(), payment_method_issuer_code: payment_method_new.payment_method_issuer_code, metadata: payment_method_new.metadata.clone(), payment_method_data: payment_method_new.payment_method_data.clone(), last_used_at: payment_method_new.last_used_at, connector_mandate_details: payment_method_new.connector_mandate_details.clone(), customer_acceptance: payment_method_new.customer_acceptance.clone(), status: payment_method_new.status, network_transaction_id: payment_method_new.network_transaction_id.clone(), client_secret: payment_method_new.client_secret.clone(), updated_by: payment_method_new.updated_by.clone(), payment_method_billing_address: payment_method_new .payment_method_billing_address .clone(), version: payment_method_new.version, network_token_locker_id: payment_method_new.network_token_locker_id.clone(), network_token_payment_method_data: payment_method_new .network_token_payment_method_data .clone(), external_vault_source: payment_method_new.external_vault_source.clone(), vault_type: payment_method_new.vault_type, } } } #[cfg(feature = "v2")] impl From<&PaymentMethodNew> for PaymentMethod { fn from(payment_method_new: &PaymentMethodNew) -> Self { Self { customer_id: payment_method_new.customer_id.clone(), merchant_id: payment_method_new.merchant_id.clone(), locker_id: payment_method_new.locker_id.clone(), created_at: payment_method_new.created_at, last_modified: payment_method_new.last_modified, payment_method_data: payment_method_new.payment_method_data.clone(), last_used_at: payment_method_new.last_used_at, connector_mandate_details: payment_method_new.connector_mandate_details.clone(), customer_acceptance: payment_method_new.customer_acceptance.clone(), status: payment_method_new.status, network_transaction_id: payment_method_new.network_transaction_id.clone(), client_secret: payment_method_new.client_secret.clone(), updated_by: payment_method_new.updated_by.clone(), payment_method_billing_address: payment_method_new .payment_method_billing_address .clone(), locker_fingerprint_id: payment_method_new.locker_fingerprint_id.clone(), payment_method_type_v2: payment_method_new.payment_method_type_v2, payment_method_subtype: payment_method_new.payment_method_subtype, id: payment_method_new.id.clone(), version: payment_method_new.version, network_token_requestor_reference_id: payment_method_new .network_token_requestor_reference_id .clone(), network_token_locker_id: payment_method_new.network_token_locker_id.clone(), network_token_payment_method_data: payment_method_new .network_token_payment_method_data .clone(), external_vault_source: None, external_vault_token_data: payment_method_new.external_vault_token_data.clone(), vault_type: payment_method_new.vault_type, } } } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsMandateReferenceRecord { pub connector_mandate_id: String, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::Currency>, pub mandate_metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>, pub connector_mandate_request_reference_id: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ConnectorTokenReferenceRecord { pub connector_token: String, pub payment_method_subtype: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<common_utils::types::MinorUnit>, pub original_payment_authorized_currency: Option<common_enums::Currency>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_token_status: common_enums::ConnectorTokenStatus, pub connector_token_request_reference_id: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PaymentsMandateReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>, ); #[cfg(feature = "v1")] impl std::ops::Deref for PaymentsMandateReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } #[cfg(feature = "v1")] impl std::ops::DerefMut for PaymentsMandateReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PaymentsTokenReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>, ); #[cfg(feature = "v2")] impl std::ops::Deref for PaymentsTokenReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } #[cfg(feature = "v2")] impl std::ops::DerefMut for PaymentsTokenReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v1")] common_utils::impl_to_sql_from_sql_json!(PaymentsMandateReference); #[cfg(feature = "v2")] common_utils::impl_to_sql_from_sql_json!(PaymentsTokenReference); #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PayoutsMandateReferenceRecord { pub transfer_method_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PayoutsMandateReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>, ); impl std::ops::Deref for PayoutsMandateReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for PayoutsMandateReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v1")] #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct CommonMandateReference { pub payments: Option<PaymentsMandateReference>, pub payouts: Option<PayoutsMandateReference>, } #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct CommonMandateReference { pub payments: Option<PaymentsTokenReference>, pub payouts: Option<PayoutsMandateReference>, } impl CommonMandateReference { pub fn get_mandate_details_value(&self) -> CustomResult<serde_json::Value, ParsingError> { let mut payments = self .payments .as_ref() .map_or_else(|| Ok(serde_json::json!({})), serde_json::to_value) .change_context(ParsingError::StructParseFailure("payment mandate details"))?; self.payouts .as_ref() .map(|payouts_mandate| { serde_json::to_value(payouts_mandate).map(|payouts_mandate_value| { payments.as_object_mut().map(|payments_object| { payments_object.insert("payouts".to_string(), payouts_mandate_value); }) }) }) .transpose() .change_context(ParsingError::StructParseFailure("payout mandate details"))?; Ok(payments) } #[cfg(feature = "v2")] /// Insert a new payment token reference for the given connector_id pub fn insert_payment_token_reference_record( &mut self, connector_id: &common_utils::id_type::MerchantConnectorAccountId, record: ConnectorTokenReferenceRecord, ) { match self.payments { Some(ref mut payments_reference) => { payments_reference.insert(connector_id.clone(), record); } None => { let mut payments_reference = HashMap::new(); payments_reference.insert(connector_id.clone(), record); self.payments = Some(PaymentsTokenReference(payments_reference)); } } } } impl diesel::serialize::ToSql<diesel::sql_types::Jsonb, diesel::pg::Pg> for CommonMandateReference { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>, ) -> diesel::serialize::Result { let payments = self.get_mandate_details_value()?; <serde_json::Value as diesel::serialize::ToSql< diesel::sql_types::Jsonb, diesel::pg::Pg, >>::to_sql(&payments, &mut out.reborrow()) } } #[cfg(feature = "v1")] impl<DB: diesel::backend::Backend> diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB> for CommonMandateReference where serde_json::Value: diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let value = <serde_json::Value as diesel::deserialize::FromSql< diesel::sql_types::Jsonb, DB, >>::from_sql(bytes)?; let payments_data = value .clone() .as_object_mut() .map(|obj| { obj.remove("payouts"); serde_json::from_value::<PaymentsMandateReference>(serde_json::Value::Object( obj.clone(), )) .inspect_err(|err| { router_env::logger::error!("Failed to parse payments data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payments data", )) }) .transpose()?; let payouts_data = serde_json::from_value::<Option<Self>>(value) .inspect_err(|err| { router_env::logger::error!("Failed to parse payouts data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payouts data", )) .map(|optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) })?; Ok(Self { payments: payments_data, payouts: payouts_data, }) } } #[cfg(feature = "v2")] impl<DB: diesel::backend::Backend> diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB> for CommonMandateReference where serde_json::Value: diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let value = <serde_json::Value as diesel::deserialize::FromSql< diesel::sql_types::Jsonb, DB, >>::from_sql(bytes)?; let payments_data = value .clone() .as_object_mut() .map(|obj| { obj.remove("payouts"); serde_json::from_value::<PaymentsTokenReference>(serde_json::Value::Object( obj.clone(), )) .inspect_err(|err| { router_env::logger::error!("Failed to parse payments data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payments data", )) }) .transpose()?; let payouts_data = serde_json::from_value::<Option<Self>>(value) .inspect_err(|err| { router_env::logger::error!("Failed to parse payouts data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payouts data", )) .map(|optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) })?; Ok(Self { payments: payments_data, payouts: payouts_data, }) } } #[cfg(feature = "v1")] impl From<PaymentsMandateReference> for CommonMandateReference { fn from(payment_reference: PaymentsMandateReference) -> Self { Self { payments: Some(payment_reference), payouts: None, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/payment_method.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 15, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_1835119994305443024
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/merchant_connector_account.rs // Contains: 9 structs, 0 enums #[cfg(feature = "v2")] use std::collections::HashMap; use std::fmt::Debug; use common_utils::{encryption::Encryption, id_type, pii}; #[cfg(feature = "v2")] use diesel::{sql_types::Jsonb, AsExpression}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::enums as storage_enums; #[cfg(feature = "v1")] use crate::schema::merchant_connector_account; #[cfg(feature = "v2")] use crate::schema_v2::merchant_connector_account; #[cfg(feature = "v1")] #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_connector_account, primary_key(merchant_connector_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantConnectorAccount { pub merchant_id: id_type::MerchantId, pub connector_name: String, pub connector_account_details: Encryption, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: id_type::MerchantConnectorAccountId, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, pub connector_type: storage_enums::ConnectorType, pub metadata: Option<pii::SecretSerdeValue>, pub connector_label: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub business_sub_label: Option<String>, pub frm_configs: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, pub profile_id: Option<id_type::ProfileId>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: storage_enums::ConnectorStatus, pub additional_merchant_data: Option<Encryption>, pub connector_wallets_details: Option<Encryption>, pub version: common_enums::ApiVersion, pub id: Option<id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] impl MerchantConnectorAccount { pub fn get_id(&self) -> id_type::MerchantConnectorAccountId { self.merchant_connector_id.clone() } } #[cfg(feature = "v2")] use crate::RequiredFromNullable; #[cfg(feature = "v2")] #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_connector_account, check_for_backend(diesel::pg::Pg))] pub struct MerchantConnectorAccount { pub merchant_id: id_type::MerchantId, pub connector_name: common_enums::connector_enums::Connector, pub connector_account_details: Encryption, pub disabled: Option<bool>, #[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, pub connector_type: storage_enums::ConnectorType, pub metadata: Option<pii::SecretSerdeValue>, pub connector_label: Option<String>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, #[diesel(deserialize_as = RequiredFromNullable<id_type::ProfileId>)] pub profile_id: id_type::ProfileId, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: storage_enums::ConnectorStatus, pub additional_merchant_data: Option<Encryption>, pub connector_wallets_details: Option<Encryption>, pub version: common_enums::ApiVersion, pub id: id_type::MerchantConnectorAccountId, pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorAccount { pub fn get_id(&self) -> id_type::MerchantConnectorAccountId { self.id.clone() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_connector_account)] pub struct MerchantConnectorAccountNew { pub merchant_id: Option<id_type::MerchantId>, pub connector_type: Option<storage_enums::ConnectorType>, pub connector_name: Option<String>, pub connector_account_details: Option<Encryption>, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: id_type::MerchantConnectorAccountId, pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_label: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub business_sub_label: Option<String>, pub frm_configs: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, pub profile_id: Option<id_type::ProfileId>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: storage_enums::ConnectorStatus, pub additional_merchant_data: Option<Encryption>, pub connector_wallets_details: Option<Encryption>, pub version: common_enums::ApiVersion, pub id: Option<id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_connector_account)] pub struct MerchantConnectorAccountNew { pub merchant_id: Option<id_type::MerchantId>, pub connector_type: Option<storage_enums::ConnectorType>, pub connector_name: Option<common_enums::connector_enums::Connector>, pub connector_account_details: Option<Encryption>, pub disabled: Option<bool>, #[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_label: Option<String>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, pub profile_id: id_type::ProfileId, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: storage_enums::ConnectorStatus, pub additional_merchant_data: Option<Encryption>, pub connector_wallets_details: Option<Encryption>, pub version: common_enums::ApiVersion, pub id: id_type::MerchantConnectorAccountId, pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_connector_account)] pub struct MerchantConnectorAccountUpdateInternal { pub connector_type: Option<storage_enums::ConnectorType>, pub connector_name: Option<String>, pub connector_account_details: Option<Encryption>, pub connector_label: Option<String>, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, pub frm_configs: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: Option<time::PrimitiveDateTime>, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: Option<storage_enums::ConnectorStatus>, pub connector_wallets_details: Option<Encryption>, pub additional_merchant_data: Option<Encryption>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_connector_account)] pub struct MerchantConnectorAccountUpdateInternal { pub connector_type: Option<storage_enums::ConnectorType>, pub connector_account_details: Option<Encryption>, pub connector_label: Option<String>, pub disabled: Option<bool>, #[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: Option<time::PrimitiveDateTime>, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: Option<storage_enums::ConnectorStatus>, pub connector_wallets_details: Option<Encryption>, pub additional_merchant_data: Option<Encryption>, pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v1")] impl MerchantConnectorAccountUpdateInternal { pub fn create_merchant_connector_account( self, source: MerchantConnectorAccount, ) -> MerchantConnectorAccount { MerchantConnectorAccount { merchant_id: source.merchant_id, connector_type: self.connector_type.unwrap_or(source.connector_type), connector_account_details: self .connector_account_details .unwrap_or(source.connector_account_details), test_mode: self.test_mode, disabled: self.disabled, merchant_connector_id: self .merchant_connector_id .unwrap_or(source.merchant_connector_id), payment_methods_enabled: self.payment_methods_enabled, frm_config: self.frm_config, modified_at: self.modified_at.unwrap_or(source.modified_at), pm_auth_config: self.pm_auth_config, status: self.status.unwrap_or(source.status), ..source } } } #[cfg(feature = "v2")] impl MerchantConnectorAccountUpdateInternal { pub fn create_merchant_connector_account( self, source: MerchantConnectorAccount, ) -> MerchantConnectorAccount { MerchantConnectorAccount { connector_type: self.connector_type.unwrap_or(source.connector_type), connector_account_details: self .connector_account_details .unwrap_or(source.connector_account_details), disabled: self.disabled, payment_methods_enabled: self.payment_methods_enabled, frm_config: self.frm_config, modified_at: self.modified_at.unwrap_or(source.modified_at), pm_auth_config: self.pm_auth_config, status: self.status.unwrap_or(source.status), feature_metadata: self.feature_metadata, ..source } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, AsExpression)] #[diesel(sql_type = Jsonb)] pub struct MerchantConnectorAccountFeatureMetadata { pub revenue_recovery: Option<RevenueRecoveryMetadata>, } #[cfg(feature = "v2")] common_utils::impl_to_sql_from_sql_json!(MerchantConnectorAccountFeatureMetadata); #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] 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. pub max_retry_count: u16, /// Maximum number of `billing connector` retries before revenue recovery can start executing retries. 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`. pub billing_account_reference: BillingAccountReference, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct BillingAccountReference(pub HashMap<id_type::MerchantConnectorAccountId, String>);
{ "crate": "diesel_models", "file": "crates/diesel_models/src/merchant_connector_account.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 9, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-3477115272060794463
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/configs.rs // Contains: 3 structs, 1 enums use std::convert::From; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::configs; #[derive(Default, Clone, Debug, Insertable, Serialize, Deserialize)] #[diesel(table_name = configs)] pub struct ConfigNew { pub key: String, pub config: String, } #[derive(Default, Clone, Debug, Identifiable, Queryable, Selectable, Deserialize, Serialize)] #[diesel(table_name = configs, primary_key(key), check_for_backend(diesel::pg::Pg))] pub struct Config { pub key: String, pub config: String, } #[derive(Debug)] pub enum ConfigUpdate { Update { config: Option<String> }, } #[derive(Clone, Debug, AsChangeset, Default)] #[diesel(table_name = configs)] pub struct ConfigUpdateInternal { config: Option<String>, } impl ConfigUpdateInternal { pub fn create_config(self, source: Config) -> Config { Config { ..source } } } impl From<ConfigUpdate> for ConfigUpdateInternal { fn from(config_update: ConfigUpdate) -> Self { match config_update { ConfigUpdate::Update { config } => Self { config }, } } } impl From<ConfigNew> for Config { fn from(config_new: ConfigNew) -> Self { Self { key: config_new.key, config: config_new.config, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/configs.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_6252262705575563884
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/blocklist_fingerprint.rs // Contains: 2 structs, 0 enums use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::blocklist_fingerprint; #[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] #[diesel(table_name = blocklist_fingerprint)] pub struct BlocklistFingerprintNew { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint_id: String, pub data_kind: common_enums::BlocklistDataKind, pub encrypted_fingerprint: String, pub created_at: time::PrimitiveDateTime, } #[derive( Clone, Debug, Eq, PartialEq, Queryable, Identifiable, Selectable, Deserialize, Serialize, )] #[diesel(table_name = blocklist_fingerprint, primary_key(merchant_id, fingerprint_id), check_for_backend(diesel::pg::Pg))] pub struct BlocklistFingerprint { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint_id: String, pub data_kind: common_enums::BlocklistDataKind, pub encrypted_fingerprint: String, pub created_at: time::PrimitiveDateTime, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/blocklist_fingerprint.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-4660711780354117842
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/routing_algorithm.rs // Contains: 2 structs, 0 enums use common_utils::id_type; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::{enums, schema::routing_algorithm}; #[derive(Clone, Debug, Identifiable, Insertable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = routing_algorithm, primary_key(algorithm_id), check_for_backend(diesel::pg::Pg))] pub struct RoutingAlgorithm { pub algorithm_id: id_type::RoutingId, pub profile_id: id_type::ProfileId, pub merchant_id: id_type::MerchantId, pub name: String, pub description: Option<String>, pub kind: enums::RoutingAlgorithmKind, pub algorithm_data: serde_json::Value, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub algorithm_for: enums::TransactionType, pub decision_engine_routing_id: Option<String>, } pub struct RoutingAlgorithmMetadata { pub algorithm_id: id_type::RoutingId, pub name: String, pub description: Option<String>, pub kind: enums::RoutingAlgorithmKind, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub algorithm_for: enums::TransactionType, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct RoutingProfileMetadata { pub profile_id: id_type::ProfileId, pub algorithm_id: id_type::RoutingId, pub name: String, pub description: Option<String>, pub kind: enums::RoutingAlgorithmKind, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub algorithm_for: enums::TransactionType, } impl RoutingProfileMetadata { pub fn metadata_is_advanced_rule_for_payments(&self) -> bool { matches!(self.kind, enums::RoutingAlgorithmKind::Advanced) && matches!(self.algorithm_for, enums::TransactionType::Payment) } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/routing_algorithm.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_3894265408425871131
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/subscription.rs // Contains: 3 structs, 0 enums use common_utils::{generate_id_with_default_len, pii::SecretSerdeValue}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::schema::subscription; #[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] #[diesel(table_name = subscription)] pub struct SubscriptionNew { id: common_utils::id_type::SubscriptionId, status: String, billing_processor: Option<String>, payment_method_id: Option<String>, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, client_secret: Option<String>, connector_subscription_id: Option<String>, merchant_id: common_utils::id_type::MerchantId, customer_id: common_utils::id_type::CustomerId, metadata: Option<SecretSerdeValue>, created_at: time::PrimitiveDateTime, modified_at: time::PrimitiveDateTime, profile_id: common_utils::id_type::ProfileId, merchant_reference_id: Option<String>, plan_id: Option<String>, item_price_id: Option<String>, } #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize, )] #[diesel(table_name = subscription, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct Subscription { pub id: common_utils::id_type::SubscriptionId, pub status: String, pub billing_processor: Option<String>, pub payment_method_id: Option<String>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub client_secret: Option<String>, pub connector_subscription_id: Option<String>, pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: common_utils::id_type::CustomerId, pub metadata: Option<serde_json::Value>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub profile_id: common_utils::id_type::ProfileId, pub merchant_reference_id: Option<String>, pub plan_id: Option<String>, pub item_price_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, AsChangeset, router_derive::DebugAsDisplay, Deserialize)] #[diesel(table_name = subscription)] pub struct SubscriptionUpdate { pub connector_subscription_id: Option<String>, pub payment_method_id: Option<String>, pub status: Option<String>, pub modified_at: time::PrimitiveDateTime, pub plan_id: Option<String>, pub item_price_id: Option<String>, } impl SubscriptionNew { #[allow(clippy::too_many_arguments)] pub fn new( id: common_utils::id_type::SubscriptionId, status: String, billing_processor: Option<String>, payment_method_id: Option<String>, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, client_secret: Option<String>, connector_subscription_id: Option<String>, merchant_id: common_utils::id_type::MerchantId, customer_id: common_utils::id_type::CustomerId, metadata: Option<SecretSerdeValue>, profile_id: common_utils::id_type::ProfileId, merchant_reference_id: Option<String>, plan_id: Option<String>, item_price_id: Option<String>, ) -> Self { let now = common_utils::date_time::now(); Self { id, status, billing_processor, payment_method_id, merchant_connector_id, client_secret, connector_subscription_id, merchant_id, customer_id, metadata, created_at: now, modified_at: now, profile_id, merchant_reference_id, plan_id, item_price_id, } } pub fn generate_and_set_client_secret(&mut self) -> Secret<String> { let client_secret = generate_id_with_default_len(&format!("{}_secret", self.id.get_string_repr())); self.client_secret = Some(client_secret.clone()); Secret::new(client_secret) } } impl SubscriptionUpdate { pub fn new( connector_subscription_id: Option<String>, payment_method_id: Option<Secret<String>>, status: Option<String>, plan_id: Option<String>, item_price_id: Option<String>, ) -> Self { Self { connector_subscription_id, payment_method_id: payment_method_id.map(|pmid| pmid.peek().clone()), status, modified_at: common_utils::date_time::now(), plan_id, item_price_id, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/subscription.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-1900784417695916154
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/address.rs // Contains: 3 structs, 0 enums use common_utils::{crypto, encryption::Encryption}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums, schema::address}; #[derive(Clone, Debug, Insertable, Serialize, Deserialize, router_derive::DebugAsDisplay)] #[diesel(table_name = address)] pub struct AddressNew { pub address_id: String, pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, pub line1: Option<Encryption>, pub line2: Option<Encryption>, pub line3: Option<Encryption>, pub state: Option<Encryption>, pub zip: Option<Encryption>, pub first_name: Option<Encryption>, pub last_name: Option<Encryption>, pub phone_number: Option<Encryption>, pub country_code: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub updated_by: String, pub email: Option<Encryption>, pub origin_zip: Option<Encryption>, } #[derive(Clone, Debug, Queryable, Identifiable, Selectable, Serialize, Deserialize)] #[diesel(table_name = address, primary_key(address_id), check_for_backend(diesel::pg::Pg))] pub struct Address { pub address_id: String, pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, pub line1: Option<Encryption>, pub line2: Option<Encryption>, pub line3: Option<Encryption>, pub state: Option<Encryption>, pub zip: Option<Encryption>, pub first_name: Option<Encryption>, pub last_name: Option<Encryption>, pub phone_number: Option<Encryption>, pub country_code: Option<String>, pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub updated_by: String, pub email: Option<Encryption>, pub origin_zip: Option<Encryption>, } #[derive(Clone)] // Intermediate struct to convert HashMap to Address pub struct EncryptableAddress { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, pub origin_zip: crypto::OptionalEncryptableSecretString, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = address)] pub struct AddressUpdateInternal { pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, pub line1: Option<Encryption>, pub line2: Option<Encryption>, pub line3: Option<Encryption>, pub state: Option<Encryption>, pub zip: Option<Encryption>, pub first_name: Option<Encryption>, pub last_name: Option<Encryption>, pub phone_number: Option<Encryption>, pub country_code: Option<String>, pub modified_at: PrimitiveDateTime, pub updated_by: String, pub email: Option<Encryption>, pub origin_zip: Option<Encryption>, } impl AddressUpdateInternal { pub fn create_address(self, source: Address) -> Address { Address { city: self.city, country: self.country, line1: self.line1, line2: self.line2, line3: self.line3, state: self.state, zip: self.zip, first_name: self.first_name, last_name: self.last_name, phone_number: self.phone_number, country_code: self.country_code, modified_at: self.modified_at, updated_by: self.updated_by, origin_zip: self.origin_zip, ..source } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/address.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-274559431039885428
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/blocklist_lookup.rs // Contains: 2 structs, 0 enums use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::blocklist_lookup; #[derive(Default, Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] #[diesel(table_name = blocklist_lookup)] pub struct BlocklistLookupNew { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint: String, } #[derive( Default, Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize, )] #[diesel(table_name = blocklist_lookup, primary_key(merchant_id, fingerprint), check_for_backend(diesel::pg::Pg))] pub struct BlocklistLookup { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint: String, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/blocklist_lookup.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_5933697906134899615
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/enums.rs // Contains: 2 structs, 11 enums #[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbCardDiscovery as CardDiscovery, DbConnectorStatus as ConnectorStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDashboardMetadata as DashboardMetadata, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType, DbFraudCheckStatus as FraudCheckStatus, DbFraudCheckType as FraudCheckType, DbFutureUsage as FutureUsage, DbGenericLinkType as GenericLinkType, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbMandateType as MandateType, DbMerchantStorageScheme as MerchantStorageScheme, DbOrderFulfillmentTimeOrigin as OrderFulfillmentTimeOrigin, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentSource as PaymentSource, DbPaymentType as PaymentType, DbPayoutStatus as PayoutStatus, DbPayoutType as PayoutType, DbProcessTrackerStatus as ProcessTrackerStatus, DbReconStatus as ReconStatus, DbRefundStatus as RefundStatus, DbRefundType as RefundType, DbRelayStatus as RelayStatus, DbRelayType as RelayType, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbRevenueRecoveryAlgorithmType as RevenueRecoveryAlgorithmType, DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind, DbRoutingApproach as RoutingApproach, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbTokenizationFlag as TokenizationFlag, DbTotpStatus as TotpStatus, DbTransactionType as TransactionType, DbUserRoleVersion as UserRoleVersion, DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub use common_enums::*; use common_utils::pii; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub use common_utils::tokenization; use diesel::{deserialize::FromSqlRow, expression::AsExpression, sql_types::Jsonb}; use router_derive::diesel_enum; use time::PrimitiveDateTime; #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithmKind { Single, Priority, VolumeSplit, Advanced, Dynamic, ThreeDsDecisionRule, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventObjectType { PaymentDetails, RefundDetails, DisputeDetails, MandateDetails, PayoutDetails, } // Refund #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundType { InstantRefund, RegularRefund, RetryRefund, } // Mandate #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateType { SingleUse, #[default] MultiUse, } #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] pub struct MandateDetails { pub update_mandate_id: Option<String>, } common_utils::impl_to_sql_from_sql_json!(MandateDetails); #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] pub enum MandateDataType { SingleUse(MandateAmountData), MultiUse(Option<MandateAmountData>), } common_utils::impl_to_sql_from_sql_json!(MandateDataType); #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { pub amount: common_utils::types::MinorUnit, pub currency: Currency, pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckType { PreFrm, PostFrm, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckLastStep { #[default] Processing, CheckoutOrSale, TransactionOrRecordRefund, Fulfillment, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UserStatus { Active, #[default] InvitationSent, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DashboardMetadata { 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( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum TotpStatus { Set, InProgress, #[default] NotSet, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::EnumString, strum::Display, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UserRoleVersion { #[default] V1, V2, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/enums.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 11, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_8112008206957644407
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/blocklist.rs // Contains: 2 structs, 0 enums use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::blocklist; #[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] #[diesel(table_name = blocklist)] pub struct BlocklistNew { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint_id: String, pub data_kind: common_enums::BlocklistDataKind, pub metadata: Option<serde_json::Value>, pub created_at: time::PrimitiveDateTime, } #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize, )] #[diesel(table_name = blocklist, primary_key(merchant_id, fingerprint_id), check_for_backend(diesel::pg::Pg))] pub struct Blocklist { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint_id: String, pub data_kind: common_enums::BlocklistDataKind, pub metadata: Option<serde_json::Value>, pub created_at: time::PrimitiveDateTime, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/blocklist.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_7367348504628537659
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/user.rs // Contains: 3 structs, 1 enums use common_utils::{encryption::Encryption, pii, types::user::LineageContext}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; use crate::{diesel_impl::OptionalDieselArray, enums::TotpStatus, schema::users}; pub mod dashboard_metadata; pub mod sample_data; pub mod theme; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = users, primary_key(user_id), check_for_backend(diesel::pg::Pg))] pub struct User { pub user_id: String, pub email: pii::Email, pub name: Secret<String>, pub password: Option<Secret<String>>, pub is_verified: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub totp_status: TotpStatus, pub totp_secret: Option<Encryption>, #[diesel(deserialize_as = OptionalDieselArray<Secret<String>>)] pub totp_recovery_codes: Option<Vec<Secret<String>>>, pub last_password_modified_at: Option<PrimitiveDateTime>, pub lineage_context: Option<LineageContext>, } #[derive( router_derive::Setter, Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay, )] #[diesel(table_name = users)] pub struct UserNew { pub user_id: String, pub email: pii::Email, pub name: Secret<String>, pub password: Option<Secret<String>>, pub is_verified: bool, pub created_at: Option<PrimitiveDateTime>, pub last_modified_at: Option<PrimitiveDateTime>, pub totp_status: TotpStatus, pub totp_secret: Option<Encryption>, pub totp_recovery_codes: Option<Vec<Secret<String>>>, pub last_password_modified_at: Option<PrimitiveDateTime>, pub lineage_context: Option<LineageContext>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = users)] pub struct UserUpdateInternal { name: Option<String>, password: Option<Secret<String>>, is_verified: Option<bool>, last_modified_at: PrimitiveDateTime, totp_status: Option<TotpStatus>, totp_secret: Option<Encryption>, totp_recovery_codes: Option<Vec<Secret<String>>>, last_password_modified_at: Option<PrimitiveDateTime>, lineage_context: Option<LineageContext>, } #[derive(Debug)] pub enum UserUpdate { VerifyUser, AccountUpdate { name: Option<String>, is_verified: Option<bool>, }, TotpUpdate { totp_status: Option<TotpStatus>, totp_secret: Option<Encryption>, totp_recovery_codes: Option<Vec<Secret<String>>>, }, PasswordUpdate { password: Secret<String>, }, LineageContextUpdate { lineage_context: LineageContext, }, } impl From<UserUpdate> for UserUpdateInternal { fn from(user_update: UserUpdate) -> Self { let last_modified_at = common_utils::date_time::now(); match user_update { UserUpdate::VerifyUser => Self { name: None, password: None, is_verified: Some(true), last_modified_at, totp_status: None, totp_secret: None, totp_recovery_codes: None, last_password_modified_at: None, lineage_context: None, }, UserUpdate::AccountUpdate { name, is_verified } => Self { name, password: None, is_verified, last_modified_at, totp_status: None, totp_secret: None, totp_recovery_codes: None, last_password_modified_at: None, lineage_context: None, }, UserUpdate::TotpUpdate { totp_status, totp_secret, totp_recovery_codes, } => Self { name: None, password: None, is_verified: None, last_modified_at, totp_status, totp_secret, totp_recovery_codes, last_password_modified_at: None, lineage_context: None, }, UserUpdate::PasswordUpdate { password } => Self { name: None, password: Some(password), is_verified: None, last_modified_at, last_password_modified_at: Some(last_modified_at), totp_status: None, totp_secret: None, totp_recovery_codes: None, lineage_context: None, }, UserUpdate::LineageContextUpdate { lineage_context } => Self { name: None, password: None, is_verified: None, last_modified_at, last_password_modified_at: None, totp_status: None, totp_secret: None, totp_recovery_codes: None, lineage_context: Some(lineage_context), }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/user.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_1384161564634469921
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/user_role.rs // Contains: 3 structs, 1 enums use std::hash::Hash; use common_enums::EntityType; use common_utils::{consts, id_type}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::user_roles}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Eq)] #[diesel(table_name = user_roles, check_for_backend(diesel::pg::Pg))] pub struct UserRole { pub id: i32, pub user_id: String, pub merchant_id: Option<id_type::MerchantId>, pub role_id: String, pub org_id: Option<id_type::OrganizationId>, pub status: enums::UserStatus, pub created_by: String, pub last_modified_by: String, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub profile_id: Option<id_type::ProfileId>, pub entity_id: Option<String>, pub entity_type: Option<EntityType>, pub version: enums::UserRoleVersion, pub tenant_id: id_type::TenantId, } impl UserRole { pub fn get_entity_id_and_type(&self) -> Option<(String, EntityType)> { match (self.version, self.entity_type, self.role_id.as_str()) { (enums::UserRoleVersion::V1, None, consts::ROLE_ID_ORGANIZATION_ADMIN) => { let org_id = self.org_id.clone()?.get_string_repr().to_string(); Some((org_id, EntityType::Organization)) } (enums::UserRoleVersion::V1, None, _) => { let merchant_id = self.merchant_id.clone()?.get_string_repr().to_string(); Some((merchant_id, EntityType::Merchant)) } (enums::UserRoleVersion::V1, Some(_), _) => { self.entity_id.clone().zip(self.entity_type) } (enums::UserRoleVersion::V2, _, _) => self.entity_id.clone().zip(self.entity_type), } } } impl Hash for UserRole { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.user_id.hash(state); if let Some((entity_id, entity_type)) = self.get_entity_id_and_type() { entity_id.hash(state); entity_type.hash(state); } } } impl PartialEq for UserRole { fn eq(&self, other: &Self) -> bool { match ( self.get_entity_id_and_type(), other.get_entity_id_and_type(), ) { ( Some((self_entity_id, self_entity_type)), Some((other_entity_id, other_entity_type)), ) => { self.user_id == other.user_id && self_entity_id == other_entity_id && self_entity_type == other_entity_type } _ => self.user_id == other.user_id, } } } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = user_roles)] pub struct UserRoleNew { pub user_id: String, pub merchant_id: Option<id_type::MerchantId>, pub role_id: String, pub org_id: Option<id_type::OrganizationId>, pub status: enums::UserStatus, pub created_by: String, pub last_modified_by: String, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub profile_id: Option<id_type::ProfileId>, pub entity_id: Option<String>, pub entity_type: Option<EntityType>, pub version: enums::UserRoleVersion, pub tenant_id: id_type::TenantId, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = user_roles)] pub struct UserRoleUpdateInternal { role_id: Option<String>, status: Option<enums::UserStatus>, last_modified_by: Option<String>, last_modified: PrimitiveDateTime, } #[derive(Clone)] pub enum UserRoleUpdate { UpdateStatus { status: enums::UserStatus, modified_by: String, }, UpdateRole { role_id: String, modified_by: String, }, } impl From<UserRoleUpdate> for UserRoleUpdateInternal { fn from(value: UserRoleUpdate) -> Self { let last_modified = common_utils::date_time::now(); match value { UserRoleUpdate::UpdateRole { role_id, modified_by, } => Self { role_id: Some(role_id), last_modified_by: Some(modified_by), status: None, last_modified, }, UserRoleUpdate::UpdateStatus { status, modified_by, } => Self { status: Some(status), last_modified, last_modified_by: Some(modified_by), role_id: None, }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/user_role.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-8161544527052116597
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/locker_mock_up.rs // Contains: 2 structs, 0 enums use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::locker_mock_up; #[derive(Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq)] #[diesel(table_name = locker_mock_up, primary_key(card_id), check_for_backend(diesel::pg::Pg))] pub struct LockerMockUp { pub card_id: String, pub external_id: String, pub card_fingerprint: String, pub card_global_fingerprint: String, pub merchant_id: common_utils::id_type::MerchantId, pub card_number: String, pub card_exp_year: String, pub card_exp_month: String, pub name_on_card: Option<String>, pub nickname: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub duplicate: Option<bool>, pub card_cvc: Option<String>, pub payment_method_id: Option<String>, pub enc_card_data: Option<String>, } #[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = locker_mock_up)] pub struct LockerMockUpNew { pub card_id: String, pub external_id: String, pub card_fingerprint: String, pub card_global_fingerprint: String, pub merchant_id: common_utils::id_type::MerchantId, pub card_number: String, pub card_exp_year: String, pub card_exp_month: String, pub name_on_card: Option<String>, pub card_cvc: Option<String>, pub payment_method_id: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub nickname: Option<String>, pub enc_card_data: Option<String>, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/locker_mock_up.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-1529040184704540211
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/refund.rs // Contains: 8 structs, 2 enums use common_utils::{ id_type, pii, types::{ChargeRefunds, ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::enums as storage_enums; #[cfg(feature = "v1")] use crate::schema::refund; #[cfg(feature = "v2")] use crate::{schema_v2::refund, RequiredFromNullable}; #[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = refund, primary_key(refund_id), check_for_backend(diesel::pg::Pg))] pub struct Refund { pub internal_reference_id: String, pub refund_id: String, //merchant_reference id pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub external_reference_id: Option<String>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub refund_error_message: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: String, pub refund_reason: Option<String>, pub refund_error_code: Option<String>, pub profile_id: Option<id_type::ProfileId>, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: id_type::OrganizationId, /// INFO: This field is deprecated and replaced by processor_refund_data pub connector_refund_data: Option<String>, /// INFO: This field is deprecated and replaced by processor_transaction_data pub connector_transaction_data: Option<String>, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, pub issuer_error_code: Option<String>, pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive( Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = refund, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct Refund { pub payment_id: id_type::GlobalPaymentId, pub merchant_id: id_type::MerchantId, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub external_reference_id: Option<String>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub refund_error_message: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: id_type::GlobalAttemptId, pub refund_reason: Option<String>, pub refund_error_code: Option<String>, pub profile_id: Option<id_type::ProfileId>, pub updated_by: String, pub charges: Option<ChargeRefunds>, pub organization_id: id_type::OrganizationId, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, pub id: id_type::GlobalRefundId, #[diesel(deserialize_as = RequiredFromNullable<id_type::RefundReferenceId>)] pub merchant_reference_id: id_type::RefundReferenceId, pub connector_id: Option<id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, router_derive::Setter, )] #[diesel(table_name = refund)] pub struct RefundNew { pub refund_id: String, pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub internal_reference_id: String, pub external_reference_id: Option<String>, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: String, pub refund_reason: Option<String>, pub profile_id: Option<id_type::ProfileId>, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: id_type::OrganizationId, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, } #[cfg(feature = "v2")] #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, router_derive::Setter, )] #[diesel(table_name = refund)] pub struct RefundNew { pub merchant_reference_id: id_type::RefundReferenceId, pub payment_id: id_type::GlobalPaymentId, pub merchant_id: id_type::MerchantId, pub id: id_type::GlobalRefundId, pub external_reference_id: Option<String>, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: id_type::GlobalAttemptId, pub refund_reason: Option<String>, pub profile_id: Option<id_type::ProfileId>, pub updated_by: String, pub connector_id: Option<id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: id_type::OrganizationId, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum RefundUpdate { Update { connector_refund_id: ConnectorTransactionId, refund_status: storage_enums::RefundStatus, sent_to_gateway: bool, refund_error_message: Option<String>, refund_arn: String, updated_by: String, processor_refund_data: Option<String>, }, MetadataAndReasonUpdate { metadata: Option<pii::SecretSerdeValue>, reason: Option<String>, updated_by: String, }, StatusUpdate { connector_refund_id: Option<ConnectorTransactionId>, sent_to_gateway: bool, refund_status: storage_enums::RefundStatus, updated_by: String, processor_refund_data: Option<String>, }, ErrorUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, connector_refund_id: Option<ConnectorTransactionId>, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, issuer_error_code: Option<String>, issuer_error_message: Option<String>, }, ManualUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, }, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum RefundUpdate { Update { connector_refund_id: ConnectorTransactionId, refund_status: storage_enums::RefundStatus, sent_to_gateway: bool, refund_error_message: Option<String>, refund_arn: String, updated_by: String, processor_refund_data: Option<String>, }, MetadataAndReasonUpdate { metadata: Option<pii::SecretSerdeValue>, reason: Option<String>, updated_by: String, }, StatusUpdate { connector_refund_id: Option<ConnectorTransactionId>, sent_to_gateway: bool, refund_status: storage_enums::RefundStatus, updated_by: String, processor_refund_data: Option<String>, }, ErrorUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, connector_refund_id: Option<ConnectorTransactionId>, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, }, ManualUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, }, } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = refund)] pub struct RefundUpdateInternal { connector_refund_id: Option<ConnectorTransactionId>, refund_status: Option<storage_enums::RefundStatus>, sent_to_gateway: Option<bool>, refund_error_message: Option<String>, refund_arn: Option<String>, metadata: Option<pii::SecretSerdeValue>, refund_reason: Option<String>, refund_error_code: Option<String>, updated_by: String, modified_at: PrimitiveDateTime, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, issuer_error_code: Option<String>, issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = refund)] pub struct RefundUpdateInternal { connector_refund_id: Option<ConnectorTransactionId>, refund_status: Option<storage_enums::RefundStatus>, sent_to_gateway: Option<bool>, refund_error_message: Option<String>, refund_arn: Option<String>, metadata: Option<pii::SecretSerdeValue>, refund_reason: Option<String>, refund_error_code: Option<String>, updated_by: String, modified_at: PrimitiveDateTime, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, } #[cfg(feature = "v1")] impl RefundUpdateInternal { pub fn create_refund(self, source: Refund) -> Refund { Refund { connector_refund_id: self.connector_refund_id, refund_status: self.refund_status.unwrap_or_default(), sent_to_gateway: self.sent_to_gateway.unwrap_or_default(), refund_error_message: self.refund_error_message, refund_arn: self.refund_arn, metadata: self.metadata, refund_reason: self.refund_reason, refund_error_code: self.refund_error_code, updated_by: self.updated_by, modified_at: self.modified_at, processor_refund_data: self.processor_refund_data, unified_code: self.unified_code, unified_message: self.unified_message, ..source } } } #[cfg(feature = "v2")] impl RefundUpdateInternal { pub fn create_refund(self, source: Refund) -> Refund { Refund { connector_refund_id: self.connector_refund_id, refund_status: self.refund_status.unwrap_or_default(), sent_to_gateway: self.sent_to_gateway.unwrap_or_default(), refund_error_message: self.refund_error_message, refund_arn: self.refund_arn, metadata: self.metadata, refund_reason: self.refund_reason, refund_error_code: self.refund_error_code, updated_by: self.updated_by, modified_at: self.modified_at, processor_refund_data: self.processor_refund_data, unified_code: self.unified_code, unified_message: self.unified_message, ..source } } } #[cfg(feature = "v1")] impl From<RefundUpdate> for RefundUpdateInternal { fn from(refund_update: RefundUpdate) -> Self { match refund_update { RefundUpdate::Update { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, updated_by, processor_refund_data, } => Self { connector_refund_id: Some(connector_refund_id), refund_status: Some(refund_status), sent_to_gateway: Some(sent_to_gateway), refund_error_message, refund_arn: Some(refund_arn), updated_by, processor_refund_data, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, RefundUpdate::MetadataAndReasonUpdate { metadata, reason, updated_by, } => Self { metadata, refund_reason: reason, updated_by, connector_refund_id: None, refund_status: None, sent_to_gateway: None, refund_error_message: None, refund_arn: None, refund_error_code: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, RefundUpdate::StatusUpdate { connector_refund_id, sent_to_gateway, refund_status, updated_by, processor_refund_data, } => Self { connector_refund_id, sent_to_gateway: Some(sent_to_gateway), refund_status: Some(refund_status), updated_by, processor_refund_data, refund_error_message: None, refund_arn: None, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, RefundUpdate::ErrorUpdate { refund_status, refund_error_message, refund_error_code, unified_code, unified_message, updated_by, connector_refund_id, processor_refund_data, issuer_error_code, issuer_error_message, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id, processor_refund_data, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), unified_code, unified_message, issuer_error_code, issuer_error_message, }, RefundUpdate::ManualUpdate { refund_status, refund_error_message, refund_error_code, updated_by, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id: None, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, } } } #[cfg(feature = "v2")] impl From<RefundUpdate> for RefundUpdateInternal { fn from(refund_update: RefundUpdate) -> Self { match refund_update { RefundUpdate::Update { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, updated_by, processor_refund_data, } => Self { connector_refund_id: Some(connector_refund_id), refund_status: Some(refund_status), sent_to_gateway: Some(sent_to_gateway), refund_error_message, refund_arn: Some(refund_arn), updated_by, processor_refund_data, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, }, RefundUpdate::MetadataAndReasonUpdate { metadata, reason, updated_by, } => Self { metadata, refund_reason: reason, updated_by, connector_refund_id: None, refund_status: None, sent_to_gateway: None, refund_error_message: None, refund_arn: None, refund_error_code: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, }, RefundUpdate::StatusUpdate { connector_refund_id, sent_to_gateway, refund_status, updated_by, processor_refund_data, } => Self { connector_refund_id, sent_to_gateway: Some(sent_to_gateway), refund_status: Some(refund_status), updated_by, processor_refund_data, refund_error_message: None, refund_arn: None, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, }, RefundUpdate::ErrorUpdate { refund_status, refund_error_message, refund_error_code, unified_code, unified_message, updated_by, connector_refund_id, processor_refund_data, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id, processor_refund_data, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), unified_code, unified_message, }, RefundUpdate::ManualUpdate { refund_status, refund_error_message, refund_error_code, updated_by, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id: None, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, }, } } } #[cfg(feature = "v1")] impl RefundUpdate { pub fn apply_changeset(self, source: Refund) -> Refund { let RefundUpdateInternal { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, metadata, refund_reason, refund_error_code, updated_by, modified_at: _, processor_refund_data, unified_code, unified_message, issuer_error_code, issuer_error_message, } = self.into(); Refund { connector_refund_id: connector_refund_id.or(source.connector_refund_id), refund_status: refund_status.unwrap_or(source.refund_status), sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway), refund_error_message: refund_error_message.or(source.refund_error_message), refund_error_code: refund_error_code.or(source.refund_error_code), refund_arn: refund_arn.or(source.refund_arn), metadata: metadata.or(source.metadata), refund_reason: refund_reason.or(source.refund_reason), updated_by, modified_at: common_utils::date_time::now(), processor_refund_data: processor_refund_data.or(source.processor_refund_data), unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), issuer_error_code: issuer_error_code.or(source.issuer_error_code), issuer_error_message: issuer_error_message.or(source.issuer_error_message), ..source } } } #[cfg(feature = "v2")] impl RefundUpdate { pub fn apply_changeset(self, source: Refund) -> Refund { let RefundUpdateInternal { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, metadata, refund_reason, refund_error_code, updated_by, modified_at: _, processor_refund_data, unified_code, unified_message, } = self.into(); Refund { connector_refund_id: connector_refund_id.or(source.connector_refund_id), refund_status: refund_status.unwrap_or(source.refund_status), sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway), refund_error_message: refund_error_message.or(source.refund_error_message), refund_error_code: refund_error_code.or(source.refund_error_code), refund_arn: refund_arn.or(source.refund_arn), metadata: metadata.or(source.metadata), refund_reason: refund_reason.or(source.refund_reason), updated_by, modified_at: common_utils::date_time::now(), processor_refund_data: processor_refund_data.or(source.processor_refund_data), unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), ..source } } pub fn build_error_update_for_unified_error_and_message( unified_error_object: (String, String), refund_error_message: Option<String>, refund_error_code: Option<String>, storage_scheme: &storage_enums::MerchantStorageScheme, ) -> Self { let (unified_code, unified_message) = unified_error_object; Self::ErrorUpdate { refund_status: Some(storage_enums::RefundStatus::Failure), refund_error_message, refund_error_code, updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: Some(unified_code), unified_message: Some(unified_message), } } pub fn build_error_update_for_integrity_check_failure( integrity_check_failed_fields: String, connector_refund_id: Option<ConnectorTransactionId>, storage_scheme: &storage_enums::MerchantStorageScheme, ) -> Self { Self::ErrorUpdate { refund_status: Some(storage_enums::RefundStatus::ManualReview), refund_error_message: Some(format!( "Integrity Check Failed! as data mismatched for fields {integrity_check_failed_fields}" )), refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: connector_refund_id.clone(), processor_refund_data: connector_refund_id.and_then(|x| x.extract_hashed_data()), unified_code: None, unified_message: None, } } pub fn build_refund_update( connector_refund_id: ConnectorTransactionId, refund_status: storage_enums::RefundStatus, storage_scheme: &storage_enums::MerchantStorageScheme, ) -> Self { Self::Update { connector_refund_id: connector_refund_id.clone(), refund_status, sent_to_gateway: true, refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), processor_refund_data: connector_refund_id.extract_hashed_data(), } } pub fn build_error_update_for_refund_failure( refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, storage_scheme: &storage_enums::MerchantStorageScheme, ) -> Self { Self::ErrorUpdate { refund_status, refund_error_message, refund_error_code, updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, } } } #[cfg(feature = "v1")] #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct RefundCoreWorkflow { pub refund_internal_reference_id: String, pub connector_transaction_id: ConnectorTransactionId, pub merchant_id: id_type::MerchantId, pub payment_id: id_type::PaymentId, pub processor_transaction_data: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct RefundCoreWorkflow { pub refund_id: id_type::GlobalRefundId, pub connector_transaction_id: ConnectorTransactionId, pub merchant_id: id_type::MerchantId, pub payment_id: id_type::GlobalPaymentId, pub processor_transaction_data: Option<String>, } #[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for Refund { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Refund { payment_id: Some(self.payment_id.clone()), refund_id: self.refund_id.clone(), }) } } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for Refund { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Refund { payment_id: Some(self.payment_id.clone()), refund_id: self.id.clone(), }) } } impl ConnectorTransactionIdTrait for Refund { fn get_optional_connector_refund_id(&self) -> Option<&String> { match self .connector_refund_id .as_ref() .map(|refund_id| refund_id.get_txn_id(self.processor_refund_data.as_ref())) .transpose() { Ok(refund_id) => refund_id, // In case hashed data is missing from DB, use the hashed ID as connector transaction ID Err(_) => self .connector_refund_id .as_ref() .map(|txn_id| txn_id.get_id()), } } fn get_connector_transaction_id(&self) -> &String { match self .connector_transaction_id .get_txn_id(self.processor_transaction_data.as_ref()) { Ok(txn_id) => txn_id, // In case hashed data is missing from DB, use the hashed ID as connector transaction ID Err(_) => self.connector_transaction_id.get_id(), } } } mod tests { #[test] fn test_backwards_compatibility() { let serialized_refund = r#"{ "internal_reference_id": "internal_ref_123", "refund_id": "refund_456", "payment_id": "payment_789", "merchant_id": "merchant_123", "connector_transaction_id": "connector_txn_789", "connector": "stripe", "connector_refund_id": null, "external_reference_id": null, "refund_type": "instant_refund", "total_amount": 10000, "currency": "USD", "refund_amount": 9500, "refund_status": "Success", "sent_to_gateway": true, "refund_error_message": null, "metadata": null, "refund_arn": null, "created_at": "2024-02-26T12:00:00Z", "updated_at": "2024-02-26T12:00:00Z", "description": null, "attempt_id": "attempt_123", "refund_reason": null, "refund_error_code": null, "profile_id": null, "updated_by": "admin", "merchant_connector_id": null, "charges": null, "connector_transaction_data": null "unified_code": null, "unified_message": null, "processor_transaction_data": null, }"#; let deserialized = serde_json::from_str::<super::Refund>(serialized_refund); assert!(deserialized.is_ok()); } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/refund.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 8, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_2372389477799517788
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/process_tracker.rs // Contains: 3 structs, 1 enums pub use common_enums::{enums::ProcessTrackerRunner, ApiVersion}; use common_utils::ext_traits::Encode; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, errors, schema::process_tracker, StorageResult}; #[derive( Clone, Debug, Eq, PartialEq, Deserialize, Identifiable, Queryable, Selectable, Serialize, router_derive::DebugAsDisplay, )] #[diesel(table_name = process_tracker, check_for_backend(diesel::pg::Pg))] pub struct ProcessTracker { pub id: String, pub name: Option<String>, #[diesel(deserialize_as = super::DieselArray<String>)] pub tag: Vec<String>, pub runner: Option<String>, pub retry_count: i32, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub schedule_time: Option<PrimitiveDateTime>, pub rule: String, pub tracking_data: serde_json::Value, pub business_status: String, pub status: storage_enums::ProcessTrackerStatus, #[diesel(deserialize_as = super::DieselArray<String>)] pub event: Vec<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub updated_at: PrimitiveDateTime, pub version: ApiVersion, } impl ProcessTracker { #[inline(always)] pub fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool { valid_statuses.iter().any(|&x| x == self.business_status) } } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = process_tracker)] pub struct ProcessTrackerNew { pub id: String, pub name: Option<String>, pub tag: Vec<String>, pub runner: Option<String>, pub retry_count: i32, pub schedule_time: Option<PrimitiveDateTime>, pub rule: String, pub tracking_data: serde_json::Value, pub business_status: String, pub status: storage_enums::ProcessTrackerStatus, pub event: Vec<String>, pub created_at: PrimitiveDateTime, pub updated_at: PrimitiveDateTime, pub version: ApiVersion, } impl ProcessTrackerNew { #[allow(clippy::too_many_arguments)] pub fn new<T>( process_tracker_id: impl Into<String>, task: impl Into<String>, runner: ProcessTrackerRunner, tag: impl IntoIterator<Item = impl Into<String>>, tracking_data: T, retry_count: Option<i32>, schedule_time: PrimitiveDateTime, api_version: ApiVersion, ) -> StorageResult<Self> where T: Serialize + std::fmt::Debug, { let current_time = common_utils::date_time::now(); Ok(Self { id: process_tracker_id.into(), name: Some(task.into()), tag: tag.into_iter().map(Into::into).collect(), runner: Some(runner.to_string()), retry_count: retry_count.unwrap_or(0), schedule_time: Some(schedule_time), rule: String::new(), tracking_data: tracking_data .encode_to_value() .change_context(errors::DatabaseError::Others) .attach_printable("Failed to serialize process tracker tracking data")?, business_status: String::from(business_status::PENDING), status: storage_enums::ProcessTrackerStatus::New, event: vec![], created_at: current_time, updated_at: current_time, version: api_version, }) } } #[derive(Debug)] pub enum ProcessTrackerUpdate { Update { name: Option<String>, retry_count: Option<i32>, schedule_time: Option<PrimitiveDateTime>, tracking_data: Option<serde_json::Value>, business_status: Option<String>, status: Option<storage_enums::ProcessTrackerStatus>, updated_at: Option<PrimitiveDateTime>, }, StatusUpdate { status: storage_enums::ProcessTrackerStatus, business_status: Option<String>, }, StatusRetryUpdate { status: storage_enums::ProcessTrackerStatus, retry_count: i32, schedule_time: PrimitiveDateTime, }, } #[derive(Debug, Clone, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = process_tracker)] pub struct ProcessTrackerUpdateInternal { name: Option<String>, retry_count: Option<i32>, schedule_time: Option<PrimitiveDateTime>, tracking_data: Option<serde_json::Value>, business_status: Option<String>, status: Option<storage_enums::ProcessTrackerStatus>, updated_at: Option<PrimitiveDateTime>, } impl Default for ProcessTrackerUpdateInternal { fn default() -> Self { Self { name: Option::default(), retry_count: Option::default(), schedule_time: Option::default(), tracking_data: Option::default(), business_status: Option::default(), status: Option::default(), updated_at: Some(common_utils::date_time::now()), } } } impl From<ProcessTrackerUpdate> for ProcessTrackerUpdateInternal { fn from(process_tracker_update: ProcessTrackerUpdate) -> Self { match process_tracker_update { ProcessTrackerUpdate::Update { name, retry_count, schedule_time, tracking_data, business_status, status, updated_at, } => Self { name, retry_count, schedule_time, tracking_data, business_status, status, updated_at, }, ProcessTrackerUpdate::StatusUpdate { status, business_status, } => Self { status: Some(status), business_status, ..Default::default() }, ProcessTrackerUpdate::StatusRetryUpdate { status, retry_count, schedule_time, } => Self { status: Some(status), retry_count: Some(retry_count), schedule_time: Some(schedule_time), ..Default::default() }, } } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use common_utils::ext_traits::StringExt; use super::ProcessTrackerRunner; #[test] fn test_enum_to_string() { let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string(); let enum_format: ProcessTrackerRunner = string_format.parse_enum("ProcessTrackerRunner").unwrap(); assert_eq!(enum_format, ProcessTrackerRunner::PaymentsSyncWorkflow); } } pub mod business_status { /// Indicates that an irrecoverable error occurred during the workflow execution. pub const GLOBAL_FAILURE: &str = "GLOBAL_FAILURE"; /// Task successfully completed by consumer. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const COMPLETED_BY_PT: &str = "COMPLETED_BY_PT"; /// An error occurred during the workflow execution which prevents further execution and /// retries. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const FAILURE: &str = "FAILURE"; /// The resource associated with the task was removed, due to which further retries can/should /// not be done. pub const REVOKED: &str = "Revoked"; /// The task was executed for the maximum possible number of times without a successful outcome. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const RETRIES_EXCEEDED: &str = "RETRIES_EXCEEDED"; /// The outgoing webhook was successfully delivered in the initial attempt. /// Further retries of the task are not required. pub const INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL: &str = "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL"; /// Indicates that an error occurred during the workflow execution. /// This status is typically set by the workflow error handler. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const GLOBAL_ERROR: &str = "GLOBAL_ERROR"; /// The resource associated with the task has been significantly modified since the task was /// created, due to which further retries of the current task are not required. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const RESOURCE_STATUS_MISMATCH: &str = "RESOURCE_STATUS_MISMATCH"; /// Business status set for newly created tasks. pub const PENDING: &str = "Pending"; /// For the PCR Workflow /// /// This status indicates the completion of a execute task pub const EXECUTE_WORKFLOW_COMPLETE: &str = "COMPLETED_EXECUTE_TASK"; /// This status indicates the failure of a execute task pub const EXECUTE_WORKFLOW_FAILURE: &str = "FAILED_EXECUTE_TASK"; /// This status indicates that the execute task was completed to trigger the psync task pub const EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC: &str = "COMPLETED_EXECUTE_TASK_TO_TRIGGER_PSYNC"; /// This status indicates that the execute task was completed to trigger the review task pub const EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW: &str = "COMPLETED_EXECUTE_TASK_TO_TRIGGER_REVIEW"; /// This status indicates that the requeue was triggered for execute task pub const EXECUTE_WORKFLOW_REQUEUE: &str = "TRIGGER_REQUEUE_FOR_EXECUTE_WORKFLOW"; /// This status indicates the completion of a psync task pub const PSYNC_WORKFLOW_COMPLETE: &str = "COMPLETED_PSYNC_TASK"; /// This status indicates that the psync task was completed to trigger the review task pub const PSYNC_WORKFLOW_COMPLETE_FOR_REVIEW: &str = "COMPLETED_PSYNC_TASK_TO_TRIGGER_REVIEW"; /// This status indicates that the requeue was triggered for psync task pub const PSYNC_WORKFLOW_REQUEUE: &str = "TRIGGER_REQUEUE_FOR_PSYNC_WORKFLOW"; /// This status indicates the completion of a review task pub const REVIEW_WORKFLOW_COMPLETE: &str = "COMPLETED_REVIEW_TASK"; /// For the CALCULATE_WORKFLOW /// /// This status indicates an invoice is queued pub const CALCULATE_WORKFLOW_QUEUED: &str = "CALCULATE_WORKFLOW_QUEUED"; /// This status indicates an invoice has been declined due to hard decline pub const CALCULATE_WORKFLOW_FINISH: &str = "FAILED_DUE_TO_HARD_DECLINE_ERROR"; /// This status indicates that the invoice is scheduled with the best available token pub const CALCULATE_WORKFLOW_SCHEDULED: &str = "CALCULATE_WORKFLOW_SCHEDULED"; /// This status indicates the invoice is in payment sync state pub const CALCULATE_WORKFLOW_PROCESSING: &str = "CALCULATE_WORKFLOW_PROCESSING"; /// This status indicates the workflow has completed successfully when the invoice is paid pub const CALCULATE_WORKFLOW_COMPLETE: &str = "CALCULATE_WORKFLOW_COMPLETE"; }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/process_tracker.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-4045560811561951506
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/business_profile.rs // Contains: 17 structs, 0 enums use std::collections::{HashMap, HashSet}; use common_enums::{AuthenticationConnectors, UIWidgetFormLayout, VaultSdk}; use common_types::primitive_wrappers; use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::Duration; #[cfg(feature = "v1")] use crate::schema::business_profile; #[cfg(feature = "v2")] use crate::schema_v2::business_profile; /// Note: The order of fields in the struct is important. /// This should be in the same order as the fields in the schema.rs file, otherwise the code will /// not compile /// If two adjacent columns have the same type, then the compiler will not throw any error, but the /// fields read / written will be interchanged #[cfg(feature = "v1")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile, primary_key(profile_id), check_for_backend(diesel::pg::Pg))] pub struct Profile { pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: bool, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: Option<Encryption>, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: Option<bool>, pub version: common_enums::ApiVersion, pub dynamic_routing_algorithm: Option<serde_json::Value>, pub is_network_tokenization_enabled: bool, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, pub is_click_to_pay_enabled: bool, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, pub is_clear_pan_retries_enabled: bool, pub force_3ds_challenge: Option<bool>, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub id: Option<common_utils::id_type::ProfileId>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, pub three_ds_decision_rule_algorithm: Option<serde_json::Value>, pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile, primary_key(profile_id))] pub struct ProfileNew { pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: bool, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: Option<Encryption>, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: Option<bool>, pub version: common_enums::ApiVersion, pub is_network_tokenization_enabled: bool, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, pub is_click_to_pay_enabled: bool, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, pub is_clear_pan_retries_enabled: bool, pub force_3ds_challenge: Option<bool>, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub id: Option<common_utils::id_type::ProfileId>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile)] pub struct ProfileUpdateInternal { pub profile_name: Option<String>, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<String>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: Option<bool>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: Option<Encryption>, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: Option<bool>, pub is_l2_l3_enabled: Option<bool>, pub dynamic_routing_algorithm: Option<serde_json::Value>, pub is_network_tokenization_enabled: Option<bool>, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, pub is_click_to_pay_enabled: Option<bool>, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, pub is_clear_pan_retries_enabled: Option<bool>, pub force_3ds_challenge: Option<bool>, pub is_debit_routing_enabled: Option<bool>, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, pub three_ds_decision_rule_algorithm: Option<serde_json::Value>, pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } #[cfg(feature = "v1")] impl ProfileUpdateInternal { pub fn apply_changeset(self, source: Profile) -> Profile { let Self { profile_name, modified_at, return_url, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, webhook_details, metadata, routing_algorithm, intent_fulfillment_time, frm_routing_algorithm, payout_routing_algorithm, is_recon_enabled, applepay_verified_domains, payment_link_config, session_expiry, authentication_connector_details, payout_link_config, is_extended_card_info_enabled, extended_card_info_config, is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector, tax_connector_id, is_tax_connector_enabled, is_l2_l3_enabled, dynamic_routing_algorithm, is_network_tokenization_enabled, is_auto_retries_enabled, max_auto_retries_enabled, always_request_extended_authorization, is_click_to_pay_enabled, authentication_product_ids, card_testing_guard_config, card_testing_secret_key, is_clear_pan_retries_enabled, force_3ds_challenge, is_debit_routing_enabled, merchant_business_country, is_iframe_redirection_enabled, is_pre_network_tokenization_enabled, three_ds_decision_rule_algorithm, acquirer_config_map, merchant_category_code, merchant_country_code, dispute_polling_interval, is_manual_retry_enabled, always_enable_overcapture, is_external_vault_enabled, external_vault_connector_details, billing_processor_id, } = self; Profile { profile_id: source.profile_id, merchant_id: source.merchant_id, profile_name: profile_name.unwrap_or(source.profile_name), created_at: source.created_at, modified_at, return_url: return_url.or(source.return_url), enable_payment_response_hash: enable_payment_response_hash .unwrap_or(source.enable_payment_response_hash), payment_response_hash_key: payment_response_hash_key .or(source.payment_response_hash_key), redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post .unwrap_or(source.redirect_to_merchant_with_http_post), webhook_details: webhook_details.or(source.webhook_details), metadata: metadata.or(source.metadata), routing_algorithm: routing_algorithm.or(source.routing_algorithm), intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time), frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm), payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm), is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), applepay_verified_domains: applepay_verified_domains .or(source.applepay_verified_domains), payment_link_config: payment_link_config.or(source.payment_link_config), session_expiry: session_expiry.or(source.session_expiry), authentication_connector_details: authentication_connector_details .or(source.authentication_connector_details), payout_link_config: payout_link_config.or(source.payout_link_config), is_extended_card_info_enabled: is_extended_card_info_enabled .or(source.is_extended_card_info_enabled), is_connector_agnostic_mit_enabled: is_connector_agnostic_mit_enabled .or(source.is_connector_agnostic_mit_enabled), extended_card_info_config: extended_card_info_config .or(source.extended_card_info_config), use_billing_as_payment_method_billing: use_billing_as_payment_method_billing .or(source.use_billing_as_payment_method_billing), collect_shipping_details_from_wallet_connector: collect_shipping_details_from_wallet_connector .or(source.collect_shipping_details_from_wallet_connector), collect_billing_details_from_wallet_connector: collect_billing_details_from_wallet_connector .or(source.collect_billing_details_from_wallet_connector), outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers .or(source.outgoing_webhook_custom_http_headers), always_collect_billing_details_from_wallet_connector: always_collect_billing_details_from_wallet_connector .or(source.always_collect_billing_details_from_wallet_connector), always_collect_shipping_details_from_wallet_connector: always_collect_shipping_details_from_wallet_connector .or(source.always_collect_shipping_details_from_wallet_connector), tax_connector_id: tax_connector_id.or(source.tax_connector_id), is_tax_connector_enabled: is_tax_connector_enabled.or(source.is_tax_connector_enabled), is_l2_l3_enabled: is_l2_l3_enabled.or(source.is_l2_l3_enabled), version: source.version, dynamic_routing_algorithm: dynamic_routing_algorithm .or(source.dynamic_routing_algorithm), is_network_tokenization_enabled: is_network_tokenization_enabled .unwrap_or(source.is_network_tokenization_enabled), is_auto_retries_enabled: is_auto_retries_enabled.or(source.is_auto_retries_enabled), max_auto_retries_enabled: max_auto_retries_enabled.or(source.max_auto_retries_enabled), always_request_extended_authorization: always_request_extended_authorization .or(source.always_request_extended_authorization), is_click_to_pay_enabled: is_click_to_pay_enabled .unwrap_or(source.is_click_to_pay_enabled), authentication_product_ids: authentication_product_ids .or(source.authentication_product_ids), card_testing_guard_config: card_testing_guard_config .or(source.card_testing_guard_config), card_testing_secret_key, is_clear_pan_retries_enabled: is_clear_pan_retries_enabled .unwrap_or(source.is_clear_pan_retries_enabled), force_3ds_challenge, id: source.id, is_debit_routing_enabled: is_debit_routing_enabled .unwrap_or(source.is_debit_routing_enabled), merchant_business_country: merchant_business_country .or(source.merchant_business_country), is_iframe_redirection_enabled: is_iframe_redirection_enabled .or(source.is_iframe_redirection_enabled), is_pre_network_tokenization_enabled: is_pre_network_tokenization_enabled .or(source.is_pre_network_tokenization_enabled), three_ds_decision_rule_algorithm: three_ds_decision_rule_algorithm .or(source.three_ds_decision_rule_algorithm), acquirer_config_map: acquirer_config_map.or(source.acquirer_config_map), merchant_category_code: merchant_category_code.or(source.merchant_category_code), merchant_country_code: merchant_country_code.or(source.merchant_country_code), dispute_polling_interval: dispute_polling_interval.or(source.dispute_polling_interval), is_manual_retry_enabled: is_manual_retry_enabled.or(source.is_manual_retry_enabled), always_enable_overcapture: always_enable_overcapture .or(source.always_enable_overcapture), is_external_vault_enabled: is_external_vault_enabled .or(source.is_external_vault_enabled), external_vault_connector_details: external_vault_connector_details .or(source.external_vault_connector_details), billing_processor_id: billing_processor_id.or(source.billing_processor_id), } } } /// Note: The order of fields in the struct is important. /// This should be in the same order as the fields in the schema.rs file, otherwise the code will /// not compile /// If two adjacent columns have the same type, then the compiler will not throw any error, but the /// fields read / written will be interchanged #[cfg(feature = "v2")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct Profile { pub merchant_id: common_utils::id_type::MerchantId, pub profile_name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<common_utils::types::Url>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub is_recon_enabled: bool, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: Option<Encryption>, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: Option<bool>, pub version: common_enums::ApiVersion, pub dynamic_routing_algorithm: Option<serde_json::Value>, pub is_network_tokenization_enabled: bool, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, pub is_click_to_pay_enabled: bool, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, pub is_clear_pan_retries_enabled: bool, pub force_3ds_challenge: Option<bool>, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub id: common_utils::id_type::ProfileId, pub is_iframe_redirection_enabled: Option<bool>, pub three_ds_decision_rule_algorithm: Option<serde_json::Value>, pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub is_l2_l3_enabled: Option<bool>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } impl Profile { #[cfg(feature = "v1")] pub fn get_id(&self) -> &common_utils::id_type::ProfileId { &self.profile_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::ProfileId { &self.id } } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile, primary_key(profile_id))] pub struct ProfileNew { pub merchant_id: common_utils::id_type::MerchantId, pub profile_name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<common_utils::types::Url>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub is_recon_enabled: bool, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: Option<Encryption>, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: Option<bool>, pub version: common_enums::ApiVersion, pub is_network_tokenization_enabled: bool, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, pub is_click_to_pay_enabled: bool, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, pub is_clear_pan_retries_enabled: Option<bool>, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub id: common_utils::id_type::ProfileId, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub is_l2_l3_enabled: Option<bool>, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile)] pub struct ProfileUpdateInternal { pub profile_name: Option<String>, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<common_utils::types::Url>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub is_recon_enabled: Option<bool>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: Option<Encryption>, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: Option<bool>, pub is_network_tokenization_enabled: Option<bool>, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, pub is_click_to_pay_enabled: Option<bool>, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, pub is_clear_pan_retries_enabled: Option<bool>, pub is_debit_routing_enabled: Option<bool>, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub is_l2_l3_enabled: Option<bool>, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } #[cfg(feature = "v2")] impl ProfileUpdateInternal { pub fn apply_changeset(self, source: Profile) -> Profile { let Self { profile_name, modified_at, return_url, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, webhook_details, metadata, is_recon_enabled, applepay_verified_domains, payment_link_config, session_expiry, authentication_connector_details, payout_link_config, is_extended_card_info_enabled, extended_card_info_config, is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector, tax_connector_id, is_tax_connector_enabled, billing_processor_id, routing_algorithm_id, order_fulfillment_time, order_fulfillment_time_origin, frm_routing_algorithm_id, payout_routing_algorithm_id, default_fallback_routing, should_collect_cvv_during_payment, is_network_tokenization_enabled, is_auto_retries_enabled, max_auto_retries_enabled, is_click_to_pay_enabled, authentication_product_ids, three_ds_decision_manager_config, card_testing_guard_config, card_testing_secret_key, is_clear_pan_retries_enabled, is_debit_routing_enabled, merchant_business_country, revenue_recovery_retry_algorithm_type, revenue_recovery_retry_algorithm_data, is_iframe_redirection_enabled, is_external_vault_enabled, external_vault_connector_details, merchant_category_code, merchant_country_code, split_txns_enabled, is_l2_l3_enabled, } = self; Profile { id: source.id, merchant_id: source.merchant_id, profile_name: profile_name.unwrap_or(source.profile_name), created_at: source.created_at, modified_at, return_url: return_url.or(source.return_url), enable_payment_response_hash: enable_payment_response_hash .unwrap_or(source.enable_payment_response_hash), payment_response_hash_key: payment_response_hash_key .or(source.payment_response_hash_key), redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post .unwrap_or(source.redirect_to_merchant_with_http_post), webhook_details: webhook_details.or(source.webhook_details), metadata: metadata.or(source.metadata), is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), applepay_verified_domains: applepay_verified_domains .or(source.applepay_verified_domains), payment_link_config: payment_link_config.or(source.payment_link_config), session_expiry: session_expiry.or(source.session_expiry), authentication_connector_details: authentication_connector_details .or(source.authentication_connector_details), payout_link_config: payout_link_config.or(source.payout_link_config), is_extended_card_info_enabled: is_extended_card_info_enabled .or(source.is_extended_card_info_enabled), is_connector_agnostic_mit_enabled: is_connector_agnostic_mit_enabled .or(source.is_connector_agnostic_mit_enabled), extended_card_info_config: extended_card_info_config .or(source.extended_card_info_config), use_billing_as_payment_method_billing: use_billing_as_payment_method_billing .or(source.use_billing_as_payment_method_billing), collect_shipping_details_from_wallet_connector: collect_shipping_details_from_wallet_connector .or(source.collect_shipping_details_from_wallet_connector), collect_billing_details_from_wallet_connector: collect_billing_details_from_wallet_connector .or(source.collect_billing_details_from_wallet_connector), outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers .or(source.outgoing_webhook_custom_http_headers), always_collect_billing_details_from_wallet_connector: always_collect_billing_details_from_wallet_connector .or(always_collect_billing_details_from_wallet_connector), always_collect_shipping_details_from_wallet_connector: always_collect_shipping_details_from_wallet_connector .or(always_collect_shipping_details_from_wallet_connector), tax_connector_id: tax_connector_id.or(source.tax_connector_id), is_tax_connector_enabled: is_tax_connector_enabled.or(source.is_tax_connector_enabled), routing_algorithm_id: routing_algorithm_id.or(source.routing_algorithm_id), order_fulfillment_time: order_fulfillment_time.or(source.order_fulfillment_time), order_fulfillment_time_origin: order_fulfillment_time_origin .or(source.order_fulfillment_time_origin), frm_routing_algorithm_id: frm_routing_algorithm_id.or(source.frm_routing_algorithm_id), payout_routing_algorithm_id: payout_routing_algorithm_id .or(source.payout_routing_algorithm_id), default_fallback_routing: default_fallback_routing.or(source.default_fallback_routing), should_collect_cvv_during_payment: should_collect_cvv_during_payment .or(source.should_collect_cvv_during_payment), version: source.version, dynamic_routing_algorithm: None, is_network_tokenization_enabled: is_network_tokenization_enabled .unwrap_or(source.is_network_tokenization_enabled), is_auto_retries_enabled: is_auto_retries_enabled.or(source.is_auto_retries_enabled), max_auto_retries_enabled: max_auto_retries_enabled.or(source.max_auto_retries_enabled), always_request_extended_authorization: None, is_click_to_pay_enabled: is_click_to_pay_enabled .unwrap_or(source.is_click_to_pay_enabled), authentication_product_ids: authentication_product_ids .or(source.authentication_product_ids), three_ds_decision_manager_config: three_ds_decision_manager_config .or(source.three_ds_decision_manager_config), card_testing_guard_config: card_testing_guard_config .or(source.card_testing_guard_config), card_testing_secret_key: card_testing_secret_key.or(source.card_testing_secret_key), is_clear_pan_retries_enabled: is_clear_pan_retries_enabled .unwrap_or(source.is_clear_pan_retries_enabled), force_3ds_challenge: None, is_debit_routing_enabled: is_debit_routing_enabled .unwrap_or(source.is_debit_routing_enabled), merchant_business_country: merchant_business_country .or(source.merchant_business_country), revenue_recovery_retry_algorithm_type: revenue_recovery_retry_algorithm_type .or(source.revenue_recovery_retry_algorithm_type), revenue_recovery_retry_algorithm_data: revenue_recovery_retry_algorithm_data .or(source.revenue_recovery_retry_algorithm_data), is_iframe_redirection_enabled: is_iframe_redirection_enabled .or(source.is_iframe_redirection_enabled), is_external_vault_enabled: is_external_vault_enabled .or(source.is_external_vault_enabled), external_vault_connector_details: external_vault_connector_details .or(source.external_vault_connector_details), three_ds_decision_rule_algorithm: None, acquirer_config_map: None, merchant_category_code: merchant_category_code.or(source.merchant_category_code), merchant_country_code: merchant_country_code.or(source.merchant_country_code), dispute_polling_interval: None, split_txns_enabled: split_txns_enabled.or(source.split_txns_enabled), is_manual_retry_enabled: None, always_enable_overcapture: None, is_l2_l3_enabled: None, billing_processor_id: billing_processor_id.or(source.billing_processor_id), } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct AuthenticationConnectorDetails { pub authentication_connectors: Vec<AuthenticationConnectors>, pub three_ds_requestor_url: String, pub three_ds_requestor_app_url: Option<String>, } common_utils::impl_to_sql_from_sql_json!(AuthenticationConnectorDetails); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct ExternalVaultConnectorDetails { pub vault_connector_id: common_utils::id_type::MerchantConnectorAccountId, pub vault_sdk: Option<VaultSdk>, } common_utils::impl_to_sql_from_sql_json!(ExternalVaultConnectorDetails); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct CardTestingGuardConfig { pub is_card_ip_blocking_enabled: bool, pub card_ip_blocking_threshold: i32, pub is_guest_user_card_blocking_enabled: bool, pub guest_user_card_blocking_threshold: i32, pub is_customer_id_blocking_enabled: bool, pub customer_id_blocking_threshold: i32, pub card_testing_guard_expiry: i32, } common_utils::impl_to_sql_from_sql_json!(CardTestingGuardConfig); impl Default for CardTestingGuardConfig { fn default() -> Self { Self { is_card_ip_blocking_enabled: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_STATUS, card_ip_blocking_threshold: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_THRESHOLD, is_guest_user_card_blocking_enabled: common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS, guest_user_card_blocking_threshold: common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD, is_customer_id_blocking_enabled: common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_STATUS, customer_id_blocking_threshold: common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD, card_testing_guard_expiry: common_utils::consts::DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS, } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct MultipleWebhookDetail { pub webhook_endpoint_id: common_utils::id_type::WebhookEndpointId, pub webhook_url: Secret<String>, pub events: HashSet<common_enums::EventType>, pub status: common_enums::OutgoingWebhookEndpointStatus, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Json)] pub struct WebhookDetails { pub webhook_version: Option<String>, pub webhook_username: Option<String>, pub webhook_password: Option<Secret<String>>, pub webhook_url: Option<Secret<String>>, pub payment_created_enabled: Option<bool>, pub payment_succeeded_enabled: Option<bool>, pub payment_failed_enabled: Option<bool>, pub payment_statuses_enabled: Option<Vec<common_enums::IntentStatus>>, pub refund_statuses_enabled: Option<Vec<common_enums::RefundStatus>>, pub payout_statuses_enabled: Option<Vec<common_enums::PayoutStatus>>, pub multiple_webhooks_list: Option<Vec<MultipleWebhookDetail>>, } common_utils::impl_to_sql_from_sql_json!(WebhookDetails); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct BusinessPaymentLinkConfig { pub domain_name: Option<String>, #[serde(flatten)] pub default_config: Option<PaymentLinkConfigRequest>, pub business_specific_configs: Option<HashMap<String, PaymentLinkConfigRequest>>, pub allowed_domains: Option<HashSet<String>>, pub branding_visibility: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentLinkConfigRequest { pub theme: Option<String>, pub logo: Option<String>, pub seller_name: Option<String>, pub sdk_layout: Option<String>, pub display_sdk_only: Option<bool>, pub enabled_saved_payment_method: Option<bool>, pub hide_card_nickname_field: Option<bool>, pub show_card_form_by_default: Option<bool>, pub background_image: Option<PaymentLinkBackgroundImageConfig>, pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>, pub payment_button_text: Option<String>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub skip_status_screen: Option<bool>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: Option<bool>, pub payment_form_header_text: Option<String>, pub payment_form_label_type: Option<common_enums::PaymentLinkSdkLabelType>, pub show_card_terms: Option<common_enums::PaymentLinkShowSdkTerms>, pub is_setup_mandate_flow: Option<bool>, pub color_icon_card_cvc_error: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct PaymentLinkBackgroundImageConfig { pub url: common_utils::types::Url, pub position: Option<common_enums::ElementPosition>, pub size: Option<common_enums::ElementSize>, } common_utils::impl_to_sql_from_sql_json!(BusinessPaymentLinkConfig); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct BusinessPayoutLinkConfig { #[serde(flatten)] pub config: BusinessGenericLinkConfig, pub form_layout: Option<UIWidgetFormLayout>, pub payout_test_mode: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct BusinessGenericLinkConfig { pub domain_name: Option<String>, pub allowed_domains: HashSet<String>, #[serde(flatten)] pub ui_config: common_utils::link_utils::GenericLinkUiConfig, } common_utils::impl_to_sql_from_sql_json!(BusinessPayoutLinkConfig); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct RevenueRecoveryAlgorithmData { pub monitoring_configured_timestamp: time::PrimitiveDateTime, } impl RevenueRecoveryAlgorithmData { pub fn has_exceeded_monitoring_threshold(&self, monitoring_threshold_in_seconds: i64) -> bool { let total_threshold_time = self.monitoring_configured_timestamp + Duration::seconds(monitoring_threshold_in_seconds); common_utils::date_time::now() >= total_threshold_time } } common_utils::impl_to_sql_from_sql_json!(RevenueRecoveryAlgorithmData);
{ "crate": "diesel_models", "file": "crates/diesel_models/src/business_profile.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 17, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_2294970787369211024
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/payment_link.rs // Contains: 2 structs, 0 enums use common_utils::types::MinorUnit; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::payment_link}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = payment_link, primary_key(payment_link_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentLink { pub payment_link_id: String, pub payment_id: common_utils::id_type::PaymentId, pub link_to_pay: String, pub merchant_id: common_utils::id_type::MerchantId, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub fulfilment_time: Option<PrimitiveDateTime>, pub custom_merchant_name: Option<String>, pub payment_link_config: Option<serde_json::Value>, pub description: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub secure_link: Option<String>, } #[derive( Clone, Debug, Eq, PartialEq, Insertable, serde::Serialize, serde::Deserialize, router_derive::DebugAsDisplay, )] #[diesel(table_name = payment_link)] pub struct PaymentLinkNew { pub payment_link_id: String, pub payment_id: common_utils::id_type::PaymentId, pub link_to_pay: String, pub merchant_id: common_utils::id_type::MerchantId, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_modified_at: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub fulfilment_time: Option<PrimitiveDateTime>, pub custom_merchant_name: Option<String>, pub payment_link_config: Option<serde_json::Value>, pub description: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub secure_link: Option<String>, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/payment_link.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_8130228110692392707
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/invoice.rs // Contains: 3 structs, 0 enums use common_enums::connector_enums::{Connector, InvoiceStatus}; use common_utils::{id_type::GenerateId, pii::SecretSerdeValue, types::MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::invoice; #[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] #[diesel(table_name = invoice, check_for_backend(diesel::pg::Pg))] pub struct InvoiceNew { pub id: common_utils::id_type::InvoiceId, pub subscription_id: common_utils::id_type::SubscriptionId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_id: common_utils::id_type::ProfileId, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, pub payment_method_id: Option<String>, pub customer_id: common_utils::id_type::CustomerId, pub amount: MinorUnit, pub currency: String, pub status: InvoiceStatus, pub provider_name: Connector, pub metadata: Option<SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, } #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize, )] #[diesel( table_name = invoice, primary_key(id), check_for_backend(diesel::pg::Pg) )] pub struct Invoice { pub id: common_utils::id_type::InvoiceId, pub subscription_id: common_utils::id_type::SubscriptionId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_id: common_utils::id_type::ProfileId, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, pub payment_method_id: Option<String>, pub customer_id: common_utils::id_type::CustomerId, pub amount: MinorUnit, pub currency: String, pub status: InvoiceStatus, pub provider_name: Connector, pub metadata: Option<SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, } #[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Deserialize)] #[diesel(table_name = invoice)] pub struct InvoiceUpdate { pub status: Option<InvoiceStatus>, pub payment_method_id: Option<String>, pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, pub modified_at: time::PrimitiveDateTime, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, pub amount: Option<MinorUnit>, pub currency: Option<String>, } impl InvoiceNew { #[allow(clippy::too_many_arguments)] pub fn new( subscription_id: common_utils::id_type::SubscriptionId, merchant_id: common_utils::id_type::MerchantId, profile_id: common_utils::id_type::ProfileId, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, payment_intent_id: Option<common_utils::id_type::PaymentId>, payment_method_id: Option<String>, customer_id: common_utils::id_type::CustomerId, amount: MinorUnit, currency: String, status: InvoiceStatus, provider_name: Connector, metadata: Option<SecretSerdeValue>, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> Self { let id = common_utils::id_type::InvoiceId::generate(); let now = common_utils::date_time::now(); Self { id, subscription_id, merchant_id, profile_id, merchant_connector_id, payment_intent_id, payment_method_id, customer_id, amount, currency, status, provider_name, metadata, created_at: now, modified_at: now, connector_invoice_id, } } } impl InvoiceUpdate { pub fn new( amount: Option<MinorUnit>, currency: Option<String>, payment_method_id: Option<String>, status: Option<InvoiceStatus>, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, payment_intent_id: Option<common_utils::id_type::PaymentId>, ) -> Self { Self { status, payment_method_id, connector_invoice_id, modified_at: common_utils::date_time::now(), payment_intent_id, amount, currency, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/invoice.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-2307598010610317463
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/generic_link.rs // Contains: 7 structs, 2 enums use common_utils::{ consts, link_utils::{ EnabledPaymentMethod, GenericLinkStatus, GenericLinkUiConfig, PaymentMethodCollectStatus, PayoutLinkData, PayoutLinkStatus, }, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::{Duration, PrimitiveDateTime}; use crate::{enums as storage_enums, schema::generic_link}; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = generic_link, primary_key(link_id), check_for_backend(diesel::pg::Pg))] pub struct GenericLink { pub link_id: String, pub primary_reference: String, pub merchant_id: common_utils::id_type::MerchantId, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: PrimitiveDateTime, pub link_data: serde_json::Value, pub link_status: GenericLinkStatus, pub link_type: storage_enums::GenericLinkType, pub url: Secret<String>, pub return_url: Option<String>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct GenericLinkState { pub link_id: String, pub primary_reference: String, pub merchant_id: common_utils::id_type::MerchantId, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: PrimitiveDateTime, pub link_data: GenericLinkData, pub link_status: GenericLinkStatus, pub link_type: storage_enums::GenericLinkType, pub url: Secret<String>, pub return_url: Option<String>, } #[derive( Clone, Debug, Eq, PartialEq, Insertable, serde::Serialize, serde::Deserialize, router_derive::DebugAsDisplay, )] #[diesel(table_name = generic_link)] pub struct GenericLinkNew { pub link_id: String, pub primary_reference: String, pub merchant_id: common_utils::id_type::MerchantId, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_modified_at: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: PrimitiveDateTime, pub link_data: serde_json::Value, pub link_status: GenericLinkStatus, pub link_type: storage_enums::GenericLinkType, pub url: Secret<String>, pub return_url: Option<String>, } impl Default for GenericLinkNew { fn default() -> Self { let now = common_utils::date_time::now(); Self { link_id: String::default(), primary_reference: String::default(), merchant_id: common_utils::id_type::MerchantId::default(), created_at: Some(now), last_modified_at: Some(now), expiry: now + Duration::seconds(consts::DEFAULT_SESSION_EXPIRY), link_data: serde_json::Value::default(), link_status: GenericLinkStatus::default(), link_type: common_enums::GenericLinkType::default(), url: Secret::default(), return_url: Option::default(), } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GenericLinkData { PaymentMethodCollect(PaymentMethodCollectLinkData), PayoutLink(PayoutLinkData), } impl GenericLinkData { pub fn get_payment_method_collect_data(&self) -> Result<&PaymentMethodCollectLinkData, String> { match self { Self::PaymentMethodCollect(pm) => Ok(pm), _ => Err("Invalid link type for fetching payment method collect data".to_string()), } } pub fn get_payout_link_data(&self) -> Result<&PayoutLinkData, String> { match self { Self::PayoutLink(pl) => Ok(pl), _ => Err("Invalid link type for fetching payout link data".to_string()), } } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PaymentMethodCollectLink { pub link_id: String, pub primary_reference: String, pub merchant_id: common_utils::id_type::MerchantId, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: PrimitiveDateTime, pub link_data: PaymentMethodCollectLinkData, pub link_status: PaymentMethodCollectStatus, pub link_type: storage_enums::GenericLinkType, pub url: Secret<String>, pub return_url: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentMethodCollectLinkData { pub pm_collect_link_id: String, pub customer_id: common_utils::id_type::CustomerId, pub link: Secret<String>, pub client_secret: Secret<String>, pub session_expiry: u32, #[serde(flatten)] pub ui_config: GenericLinkUiConfig, pub enabled_payment_methods: Option<Vec<EnabledPaymentMethod>>, } #[derive(Clone, Debug, Identifiable, Queryable, Serialize, Deserialize)] #[diesel(table_name = generic_link)] #[diesel(primary_key(link_id))] pub struct PayoutLink { pub link_id: String, pub primary_reference: common_utils::id_type::PayoutId, pub merchant_id: common_utils::id_type::MerchantId, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: PrimitiveDateTime, pub link_data: PayoutLinkData, pub link_status: PayoutLinkStatus, pub link_type: storage_enums::GenericLinkType, pub url: Secret<String>, pub return_url: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PayoutLinkUpdate { StatusUpdate { link_status: PayoutLinkStatus }, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = generic_link)] pub struct GenericLinkUpdateInternal { pub link_status: Option<GenericLinkStatus>, } impl From<PayoutLinkUpdate> for GenericLinkUpdateInternal { fn from(generic_link_update: PayoutLinkUpdate) -> Self { match generic_link_update { PayoutLinkUpdate::StatusUpdate { link_status } => Self { link_status: Some(GenericLinkStatus::PayoutLink(link_status)), }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/generic_link.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 7, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_7930849895995780115
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/unified_translations.rs // Contains: 4 structs, 0 enums //! Translations use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::schema::unified_translations; #[derive(Clone, Debug, Queryable, Selectable, Identifiable)] #[diesel(table_name = unified_translations, primary_key(unified_code, unified_message, locale), check_for_backend(diesel::pg::Pg))] pub struct UnifiedTranslations { pub unified_code: String, pub unified_message: String, pub locale: String, pub translation: String, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, } #[derive(Clone, Debug, Insertable)] #[diesel(table_name = unified_translations)] pub struct UnifiedTranslationsNew { pub unified_code: String, pub unified_message: String, pub locale: String, pub translation: String, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, } #[derive(Clone, Debug, AsChangeset)] #[diesel(table_name = unified_translations)] pub struct UnifiedTranslationsUpdateInternal { pub translation: Option<String>, pub last_modified_at: PrimitiveDateTime, } #[derive(Debug)] pub struct UnifiedTranslationsUpdate { pub translation: Option<String>, } impl From<UnifiedTranslationsUpdate> for UnifiedTranslationsUpdateInternal { fn from(value: UnifiedTranslationsUpdate) -> Self { let now = common_utils::date_time::now(); let UnifiedTranslationsUpdate { translation } = value; Self { translation, last_modified_at: now, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/unified_translations.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-5183463622451718606
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/api_keys.rs // Contains: 5 structs, 1 enums use diesel::{AsChangeset, AsExpression, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::schema::api_keys; #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, Identifiable, Queryable, Selectable, )] #[diesel(table_name = api_keys, primary_key(key_id), check_for_backend(diesel::pg::Pg))] pub struct ApiKey { pub key_id: common_utils::id_type::ApiKeyId, pub merchant_id: common_utils::id_type::MerchantId, pub name: String, pub description: Option<String>, pub hashed_api_key: HashedApiKey, pub prefix: String, pub created_at: PrimitiveDateTime, pub expires_at: Option<PrimitiveDateTime>, pub last_used: Option<PrimitiveDateTime>, } #[derive(Debug, Insertable)] #[diesel(table_name = api_keys)] pub struct ApiKeyNew { pub key_id: common_utils::id_type::ApiKeyId, pub merchant_id: common_utils::id_type::MerchantId, pub name: String, pub description: Option<String>, pub hashed_api_key: HashedApiKey, pub prefix: String, pub created_at: PrimitiveDateTime, pub expires_at: Option<PrimitiveDateTime>, pub last_used: Option<PrimitiveDateTime>, } #[derive(Debug)] pub enum ApiKeyUpdate { Update { name: Option<String>, description: Option<String>, expires_at: Option<Option<PrimitiveDateTime>>, last_used: Option<PrimitiveDateTime>, }, LastUsedUpdate { last_used: PrimitiveDateTime, }, } #[derive(Debug, AsChangeset)] #[diesel(table_name = api_keys)] pub(crate) struct ApiKeyUpdateInternal { pub name: Option<String>, pub description: Option<String>, pub expires_at: Option<Option<PrimitiveDateTime>>, pub last_used: Option<PrimitiveDateTime>, } impl From<ApiKeyUpdate> for ApiKeyUpdateInternal { fn from(api_key_update: ApiKeyUpdate) -> Self { match api_key_update { ApiKeyUpdate::Update { name, description, expires_at, last_used, } => Self { name, description, expires_at, last_used, }, ApiKeyUpdate::LastUsedUpdate { last_used } => Self { last_used: Some(last_used), name: None, description: None, expires_at: None, }, } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, AsExpression, PartialEq)] #[diesel(sql_type = diesel::sql_types::Text)] pub struct HashedApiKey(String); impl HashedApiKey { pub fn into_inner(self) -> String { self.0 } } impl From<String> for HashedApiKey { fn from(hashed_api_key: String) -> Self { Self(hashed_api_key) } } mod diesel_impl { use diesel::{ backend::Backend, deserialize::FromSql, serialize::{Output, ToSql}, sql_types::Text, Queryable, }; impl<DB> ToSql<Text, DB> for super::HashedApiKey where DB: Backend, String: ToSql<Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> FromSql<Text, DB> for super::HashedApiKey where DB: Backend, String: FromSql<Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { Ok(Self(String::from_sql(bytes)?)) } } impl<DB> Queryable<Text, DB> for super::HashedApiKey where DB: Backend, Self: FromSql<Text, DB>, { type Row = Self; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { Ok(row) } } } // Tracking data by process_tracker #[derive(Default, Debug, Deserialize, Serialize, Clone)] pub struct ApiKeyExpiryTrackingData { pub key_id: common_utils::id_type::ApiKeyId, pub merchant_id: common_utils::id_type::MerchantId, pub api_key_name: String, pub prefix: String, pub api_key_expiry: Option<PrimitiveDateTime>, // Days on which email reminder about api_key expiry has to be sent, prior to it's expiry. pub expiry_reminder_days: Vec<u8>, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/api_keys.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-3658438736573738542
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/customers.rs // Contains: 6 structs, 0 enums use common_enums::ApiVersion; use common_utils::{encryption::Encryption, pii, types::Description}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::schema::customers; #[cfg(feature = "v2")] use crate::{ diesel_impl::RequiredFromNullableWithDefault, enums::DeleteStatus, schema_v2::customers, }; #[cfg(feature = "v1")] #[derive( Clone, Debug, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, Insertable, )] #[diesel(table_name = customers)] pub struct CustomerNew { pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub description: Option<Description>, pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<pii::SecretSerdeValue>, pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub address_id: Option<String>, pub updated_by: Option<String>, pub version: ApiVersion, pub tax_registration_id: Option<Encryption>, } #[cfg(feature = "v1")] impl CustomerNew { pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } } #[cfg(feature = "v1")] impl From<CustomerNew> for Customer { fn from(customer_new: CustomerNew) -> Self { Self { customer_id: customer_new.customer_id, merchant_id: customer_new.merchant_id, name: customer_new.name, email: customer_new.email, phone: customer_new.phone, phone_country_code: customer_new.phone_country_code, description: customer_new.description, created_at: customer_new.created_at, metadata: customer_new.metadata, connector_customer: customer_new.connector_customer, modified_at: customer_new.modified_at, address_id: customer_new.address_id, default_payment_method_id: None, updated_by: customer_new.updated_by, version: customer_new.version, tax_registration_id: customer_new.tax_registration_id, } } } #[cfg(feature = "v2")] #[derive( Clone, Debug, Insertable, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, )] #[diesel(table_name = customers, primary_key(id))] pub struct CustomerNew { pub merchant_id: common_utils::id_type::MerchantId, pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub modified_at: PrimitiveDateTime, pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, pub version: ApiVersion, pub tax_registration_id: Option<Encryption>, pub merchant_reference_id: Option<common_utils::id_type::CustomerId>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, pub status: DeleteStatus, pub id: common_utils::id_type::GlobalCustomerId, } #[cfg(feature = "v2")] impl CustomerNew { pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } } #[cfg(feature = "v2")] impl From<CustomerNew> for Customer { fn from(customer_new: CustomerNew) -> Self { Self { merchant_id: customer_new.merchant_id, name: customer_new.name, email: customer_new.email, phone: customer_new.phone, phone_country_code: customer_new.phone_country_code, description: customer_new.description, created_at: customer_new.created_at, metadata: customer_new.metadata, connector_customer: customer_new.connector_customer, modified_at: customer_new.modified_at, default_payment_method_id: None, updated_by: customer_new.updated_by, tax_registration_id: customer_new.tax_registration_id, merchant_reference_id: customer_new.merchant_reference_id, default_billing_address: customer_new.default_billing_address, default_shipping_address: customer_new.default_shipping_address, id: customer_new.id, version: customer_new.version, status: customer_new.status, } } } #[cfg(feature = "v1")] #[derive( Clone, Debug, Identifiable, Queryable, Selectable, serde::Deserialize, serde::Serialize, )] #[diesel(table_name = customers, primary_key(customer_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct Customer { pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, pub address_id: Option<String>, pub default_payment_method_id: Option<String>, pub updated_by: Option<String>, pub version: ApiVersion, pub tax_registration_id: Option<Encryption>, } #[cfg(feature = "v2")] #[derive( Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = customers, primary_key(id))] pub struct Customer { pub merchant_id: common_utils::id_type::MerchantId, pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub modified_at: PrimitiveDateTime, pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, pub version: ApiVersion, pub tax_registration_id: Option<Encryption>, pub merchant_reference_id: Option<common_utils::id_type::CustomerId>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, #[diesel(deserialize_as = RequiredFromNullableWithDefault<DeleteStatus>)] pub status: DeleteStatus, pub id: common_utils::id_type::GlobalCustomerId, } #[cfg(feature = "v1")] #[derive( Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, )] #[diesel(table_name = customers)] pub struct CustomerUpdateInternal { pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub description: Option<Description>, pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, pub connector_customer: Option<pii::SecretSerdeValue>, pub address_id: Option<String>, pub default_payment_method_id: Option<Option<String>>, pub updated_by: Option<String>, pub tax_registration_id: Option<Encryption>, } #[cfg(feature = "v1")] impl CustomerUpdateInternal { pub fn apply_changeset(self, source: Customer) -> Customer { let Self { name, email, phone, description, phone_country_code, metadata, connector_customer, address_id, default_payment_method_id, tax_registration_id, .. } = self; Customer { name: name.map_or(source.name, Some), email: email.map_or(source.email, Some), phone: phone.map_or(source.phone, Some), description: description.map_or(source.description, Some), phone_country_code: phone_country_code.map_or(source.phone_country_code, Some), metadata: metadata.map_or(source.metadata, Some), modified_at: common_utils::date_time::now(), connector_customer: connector_customer.map_or(source.connector_customer, Some), address_id: address_id.map_or(source.address_id, Some), default_payment_method_id: default_payment_method_id .flatten() .map_or(source.default_payment_method_id, Some), tax_registration_id: tax_registration_id.map_or(source.tax_registration_id, Some), ..source } } } #[cfg(feature = "v2")] #[derive( Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, )] #[diesel(table_name = customers)] pub struct CustomerUpdateInternal { pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub description: Option<Description>, pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub default_payment_method_id: Option<Option<common_utils::id_type::GlobalPaymentMethodId>>, pub updated_by: Option<String>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, pub status: Option<DeleteStatus>, pub tax_registration_id: Option<Encryption>, } #[cfg(feature = "v2")] impl CustomerUpdateInternal { pub fn apply_changeset(self, source: Customer) -> Customer { let Self { name, email, phone, description, phone_country_code, metadata, connector_customer, default_payment_method_id, default_billing_address, default_shipping_address, status, tax_registration_id, .. } = self; Customer { name: name.map_or(source.name, Some), email: email.map_or(source.email, Some), phone: phone.map_or(source.phone, Some), description: description.map_or(source.description, Some), phone_country_code: phone_country_code.map_or(source.phone_country_code, Some), metadata: metadata.map_or(source.metadata, Some), modified_at: common_utils::date_time::now(), connector_customer: connector_customer.map_or(source.connector_customer, Some), default_payment_method_id: default_payment_method_id .flatten() .map_or(source.default_payment_method_id, Some), default_billing_address: default_billing_address .map_or(source.default_billing_address, Some), default_shipping_address: default_shipping_address .map_or(source.default_shipping_address, Some), status: status.unwrap_or(source.status), tax_registration_id: tax_registration_id.map_or(source.tax_registration_id, Some), ..source } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/customers.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_8008319850368681339
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/gsm.rs // Contains: 4 structs, 0 enums //! Gateway status mapping use common_enums::ErrorCategory; use common_utils::{ custom_serde, events::{ApiEventMetric, ApiEventsType}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::schema::gateway_status_map; #[derive( Clone, Debug, Eq, PartialEq, router_derive::DebugAsDisplay, Identifiable, Queryable, Selectable, serde::Serialize, )] #[diesel(table_name = gateway_status_map, primary_key(connector, flow, sub_flow, code, message), check_for_backend(diesel::pg::Pg))] pub struct GatewayStatusMap { pub connector: String, pub flow: String, pub sub_flow: String, pub code: String, pub message: String, pub status: String, pub router_error: Option<String>, pub decision: String, #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "custom_serde::iso8601")] pub last_modified: PrimitiveDateTime, pub step_up_possible: bool, pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: bool, pub feature_data: Option<common_types::domain::GsmFeatureData>, pub feature: Option<common_enums::GsmFeature>, } #[derive(Clone, Debug, Eq, PartialEq, Insertable)] #[diesel(table_name = gateway_status_map)] pub struct GatewayStatusMappingNew { pub connector: String, pub flow: String, pub sub_flow: String, pub code: String, pub message: String, pub status: String, pub router_error: Option<String>, pub decision: String, pub step_up_possible: bool, pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: bool, pub feature_data: Option<common_types::domain::GsmFeatureData>, pub feature: Option<common_enums::GsmFeature>, } #[derive( Clone, Debug, PartialEq, Eq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, )] #[diesel(table_name = gateway_status_map)] pub struct GatewayStatusMapperUpdateInternal { pub connector: Option<String>, pub flow: Option<String>, pub sub_flow: Option<String>, pub code: Option<String>, pub message: Option<String>, pub status: Option<String>, pub router_error: Option<Option<String>>, pub decision: Option<String>, pub step_up_possible: Option<bool>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub last_modified: PrimitiveDateTime, pub clear_pan_possible: Option<bool>, pub feature_data: Option<common_types::domain::GsmFeatureData>, pub feature: Option<common_enums::GsmFeature>, } #[derive(Debug)] pub struct GatewayStatusMappingUpdate { pub status: Option<String>, pub router_error: Option<Option<String>>, pub decision: Option<String>, pub step_up_possible: Option<bool>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: Option<bool>, pub feature_data: Option<common_types::domain::GsmFeatureData>, pub feature: Option<common_enums::GsmFeature>, } impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { fn from(value: GatewayStatusMappingUpdate) -> Self { let GatewayStatusMappingUpdate { decision, status, router_error, step_up_possible, unified_code, unified_message, error_category, clear_pan_possible, feature_data, feature, } = value; Self { status, router_error, decision, step_up_possible, unified_code, unified_message, error_category, last_modified: common_utils::date_time::now(), connector: None, flow: None, sub_flow: None, code: None, message: None, clear_pan_possible, feature_data, feature, } } } impl ApiEventMetric for GatewayStatusMap { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/gsm.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_4936269879160455467
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/hyperswitch_ai_interaction.rs // Contains: 2 structs, 0 enums use common_utils::encryption::Encryption; use diesel::{self, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::schema::hyperswitch_ai_interaction; #[derive( Clone, Debug, Deserialize, Identifiable, Queryable, Selectable, Serialize, router_derive::DebugAsDisplay, )] #[diesel(table_name = hyperswitch_ai_interaction, primary_key(id, created_at), check_for_backend(diesel::pg::Pg))] pub struct HyperswitchAiInteraction { 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: Option<Encryption>, pub response: Option<Encryption>, pub database_query: Option<String>, pub interaction_status: Option<String>, pub created_at: PrimitiveDateTime, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = hyperswitch_ai_interaction)] pub struct HyperswitchAiInteractionNew { 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: Option<Encryption>, pub response: Option<Encryption>, pub database_query: Option<String>, pub interaction_status: Option<String>, pub created_at: PrimitiveDateTime, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/hyperswitch_ai_interaction.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_7063426453582926996
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/payout_attempt.rs // Contains: 3 structs, 1 enums use common_utils::{ payout_method_utils, pii, types::{UnifiedCode, UnifiedMessage}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::payout_attempt}; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = payout_attempt, primary_key(payout_attempt_id), check_for_backend(diesel::pg::Pg))] pub struct PayoutAttempt { pub payout_attempt_id: String, pub payout_id: common_utils::id_type::PayoutId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_id: common_utils::id_type::MerchantId, pub address_id: Option<String>, pub connector: Option<String>, pub connector_payout_id: Option<String>, pub payout_token: Option<String>, pub status: storage_enums::PayoutStatus, pub is_eligible: Option<bool>, pub error_message: Option<String>, pub error_code: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, pub profile_id: common_utils::id_type::ProfileId, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub merchant_order_reference_id: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive( Clone, Debug, Eq, PartialEq, Insertable, serde::Serialize, serde::Deserialize, router_derive::DebugAsDisplay, router_derive::Setter, )] #[diesel(table_name = payout_attempt)] pub struct PayoutAttemptNew { pub payout_attempt_id: String, pub payout_id: common_utils::id_type::PayoutId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_id: common_utils::id_type::MerchantId, pub address_id: Option<String>, pub connector: Option<String>, pub connector_payout_id: Option<String>, pub payout_token: Option<String>, pub status: storage_enums::PayoutStatus, pub is_eligible: Option<bool>, pub error_message: Option<String>, pub error_code: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, pub profile_id: common_utils::id_type::ProfileId, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub merchant_order_reference_id: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PayoutAttemptUpdate { StatusUpdate { connector_payout_id: Option<String>, status: storage_enums::PayoutStatus, error_message: Option<String>, error_code: Option<String>, is_eligible: Option<bool>, unified_code: Option<UnifiedCode>, unified_message: Option<UnifiedMessage>, payout_connector_metadata: Option<pii::SecretSerdeValue>, }, PayoutTokenUpdate { payout_token: String, }, BusinessUpdate { business_country: Option<storage_enums::CountryAlpha2>, business_label: Option<String>, address_id: Option<String>, customer_id: Option<common_utils::id_type::CustomerId>, }, UpdateRouting { connector: String, routing_info: Option<serde_json::Value>, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, }, AdditionalPayoutMethodDataUpdate { additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, }, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payout_attempt)] pub struct PayoutAttemptUpdateInternal { pub payout_token: Option<String>, pub connector_payout_id: Option<String>, pub status: Option<storage_enums::PayoutStatus>, pub error_message: Option<String>, pub error_code: Option<String>, pub is_eligible: Option<bool>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub connector: Option<String>, pub routing_info: Option<serde_json::Value>, pub last_modified_at: PrimitiveDateTime, pub address_id: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub merchant_order_reference_id: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } impl Default for PayoutAttemptUpdateInternal { fn default() -> Self { Self { payout_token: None, connector_payout_id: None, status: None, error_message: None, error_code: None, is_eligible: None, business_country: None, business_label: None, connector: None, routing_info: None, merchant_connector_id: None, last_modified_at: common_utils::date_time::now(), address_id: None, customer_id: None, unified_code: None, unified_message: None, additional_payout_method_data: None, merchant_order_reference_id: None, payout_connector_metadata: None, } } } impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal { fn from(payout_update: PayoutAttemptUpdate) -> Self { match payout_update { PayoutAttemptUpdate::PayoutTokenUpdate { payout_token } => Self { payout_token: Some(payout_token), ..Default::default() }, PayoutAttemptUpdate::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, } => Self { connector_payout_id, status: Some(status), error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, ..Default::default() }, PayoutAttemptUpdate::BusinessUpdate { business_country, business_label, address_id, customer_id, } => Self { business_country, business_label, address_id, customer_id, ..Default::default() }, PayoutAttemptUpdate::UpdateRouting { connector, routing_info, merchant_connector_id, } => Self { connector: Some(connector), routing_info, merchant_connector_id, ..Default::default() }, PayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, } => Self { additional_payout_method_data, ..Default::default() }, } } } impl PayoutAttemptUpdate { pub fn apply_changeset(self, source: PayoutAttempt) -> PayoutAttempt { let PayoutAttemptUpdateInternal { payout_token, connector_payout_id, status, error_message, error_code, is_eligible, business_country, business_label, connector, routing_info, last_modified_at, address_id, customer_id, merchant_connector_id, unified_code, unified_message, additional_payout_method_data, merchant_order_reference_id, payout_connector_metadata, } = self.into(); PayoutAttempt { payout_token: payout_token.or(source.payout_token), connector_payout_id: connector_payout_id.or(source.connector_payout_id), status: status.unwrap_or(source.status), error_message: error_message.or(source.error_message), error_code: error_code.or(source.error_code), is_eligible: is_eligible.or(source.is_eligible), business_country: business_country.or(source.business_country), business_label: business_label.or(source.business_label), connector: connector.or(source.connector), routing_info: routing_info.or(source.routing_info), last_modified_at, address_id: address_id.or(source.address_id), customer_id: customer_id.or(source.customer_id), merchant_connector_id: merchant_connector_id.or(source.merchant_connector_id), unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), additional_payout_method_data: additional_payout_method_data .or(source.additional_payout_method_data), merchant_order_reference_id: merchant_order_reference_id .or(source.merchant_order_reference_id), payout_connector_metadata: payout_connector_metadata .or(source.payout_connector_metadata), ..source } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/payout_attempt.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-3395068887327304885
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/authentication.rs // Contains: 3 structs, 1 enums use std::str::FromStr; use common_utils::{ encryption::Encryption, errors::{CustomResult, ValidationError}, pii, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use error_stack::ResultExt; use serde::{self, Deserialize, Serialize}; use serde_json; use crate::schema::authentication; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = authentication, primary_key(authentication_id), check_for_backend(diesel::pg::Pg))] pub struct Authentication { pub authentication_id: common_utils::id_type::AuthenticationId, pub merchant_id: common_utils::id_type::MerchantId, pub authentication_connector: Option<String>, pub connector_authentication_id: Option<String>, pub authentication_data: Option<serde_json::Value>, pub payment_method_id: String, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, pub authentication_status: common_enums::AuthenticationStatus, pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: time::PrimitiveDateTime, pub error_message: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<String>, pub cavv: Option<String>, pub authentication_flow_type: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<String>, pub trans_status: Option<common_enums::TransactionStatus>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub acs_url: Option<String>, pub challenge_request: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub profile_id: common_utils::id_type::ProfileId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, pub acquirer_country_code: Option<String>, pub service_details: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub authentication_client_secret: Option<String>, pub force_3ds_challenge: Option<bool>, pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, pub return_url: Option<String>, pub amount: Option<common_utils::types::MinorUnit>, pub currency: Option<common_enums::Currency>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub browser_info: Option<serde_json::Value>, pub email: Option<Encryption>, pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>, pub challenge_code: Option<String>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, pub message_extension: Option<pii::SecretSerdeValue>, pub challenge_request_key: Option<String>, } impl Authentication { pub fn is_separate_authn_required(&self) -> bool { self.maximum_supported_version .as_ref() .is_some_and(|version| version.get_major() == 2) } // get authentication_connector from authentication record and check if it is jwt flow pub fn is_jwt_flow(&self) -> CustomResult<bool, ValidationError> { Ok(self .authentication_connector .clone() .map(|connector| { common_enums::AuthenticationConnectors::from_str(&connector) .change_context(ValidationError::InvalidValue { message: "failed to parse authentication_connector".to_string(), }) .map(|connector_enum| connector_enum.is_jwt_flow()) }) .transpose()? .unwrap_or(false)) } } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Insertable)] #[diesel(table_name = authentication)] pub struct AuthenticationNew { pub authentication_id: common_utils::id_type::AuthenticationId, pub merchant_id: common_utils::id_type::MerchantId, pub authentication_connector: Option<String>, pub connector_authentication_id: Option<String>, // pub authentication_data: Option<serde_json::Value>, pub payment_method_id: String, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, pub authentication_status: common_enums::AuthenticationStatus, pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus, pub error_message: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<String>, pub cavv: Option<String>, pub authentication_flow_type: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<String>, pub trans_status: Option<common_enums::TransactionStatus>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub acs_url: Option<String>, pub challenge_request: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub profile_id: common_utils::id_type::ProfileId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, pub acquirer_country_code: Option<String>, pub service_details: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub authentication_client_secret: Option<String>, pub force_3ds_challenge: Option<bool>, pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, pub return_url: Option<String>, pub amount: Option<common_utils::types::MinorUnit>, pub currency: Option<common_enums::Currency>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub browser_info: Option<serde_json::Value>, pub email: Option<Encryption>, pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>, pub challenge_code: Option<String>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, pub message_extension: Option<pii::SecretSerdeValue>, pub challenge_request_key: Option<String>, } #[derive(Debug)] pub enum AuthenticationUpdate { PreAuthenticationVersionCallUpdate { maximum_supported_3ds_version: common_utils::types::SemanticVersion, message_version: common_utils::types::SemanticVersion, }, PreAuthenticationThreeDsMethodCall { threeds_server_transaction_id: String, three_ds_method_data: Option<String>, three_ds_method_url: Option<String>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, connector_metadata: Option<serde_json::Value>, }, PreAuthenticationUpdate { threeds_server_transaction_id: String, maximum_supported_3ds_version: common_utils::types::SemanticVersion, connector_authentication_id: String, three_ds_method_data: Option<String>, three_ds_method_url: Option<String>, message_version: common_utils::types::SemanticVersion, connector_metadata: Option<serde_json::Value>, authentication_status: common_enums::AuthenticationStatus, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, directory_server_id: Option<String>, acquirer_country_code: Option<String>, billing_address: Option<Encryption>, shipping_address: Option<Encryption>, browser_info: Box<Option<serde_json::Value>>, email: Option<Encryption>, }, AuthenticationUpdate { trans_status: common_enums::TransactionStatus, authentication_type: common_enums::DecoupledAuthenticationType, acs_url: Option<String>, challenge_request: Option<String>, acs_reference_number: Option<String>, acs_trans_id: Option<String>, acs_signed_content: Option<String>, connector_metadata: Option<serde_json::Value>, authentication_status: common_enums::AuthenticationStatus, ds_trans_id: Option<String>, eci: Option<String>, challenge_code: Option<String>, challenge_cancel: Option<String>, challenge_code_reason: Option<String>, message_extension: Option<pii::SecretSerdeValue>, challenge_request_key: Option<String>, }, PostAuthenticationUpdate { trans_status: common_enums::TransactionStatus, eci: Option<String>, authentication_status: common_enums::AuthenticationStatus, challenge_cancel: Option<String>, challenge_code_reason: Option<String>, }, ErrorUpdate { error_message: Option<String>, error_code: Option<String>, authentication_status: common_enums::AuthenticationStatus, connector_authentication_id: Option<String>, }, PostAuthorizationUpdate { authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus, }, AuthenticationStatusUpdate { trans_status: common_enums::TransactionStatus, authentication_status: common_enums::AuthenticationStatus, }, } #[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Serialize, Deserialize)] #[diesel(table_name = authentication)] pub struct AuthenticationUpdateInternal { pub connector_authentication_id: Option<String>, // pub authentication_data: Option<serde_json::Value>, pub payment_method_id: Option<String>, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, pub authentication_status: Option<common_enums::AuthenticationStatus>, pub authentication_lifecycle_status: Option<common_enums::AuthenticationLifecycleStatus>, pub modified_at: time::PrimitiveDateTime, pub error_message: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<String>, pub authentication_flow_type: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<String>, pub trans_status: Option<common_enums::TransactionStatus>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub acs_url: Option<String>, pub challenge_request: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, pub acquirer_country_code: Option<String>, pub service_details: Option<serde_json::Value>, pub force_3ds_challenge: Option<bool>, pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub browser_info: Option<serde_json::Value>, pub email: Option<Encryption>, pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>, pub challenge_code: Option<String>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, pub message_extension: Option<pii::SecretSerdeValue>, pub challenge_request_key: Option<String>, } impl Default for AuthenticationUpdateInternal { fn default() -> Self { Self { connector_authentication_id: Default::default(), payment_method_id: Default::default(), authentication_type: Default::default(), authentication_status: Default::default(), authentication_lifecycle_status: Default::default(), modified_at: common_utils::date_time::now(), error_message: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), maximum_supported_version: Default::default(), threeds_server_transaction_id: Default::default(), authentication_flow_type: Default::default(), message_version: Default::default(), eci: Default::default(), trans_status: Default::default(), acquirer_bin: Default::default(), acquirer_merchant_id: Default::default(), three_ds_method_data: Default::default(), three_ds_method_url: Default::default(), acs_url: Default::default(), challenge_request: Default::default(), acs_reference_number: Default::default(), acs_trans_id: Default::default(), acs_signed_content: Default::default(), ds_trans_id: Default::default(), directory_server_id: Default::default(), acquirer_country_code: Default::default(), service_details: Default::default(), force_3ds_challenge: Default::default(), psd2_sca_exemption_type: Default::default(), billing_address: Default::default(), shipping_address: Default::default(), browser_info: Default::default(), email: Default::default(), profile_acquirer_id: Default::default(), challenge_code: Default::default(), challenge_cancel: Default::default(), challenge_code_reason: Default::default(), message_extension: Default::default(), challenge_request_key: Default::default(), } } } impl AuthenticationUpdateInternal { pub fn apply_changeset(self, source: Authentication) -> Authentication { let Self { connector_authentication_id, payment_method_id, authentication_type, authentication_status, authentication_lifecycle_status, modified_at: _, error_code, error_message, connector_metadata, maximum_supported_version, threeds_server_transaction_id, authentication_flow_type, message_version, eci, trans_status, acquirer_bin, acquirer_merchant_id, three_ds_method_data, three_ds_method_url, acs_url, challenge_request, acs_reference_number, acs_trans_id, acs_signed_content, ds_trans_id, directory_server_id, acquirer_country_code, service_details, force_3ds_challenge, psd2_sca_exemption_type, billing_address, shipping_address, browser_info, email, profile_acquirer_id, challenge_code, challenge_cancel, challenge_code_reason, message_extension, challenge_request_key, } = self; Authentication { connector_authentication_id: connector_authentication_id .or(source.connector_authentication_id), payment_method_id: payment_method_id.unwrap_or(source.payment_method_id), authentication_type: authentication_type.or(source.authentication_type), authentication_status: authentication_status.unwrap_or(source.authentication_status), authentication_lifecycle_status: authentication_lifecycle_status .unwrap_or(source.authentication_lifecycle_status), modified_at: common_utils::date_time::now(), error_code: error_code.or(source.error_code), error_message: error_message.or(source.error_message), connector_metadata: connector_metadata.or(source.connector_metadata), maximum_supported_version: maximum_supported_version .or(source.maximum_supported_version), threeds_server_transaction_id: threeds_server_transaction_id .or(source.threeds_server_transaction_id), authentication_flow_type: authentication_flow_type.or(source.authentication_flow_type), message_version: message_version.or(source.message_version), eci: eci.or(source.eci), trans_status: trans_status.or(source.trans_status), acquirer_bin: acquirer_bin.or(source.acquirer_bin), acquirer_merchant_id: acquirer_merchant_id.or(source.acquirer_merchant_id), three_ds_method_data: three_ds_method_data.or(source.three_ds_method_data), three_ds_method_url: three_ds_method_url.or(source.three_ds_method_url), acs_url: acs_url.or(source.acs_url), challenge_request: challenge_request.or(source.challenge_request), acs_reference_number: acs_reference_number.or(source.acs_reference_number), acs_trans_id: acs_trans_id.or(source.acs_trans_id), acs_signed_content: acs_signed_content.or(source.acs_signed_content), ds_trans_id: ds_trans_id.or(source.ds_trans_id), directory_server_id: directory_server_id.or(source.directory_server_id), acquirer_country_code: acquirer_country_code.or(source.acquirer_country_code), service_details: service_details.or(source.service_details), force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge), psd2_sca_exemption_type: psd2_sca_exemption_type.or(source.psd2_sca_exemption_type), billing_address: billing_address.or(source.billing_address), shipping_address: shipping_address.or(source.shipping_address), browser_info: browser_info.or(source.browser_info), email: email.or(source.email), profile_acquirer_id: profile_acquirer_id.or(source.profile_acquirer_id), challenge_code: challenge_code.or(source.challenge_code), challenge_cancel: challenge_cancel.or(source.challenge_cancel), challenge_code_reason: challenge_code_reason.or(source.challenge_code_reason), message_extension: message_extension.or(source.message_extension), challenge_request_key: challenge_request_key.or(source.challenge_request_key), ..source } } } impl From<AuthenticationUpdate> for AuthenticationUpdateInternal { fn from(auth_update: AuthenticationUpdate) -> Self { match auth_update { AuthenticationUpdate::ErrorUpdate { error_message, error_code, authentication_status, connector_authentication_id, } => Self { error_code, error_message, authentication_status: Some(authentication_status), connector_authentication_id, authentication_type: None, authentication_lifecycle_status: None, modified_at: common_utils::date_time::now(), payment_method_id: None, connector_metadata: None, ..Default::default() }, AuthenticationUpdate::PostAuthorizationUpdate { authentication_lifecycle_status, } => Self { connector_authentication_id: None, payment_method_id: None, authentication_type: None, authentication_status: None, authentication_lifecycle_status: Some(authentication_lifecycle_status), modified_at: common_utils::date_time::now(), error_message: None, error_code: None, connector_metadata: None, ..Default::default() }, AuthenticationUpdate::PreAuthenticationUpdate { threeds_server_transaction_id, maximum_supported_3ds_version, connector_authentication_id, three_ds_method_data, three_ds_method_url, message_version, connector_metadata, authentication_status, acquirer_bin, acquirer_merchant_id, directory_server_id, acquirer_country_code, billing_address, shipping_address, browser_info, email, } => Self { threeds_server_transaction_id: Some(threeds_server_transaction_id), maximum_supported_version: Some(maximum_supported_3ds_version), connector_authentication_id: Some(connector_authentication_id), three_ds_method_data, three_ds_method_url, message_version: Some(message_version), connector_metadata, authentication_status: Some(authentication_status), acquirer_bin, acquirer_merchant_id, directory_server_id, acquirer_country_code, billing_address, shipping_address, browser_info: *browser_info, email, ..Default::default() }, AuthenticationUpdate::AuthenticationUpdate { trans_status, authentication_type, acs_url, challenge_request, acs_reference_number, acs_trans_id, acs_signed_content, connector_metadata, authentication_status, ds_trans_id, eci, challenge_code, challenge_cancel, challenge_code_reason, message_extension, challenge_request_key, } => Self { trans_status: Some(trans_status), authentication_type: Some(authentication_type), acs_url, challenge_request, acs_reference_number, acs_trans_id, acs_signed_content, connector_metadata, authentication_status: Some(authentication_status), ds_trans_id, eci, challenge_code, challenge_cancel, challenge_code_reason, message_extension, challenge_request_key, ..Default::default() }, AuthenticationUpdate::PostAuthenticationUpdate { trans_status, eci, authentication_status, challenge_cancel, challenge_code_reason, } => Self { trans_status: Some(trans_status), eci, authentication_status: Some(authentication_status), challenge_cancel, challenge_code_reason, ..Default::default() }, AuthenticationUpdate::PreAuthenticationVersionCallUpdate { maximum_supported_3ds_version, message_version, } => Self { maximum_supported_version: Some(maximum_supported_3ds_version), message_version: Some(message_version), ..Default::default() }, AuthenticationUpdate::PreAuthenticationThreeDsMethodCall { threeds_server_transaction_id, three_ds_method_data, three_ds_method_url, acquirer_bin, acquirer_merchant_id, connector_metadata, } => Self { threeds_server_transaction_id: Some(threeds_server_transaction_id), three_ds_method_data, three_ds_method_url, acquirer_bin, acquirer_merchant_id, connector_metadata, ..Default::default() }, AuthenticationUpdate::AuthenticationStatusUpdate { trans_status, authentication_status, } => Self { trans_status: Some(trans_status), authentication_status: Some(authentication_status), ..Default::default() }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/authentication.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_3981519913420595304
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/merchant_key_store.rs // Contains: 3 structs, 0 enums use common_utils::{custom_serde, encryption::Encryption}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::schema::merchant_key_store; #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_key_store, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantKeyStore { pub merchant_id: common_utils::id_type::MerchantId, pub key: Encryption, #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, } #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Insertable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_key_store)] pub struct MerchantKeyStoreNew { pub merchant_id: common_utils::id_type::MerchantId, pub key: Encryption, pub created_at: PrimitiveDateTime, } #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, AsChangeset, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_key_store)] pub struct MerchantKeyStoreUpdateInternal { pub merchant_id: common_utils::id_type::MerchantId, pub key: Encryption, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/merchant_key_store.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-9162134168154031604
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/user_key_store.rs // Contains: 2 structs, 0 enums use common_utils::encryption::Encryption; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::schema::user_key_store; #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, )] #[diesel(table_name = user_key_store, primary_key(user_id), check_for_backend(diesel::pg::Pg))] pub struct UserKeyStore { pub user_id: String, pub key: Encryption, pub created_at: PrimitiveDateTime, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Insertable)] #[diesel(table_name = user_key_store)] pub struct UserKeyStoreNew { pub user_id: String, pub key: Encryption, pub created_at: PrimitiveDateTime, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/user_key_store.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-4944030027429677313
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/ephemeral_key.rs // Contains: 2 structs, 0 enums #[cfg(feature = "v2")] use masking::{PeekInterface, Secret}; #[cfg(feature = "v2")] pub struct ClientSecretTypeNew { pub id: common_utils::id_type::ClientSecretId, pub merchant_id: common_utils::id_type::MerchantId, pub secret: Secret<String>, pub resource_id: common_utils::types::authentication::ResourceId, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct ClientSecretType { pub id: common_utils::id_type::ClientSecretId, pub merchant_id: common_utils::id_type::MerchantId, pub resource_id: common_utils::types::authentication::ResourceId, pub created_at: time::PrimitiveDateTime, pub expires: time::PrimitiveDateTime, pub secret: Secret<String>, } #[cfg(feature = "v2")] impl ClientSecretType { pub fn generate_secret_key(&self) -> String { format!("cs_{}", self.secret.peek()) } } pub struct EphemeralKeyNew { pub id: String, pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: common_utils::id_type::CustomerId, pub secret: String, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct EphemeralKey { pub id: String, pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: common_utils::id_type::CustomerId, pub created_at: i64, pub expires: i64, pub secret: String, } impl common_utils::events::ApiEventMetric for EphemeralKey { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/ephemeral_key.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-3060782171977590702
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/reverse_lookup.rs // Contains: 2 structs, 0 enums use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::reverse_lookup; /// This reverse lookup table basically looks up id's and get result_id that you want. This is /// useful for KV where you can't lookup without key #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, Eq, PartialEq, )] #[diesel(table_name = reverse_lookup, primary_key(lookup_id), check_for_backend(diesel::pg::Pg))] pub struct ReverseLookup { /// Primary key. The key id. pub lookup_id: String, /// the `field` in KV database. Which is used to differentiate between two same keys pub sk_id: String, /// the value id. i.e the id you want to access KV table. pub pk_id: String, /// the source of insertion for reference pub source: String, pub updated_by: String, } #[derive( Clone, Debug, Insertable, router_derive::DebugAsDisplay, Eq, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = reverse_lookup)] pub struct ReverseLookupNew { pub lookup_id: String, pub pk_id: String, pub sk_id: String, pub source: String, pub updated_by: String, } impl From<ReverseLookupNew> for ReverseLookup { fn from(new: ReverseLookupNew) -> Self { Self { lookup_id: new.lookup_id, sk_id: new.sk_id, pk_id: new.pk_id, source: new.source, updated_by: new.updated_by, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/reverse_lookup.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-9124801364727031149
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/relay.rs // Contains: 3 structs, 0 enums use common_utils::pii; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::relay}; #[derive( Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = relay)] pub struct Relay { pub id: common_utils::id_type::RelayId, pub connector_resource_id: String, pub connector_id: common_utils::id_type::MerchantConnectorAccountId, pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub relay_type: storage_enums::RelayType, pub request_data: Option<pii::SecretSerdeValue>, pub status: storage_enums::RelayStatus, pub connector_reference_id: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub response_data: Option<pii::SecretSerdeValue>, } #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, router_derive::Setter, )] #[diesel(table_name = relay)] pub struct RelayNew { pub id: common_utils::id_type::RelayId, pub connector_resource_id: String, pub connector_id: common_utils::id_type::MerchantConnectorAccountId, pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub relay_type: storage_enums::RelayType, pub request_data: Option<pii::SecretSerdeValue>, pub status: storage_enums::RelayStatus, pub connector_reference_id: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub response_data: Option<pii::SecretSerdeValue>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = relay)] pub struct RelayUpdateInternal { pub connector_reference_id: Option<String>, pub status: Option<storage_enums::RelayStatus>, pub error_code: Option<String>, pub error_message: Option<String>, pub modified_at: PrimitiveDateTime, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/relay.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_2747615680753680263
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/mandate.rs // Contains: 4 structs, 1 enums use common_enums::MerchantStorageScheme; use common_utils::pii; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::mandate}; #[derive( Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = mandate, primary_key(mandate_id), check_for_backend(diesel::pg::Pg))] pub struct Mandate { pub mandate_id: String, pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_method_id: String, pub mandate_status: storage_enums::MandateStatus, pub mandate_type: storage_enums::MandateType, pub customer_accepted_at: Option<PrimitiveDateTime>, pub customer_ip_address: Option<Secret<String, pii::IpAddress>>, pub customer_user_agent: Option<String>, pub network_transaction_id: Option<String>, pub previous_attempt_id: Option<String>, pub created_at: PrimitiveDateTime, pub mandate_amount: Option<i64>, pub mandate_currency: Option<storage_enums::Currency>, pub amount_captured: Option<i64>, pub connector: String, pub connector_mandate_id: Option<String>, pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_ids: Option<pii::SecretSerdeValue>, pub original_payment_id: Option<common_utils::id_type::PaymentId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub updated_by: Option<String>, // This is the extended version of customer user agent that can store string upto 2048 characters unlike customer user agent that can store 255 characters at max pub customer_user_agent_extended: Option<String>, } #[derive( router_derive::Setter, Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = mandate)] pub struct MandateNew { pub mandate_id: String, pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_method_id: String, pub mandate_status: storage_enums::MandateStatus, pub mandate_type: storage_enums::MandateType, pub customer_accepted_at: Option<PrimitiveDateTime>, pub customer_ip_address: Option<Secret<String, pii::IpAddress>>, pub customer_user_agent: Option<String>, pub network_transaction_id: Option<String>, pub previous_attempt_id: Option<String>, pub created_at: Option<PrimitiveDateTime>, pub mandate_amount: Option<i64>, pub mandate_currency: Option<storage_enums::Currency>, pub amount_captured: Option<i64>, pub connector: String, pub connector_mandate_id: Option<String>, pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_ids: Option<pii::SecretSerdeValue>, pub original_payment_id: Option<common_utils::id_type::PaymentId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub updated_by: Option<String>, pub customer_user_agent_extended: Option<String>, } impl Mandate { /// Returns customer_user_agent_extended with customer_user_agent as fallback pub fn get_user_agent_extended(&self) -> Option<String> { self.customer_user_agent_extended .clone() .or_else(|| self.customer_user_agent.clone()) } } impl MandateNew { pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } /// Returns customer_user_agent_extended with customer_user_agent as fallback pub fn get_customer_user_agent_extended(&self) -> Option<String> { self.customer_user_agent_extended .clone() .or_else(|| self.customer_user_agent.clone()) } } #[derive(Debug)] pub enum MandateUpdate { StatusUpdate { mandate_status: storage_enums::MandateStatus, }, CaptureAmountUpdate { amount_captured: Option<i64>, }, ConnectorReferenceUpdate { connector_mandate_ids: Option<pii::SecretSerdeValue>, }, ConnectorMandateIdUpdate { connector_mandate_id: Option<String>, connector_mandate_ids: Option<pii::SecretSerdeValue>, payment_method_id: String, original_payment_id: Option<common_utils::id_type::PaymentId>, }, } impl MandateUpdate { pub fn convert_to_mandate_update( self, storage_scheme: MerchantStorageScheme, ) -> MandateUpdateInternal { let mut updated_object = MandateUpdateInternal::from(self); updated_object.updated_by = Some(storage_scheme.to_string()); updated_object } } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: i64, pub currency: storage_enums::Currency, } #[derive( Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = mandate)] pub struct MandateUpdateInternal { mandate_status: Option<storage_enums::MandateStatus>, amount_captured: Option<i64>, connector_mandate_ids: Option<pii::SecretSerdeValue>, connector_mandate_id: Option<String>, payment_method_id: Option<String>, original_payment_id: Option<common_utils::id_type::PaymentId>, updated_by: Option<String>, } impl From<MandateUpdate> for MandateUpdateInternal { fn from(mandate_update: MandateUpdate) -> Self { match mandate_update { MandateUpdate::StatusUpdate { mandate_status } => Self { mandate_status: Some(mandate_status), connector_mandate_ids: None, amount_captured: None, connector_mandate_id: None, payment_method_id: None, original_payment_id: None, updated_by: None, }, MandateUpdate::CaptureAmountUpdate { amount_captured } => Self { mandate_status: None, amount_captured, connector_mandate_ids: None, connector_mandate_id: None, payment_method_id: None, original_payment_id: None, updated_by: None, }, MandateUpdate::ConnectorReferenceUpdate { connector_mandate_ids, } => Self { connector_mandate_ids, ..Default::default() }, MandateUpdate::ConnectorMandateIdUpdate { connector_mandate_id, connector_mandate_ids, payment_method_id, original_payment_id, } => Self { connector_mandate_id, connector_mandate_ids, payment_method_id: Some(payment_method_id), original_payment_id, ..Default::default() }, } } } impl MandateUpdateInternal { pub fn apply_changeset(self, source: Mandate) -> Mandate { let Self { mandate_status, amount_captured, connector_mandate_ids, connector_mandate_id, payment_method_id, original_payment_id, updated_by, } = self; Mandate { mandate_status: mandate_status.unwrap_or(source.mandate_status), amount_captured: amount_captured.map_or(source.amount_captured, Some), connector_mandate_ids: connector_mandate_ids.map_or(source.connector_mandate_ids, Some), connector_mandate_id: connector_mandate_id.map_or(source.connector_mandate_id, Some), payment_method_id: payment_method_id.unwrap_or(source.payment_method_id), original_payment_id: original_payment_id.map_or(source.original_payment_id, Some), updated_by: updated_by.map_or(source.updated_by, Some), ..source } } } impl From<&MandateNew> for Mandate { fn from(mandate_new: &MandateNew) -> Self { Self { mandate_id: mandate_new.mandate_id.clone(), customer_id: mandate_new.customer_id.clone(), merchant_id: mandate_new.merchant_id.clone(), payment_method_id: mandate_new.payment_method_id.clone(), mandate_status: mandate_new.mandate_status, mandate_type: mandate_new.mandate_type, customer_accepted_at: mandate_new.customer_accepted_at, customer_ip_address: mandate_new.customer_ip_address.clone(), customer_user_agent: None, network_transaction_id: mandate_new.network_transaction_id.clone(), previous_attempt_id: mandate_new.previous_attempt_id.clone(), created_at: mandate_new .created_at .unwrap_or_else(common_utils::date_time::now), mandate_amount: mandate_new.mandate_amount, mandate_currency: mandate_new.mandate_currency, amount_captured: mandate_new.amount_captured, connector: mandate_new.connector.clone(), connector_mandate_id: mandate_new.connector_mandate_id.clone(), start_date: mandate_new.start_date, end_date: mandate_new.end_date, metadata: mandate_new.metadata.clone(), connector_mandate_ids: mandate_new.connector_mandate_ids.clone(), original_payment_id: mandate_new.original_payment_id.clone(), merchant_connector_id: mandate_new.merchant_connector_id.clone(), updated_by: mandate_new.updated_by.clone(), // Using customer_user_agent as a fallback customer_user_agent_extended: mandate_new.get_customer_user_agent_extended(), } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/mandate.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-1895365943880965730
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/payment_intent.rs // Contains: 14 structs, 2 enums use common_enums::{PaymentMethodType, RequestIncrementalAuthorization}; use common_types::primitive_wrappers::{ EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool, }; use common_utils::{encryption::Encryption, pii, types::MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::ExposeInterface; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::schema::payment_intent; #[cfg(feature = "v2")] use crate::schema_v2::payment_intent; #[cfg(feature = "v2")] use crate::types::{FeatureMetadata, OrderDetailsWithAmount}; #[cfg(feature = "v2")] use crate::RequiredFromNullable; use crate::{business_profile::PaymentLinkBackgroundImageConfig, enums as storage_enums}; #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, #[diesel(deserialize_as = RequiredFromNullable<storage_enums::Currency>)] pub currency: storage_enums::Currency, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::GlobalCustomerId>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub attempt_count: i16, #[diesel(deserialize_as = RequiredFromNullable<common_utils::id_type::ProfileId>)] pub profile_id: common_utils::id_type::ProfileId, pub payment_link_id: Option<String>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, #[diesel(deserialize_as = RequiredFromNullable<PrimitiveDateTime>)] pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, pub created_by: Option<String>, pub is_iframe_redirection_enabled: Option<bool>, pub is_payment_id_from_merchant: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, pub mit_category: Option<storage_enums::MitCategory>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<serde_json::Value>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub enable_payment_link: Option<bool>, pub apply_mit_exemption: Option<bool>, pub customer_present: Option<bool>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub id: common_utils::id_type::GlobalPaymentId, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, pub active_attempts_group_id: Option<String>, pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<serde_json::Value>, pub connector_metadata: Option<serde_json::Value>, pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, pub profile_id: Option<common_utils::id_type::ProfileId>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, pub created_by: Option<String>, pub is_iframe_redirection_enabled: Option<bool>, pub extended_return_url: Option<String>, pub is_payment_id_from_merchant: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, pub mit_category: Option<storage_enums::MitCategory>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PaymentLinkConfigRequestForPayments { /// custom theme for the payment link pub theme: Option<String>, /// merchant display logo pub logo: Option<String>, /// Custom merchant name for payment link pub seller_name: Option<String>, /// Custom layout for sdk pub sdk_layout: Option<String>, /// Display only the sdk for payment link pub display_sdk_only: Option<bool>, /// Enable saved payment method option for payment link pub enabled_saved_payment_method: Option<bool>, /// Hide card nickname field option for payment link pub hide_card_nickname_field: Option<bool>, /// Show card form by default for payment link 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 pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>, /// Text for payment link's handle confirm button pub payment_button_text: Option<String>, /// Skip the status screen after payment completion pub skip_status_screen: Option<bool>, /// 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>, /// 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<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<std::collections::HashMap<String, std::collections::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 pub payment_form_label_type: Option<common_enums::PaymentLinkSdkLabelType>, /// Boolean for controlling whether or not to show the explicit consent for storing cards pub show_card_terms: Option<common_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>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct PaymentLinkTransactionDetails { /// Key for the transaction details pub key: String, /// Value for the transaction details pub value: String, /// UI configuration for the transaction details pub ui_configuration: Option<TransactionDetailsUiConfiguration>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkTransactionDetails); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct TransactionDetailsUiConfiguration { /// Position of the key-value pair in the UI pub position: Option<i8>, /// Whether the key should be bold pub is_key_bold: Option<bool>, /// Whether the value should be bold pub is_value_bold: Option<bool>, } common_utils::impl_to_sql_from_sql_json!(TransactionDetailsUiConfiguration); #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct TaxDetails { /// This is the tax related information that is calculated irrespective of any payment method. /// This is calculated when the order is created with shipping details pub default: Option<DefaultTax>, /// This is the tax related information that is calculated based on the payment method /// This is calculated when calling the /calculate_tax API pub payment_method_type: Option<PaymentMethodTypeTax>, } impl TaxDetails { /// Get the tax amount /// If default tax is present, return the default tax amount /// If default tax is not present, return the tax amount based on the payment method if it matches the provided payment method type pub fn get_tax_amount(&self, payment_method: Option<PaymentMethodType>) -> Option<MinorUnit> { self.payment_method_type .as_ref() .zip(payment_method) .filter(|(payment_method_type_tax, payment_method)| { payment_method_type_tax.pmt == *payment_method }) .map(|(payment_method_type_tax, _)| payment_method_type_tax.order_tax_amount) .or_else(|| self.get_default_tax_amount()) } /// Get the default tax amount pub fn get_default_tax_amount(&self) -> Option<MinorUnit> { self.default .as_ref() .map(|default_tax_details| default_tax_details.order_tax_amount) } } common_utils::impl_to_sql_from_sql_json!(TaxDetails); #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PaymentMethodTypeTax { pub order_tax_amount: MinorUnit, pub pmt: PaymentMethodType, } #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DefaultTax { pub order_tax_amount: MinorUnit, } #[cfg(feature = "v2")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: storage_enums::Currency, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::GlobalCustomerId>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub attempt_count: i16, pub profile_id: common_utils::id_type::ProfileId, pub payment_link_id: Option<String>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<serde_json::Value>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub enable_payment_link: Option<bool>, pub apply_mit_exemption: Option<bool>, pub id: common_utils::id_type::GlobalPaymentId, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub created_by: Option<String>, pub is_iframe_redirection_enabled: Option<bool>, pub is_payment_id_from_merchant: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub mit_category: Option<storage_enums::MitCategory>, } #[cfg(feature = "v1")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<serde_json::Value>, pub connector_metadata: Option<serde_json::Value>, pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_decision: Option<String>, pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, pub created_by: Option<String>, pub is_iframe_redirection_enabled: Option<bool>, pub extended_return_url: Option<String>, pub is_payment_id_from_merchant: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, pub mit_category: Option<storage_enums::MitCategory>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { /// Update the payment intent details on payment intent confirmation, before calling the connector ConfirmIntent { status: storage_enums::IntentStatus, active_attempt_id: common_utils::id_type::GlobalAttemptId, updated_by: String, }, /// Update the payment intent details on payment intent confirmation, after calling the connector ConfirmIntentPostUpdate { status: storage_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, }, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { ResponseUpdate { status: storage_enums::IntentStatus, amount_captured: Option<MinorUnit>, fingerprint_id: Option<String>, updated_by: String, incremental_authorization_allowed: Option<bool>, feature_metadata: Option<masking::Secret<serde_json::Value>>, }, MetadataUpdate { metadata: serde_json::Value, updated_by: String, }, Update(Box<PaymentIntentUpdateFields>), PaymentCreateUpdate { return_url: Option<String>, status: Option<storage_enums::IntentStatus>, customer_id: Option<common_utils::id_type::CustomerId>, shipping_address_id: Option<String>, billing_address_id: Option<String>, customer_details: Option<Encryption>, updated_by: String, }, MerchantStatusUpdate { status: storage_enums::IntentStatus, shipping_address_id: Option<String>, billing_address_id: Option<String>, updated_by: String, }, PGStatusUpdate { status: storage_enums::IntentStatus, updated_by: String, incremental_authorization_allowed: Option<bool>, feature_metadata: Option<masking::Secret<serde_json::Value>>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, attempt_count: i16, updated_by: String, }, StatusAndAttemptUpdate { status: storage_enums::IntentStatus, active_attempt_id: String, attempt_count: i16, updated_by: String, }, ApproveUpdate { status: storage_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, RejectUpdate { status: storage_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, SurchargeApplicableUpdate { surcharge_applicable: Option<bool>, updated_by: String, }, IncrementalAuthorizationAmountUpdate { amount: MinorUnit, }, AuthorizationCountUpdate { authorization_count: i32, }, CompleteAuthorizeUpdate { shipping_address_id: Option<String>, }, ManualUpdate { status: Option<storage_enums::IntentStatus>, updated_by: String, }, SessionResponseUpdate { tax_details: TaxDetails, shipping_address_id: Option<String>, updated_by: String, shipping_details: Option<Encryption>, }, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub status: storage_enums::IntentStatus, pub customer_id: Option<common_utils::id_type::CustomerId>, pub shipping_address: Option<Encryption>, pub billing_address: Option<Encryption>, pub return_url: Option<String>, pub description: Option<String>, pub statement_descriptor: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub is_payment_processor_token_flow: Option<bool>, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub payment_channel: Option<Option<common_enums::PaymentChannel>>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub status: storage_enums::IntentStatus, pub customer_id: Option<common_utils::id_type::CustomerId>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub return_url: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<serde_json::Value>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<TaxDetails>, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub feature_metadata: Option<masking::Secret<serde_json::Value>>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, } // TODO: uncomment fields as necessary #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { pub status: Option<storage_enums::IntentStatus>, pub prerouting_algorithm: Option<serde_json::Value>, pub amount_captured: Option<MinorUnit>, pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<Option<common_utils::id_type::GlobalAttemptId>>, pub amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub shipping_cost: Option<MinorUnit>, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub surcharge_applicable: Option<bool>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub customer_present: Option<bool>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub apply_mit_exemption: Option<bool>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub session_expiry: Option<PrimitiveDateTime>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub request_external_three_ds_authentication: Option<bool>, pub updated_by: String, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, } #[cfg(feature = "v2")] impl PaymentIntentUpdateInternal { pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { let Self { status, prerouting_algorithm, amount_captured, modified_at: _, // This will be ignored from self active_attempt_id, amount, currency, shipping_cost, tax_details, skip_external_tax_calculation, surcharge_applicable, surcharge_amount, tax_on_surcharge, routing_algorithm_id, capture_method, authentication_type, billing_address, shipping_address, customer_present, description, return_url, setup_future_usage, apply_mit_exemption, statement_descriptor, order_details, allowed_payment_method_types, metadata, connector_metadata, feature_metadata, payment_link_config, request_incremental_authorization, session_expiry, frm_metadata, request_external_three_ds_authentication, updated_by, force_3ds_challenge, is_iframe_redirection_enabled, enable_partial_authorization, } = self; PaymentIntent { status: status.unwrap_or(source.status), prerouting_algorithm: prerouting_algorithm.or(source.prerouting_algorithm), amount_captured: amount_captured.or(source.amount_captured), modified_at: common_utils::date_time::now(), active_attempt_id: match active_attempt_id { Some(v_option) => v_option, None => source.active_attempt_id, }, amount: amount.unwrap_or(source.amount), currency: currency.unwrap_or(source.currency), shipping_cost: shipping_cost.or(source.shipping_cost), tax_details: tax_details.or(source.tax_details), skip_external_tax_calculation: skip_external_tax_calculation .or(source.skip_external_tax_calculation), surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable), surcharge_amount: surcharge_amount.or(source.surcharge_amount), tax_on_surcharge: tax_on_surcharge.or(source.tax_on_surcharge), routing_algorithm_id: routing_algorithm_id.or(source.routing_algorithm_id), capture_method: capture_method.or(source.capture_method), authentication_type: authentication_type.or(source.authentication_type), billing_address: billing_address.or(source.billing_address), shipping_address: shipping_address.or(source.shipping_address), customer_present: customer_present.or(source.customer_present), description: description.or(source.description), return_url: return_url.or(source.return_url), setup_future_usage: setup_future_usage.or(source.setup_future_usage), apply_mit_exemption: apply_mit_exemption.or(source.apply_mit_exemption), statement_descriptor: statement_descriptor.or(source.statement_descriptor), order_details: order_details.or(source.order_details), allowed_payment_method_types: allowed_payment_method_types .or(source.allowed_payment_method_types), metadata: metadata.or(source.metadata), connector_metadata: connector_metadata.or(source.connector_metadata), feature_metadata: feature_metadata.or(source.feature_metadata), payment_link_config: payment_link_config.or(source.payment_link_config), request_incremental_authorization: request_incremental_authorization .or(source.request_incremental_authorization), session_expiry: session_expiry.unwrap_or(source.session_expiry), frm_metadata: frm_metadata.or(source.frm_metadata), request_external_three_ds_authentication: request_external_three_ds_authentication .or(source.request_external_three_ds_authentication), updated_by, force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge), is_iframe_redirection_enabled: is_iframe_redirection_enabled .or(source.is_iframe_redirection_enabled), // Fields from source merchant_id: source.merchant_id, customer_id: source.customer_id, created_at: source.created_at, last_synced: source.last_synced, attempt_count: source.attempt_count, profile_id: source.profile_id, payment_link_id: source.payment_link_id, authorization_count: source.authorization_count, customer_details: source.customer_details, organization_id: source.organization_id, request_extended_authorization: source.request_extended_authorization, psd2_sca_exemption_type: source.psd2_sca_exemption_type, split_payments: source.split_payments, platform_merchant_id: source.platform_merchant_id, force_3ds_challenge_trigger: source.force_3ds_challenge_trigger, processor_merchant_id: source.processor_merchant_id, created_by: source.created_by, merchant_reference_id: source.merchant_reference_id, frm_merchant_decision: source.frm_merchant_decision, enable_payment_link: source.enable_payment_link, id: source.id, is_payment_id_from_merchant: source.is_payment_id_from_merchant, payment_channel: source.payment_channel, tax_status: source.tax_status, discount_amount: source.discount_amount, shipping_amount_tax: source.shipping_amount_tax, duty_amount: source.duty_amount, order_date: source.order_date, enable_partial_authorization: source.enable_partial_authorization, split_txns_enabled: source.split_txns_enabled, enable_overcapture: None, active_attempt_id_type: source.active_attempt_id_type, active_attempts_group_id: source.active_attempts_group_id, mit_category: None, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { pub amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub status: Option<storage_enums::IntentStatus>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub return_url: Option<String>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub metadata: Option<serde_json::Value>, pub billing_address_id: Option<String>, pub shipping_address_id: Option<String>, pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub attempt_count: Option<i16>, pub merchant_decision: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<TaxDetails>, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub extended_return_url: Option<String>, pub payment_channel: Option<common_enums::PaymentChannel>, pub feature_metadata: Option<masking::Secret<serde_json::Value>>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, } #[cfg(feature = "v1")] impl PaymentIntentUpdate { pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { let PaymentIntentUpdateInternal { amount, currency, status, amount_captured, customer_id, return_url, setup_future_usage, off_session, metadata, billing_address_id, shipping_address_id, modified_at: _, active_attempt_id, business_country, business_label, description, statement_descriptor_name, statement_descriptor_suffix, order_details, attempt_count, merchant_decision, payment_confirm_source, updated_by, surcharge_applicable, incremental_authorization_allowed, authorization_count, session_expiry, fingerprint_id, request_external_three_ds_authentication, frm_metadata, customer_details, billing_details, merchant_order_reference_id, shipping_details, is_payment_processor_token_flow, tax_details, force_3ds_challenge, is_iframe_redirection_enabled, extended_return_url, payment_channel, feature_metadata, tax_status, discount_amount, order_date, shipping_amount_tax, duty_amount, enable_partial_authorization, enable_overcapture, } = self.into(); PaymentIntent { amount: amount.unwrap_or(source.amount), currency: currency.or(source.currency), status: status.unwrap_or(source.status), amount_captured: amount_captured.or(source.amount_captured), customer_id: customer_id.or(source.customer_id), return_url: return_url.or(source.return_url), setup_future_usage: setup_future_usage.or(source.setup_future_usage), off_session: off_session.or(source.off_session), metadata: metadata.or(source.metadata), billing_address_id: billing_address_id.or(source.billing_address_id), shipping_address_id: shipping_address_id.or(source.shipping_address_id), modified_at: common_utils::date_time::now(), active_attempt_id: active_attempt_id.unwrap_or(source.active_attempt_id), business_country: business_country.or(source.business_country), business_label: business_label.or(source.business_label), description: description.or(source.description), statement_descriptor_name: statement_descriptor_name .or(source.statement_descriptor_name), statement_descriptor_suffix: statement_descriptor_suffix .or(source.statement_descriptor_suffix), order_details: order_details.or(source.order_details), attempt_count: attempt_count.unwrap_or(source.attempt_count), merchant_decision: merchant_decision.or(source.merchant_decision), payment_confirm_source: payment_confirm_source.or(source.payment_confirm_source), updated_by, surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable), incremental_authorization_allowed: incremental_authorization_allowed .or(source.incremental_authorization_allowed), authorization_count: authorization_count.or(source.authorization_count), fingerprint_id: fingerprint_id.or(source.fingerprint_id), session_expiry: session_expiry.or(source.session_expiry), request_external_three_ds_authentication: request_external_three_ds_authentication .or(source.request_external_three_ds_authentication), frm_metadata: frm_metadata.or(source.frm_metadata), customer_details: customer_details.or(source.customer_details), billing_details: billing_details.or(source.billing_details), merchant_order_reference_id: merchant_order_reference_id .or(source.merchant_order_reference_id), shipping_details: shipping_details.or(source.shipping_details), is_payment_processor_token_flow: is_payment_processor_token_flow .or(source.is_payment_processor_token_flow), tax_details: tax_details.or(source.tax_details), force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge), is_iframe_redirection_enabled: is_iframe_redirection_enabled .or(source.is_iframe_redirection_enabled), extended_return_url: extended_return_url.or(source.extended_return_url), payment_channel: payment_channel.or(source.payment_channel), feature_metadata: feature_metadata .map(|value| value.expose()) .or(source.feature_metadata), tax_status: tax_status.or(source.tax_status), discount_amount: discount_amount.or(source.discount_amount), order_date: order_date.or(source.order_date), shipping_amount_tax: shipping_amount_tax.or(source.shipping_amount_tax), duty_amount: duty_amount.or(source.duty_amount), enable_partial_authorization: enable_partial_authorization .or(source.enable_partial_authorization), enable_overcapture: enable_overcapture.or(source.enable_overcapture), ..source } } } #[cfg(feature = "v1")] impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fn from(payment_intent_update: PaymentIntentUpdate) -> Self { match payment_intent_update { PaymentIntentUpdate::MetadataUpdate { metadata, updated_by, } => Self { metadata: Some(metadata), modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::Update(value) => Self { amount: Some(value.amount), currency: Some(value.currency), setup_future_usage: value.setup_future_usage, status: Some(value.status), customer_id: value.customer_id, shipping_address_id: value.shipping_address_id, billing_address_id: value.billing_address_id, return_url: None, // deprecated business_country: value.business_country, business_label: value.business_label, description: value.description, statement_descriptor_name: value.statement_descriptor_name, statement_descriptor_suffix: value.statement_descriptor_suffix, order_details: value.order_details, metadata: value.metadata, payment_confirm_source: value.payment_confirm_source, updated_by: value.updated_by, session_expiry: value.session_expiry, fingerprint_id: value.fingerprint_id, request_external_three_ds_authentication: value .request_external_three_ds_authentication, frm_metadata: value.frm_metadata, customer_details: value.customer_details, billing_details: value.billing_details, merchant_order_reference_id: value.merchant_order_reference_id, shipping_details: value.shipping_details, amount_captured: None, off_session: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, attempt_count: None, merchant_decision: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, is_payment_processor_token_flow: value.is_payment_processor_token_flow, tax_details: None, force_3ds_challenge: value.force_3ds_challenge, is_iframe_redirection_enabled: value.is_iframe_redirection_enabled, extended_return_url: value.return_url, payment_channel: value.payment_channel, feature_metadata: value.feature_metadata, tax_status: value.tax_status, discount_amount: value.discount_amount, order_date: value.order_date, shipping_amount_tax: value.shipping_amount_tax, duty_amount: value.duty_amount, enable_partial_authorization: value.enable_partial_authorization, enable_overcapture: value.enable_overcapture, }, PaymentIntentUpdate::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details, updated_by, } => Self { return_url: None, // deprecated status, customer_id, shipping_address_id, billing_address_id, customer_details, modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, amount_captured: None, setup_future_usage: None, off_session: None, metadata: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: return_url, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::PGStatusUpdate { status, updated_by, incremental_authorization_allowed, feature_metadata, } => Self { status: Some(status), modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::MerchantStatusUpdate { status, shipping_address_id, billing_address_id, updated_by, } => Self { status: Some(status), shipping_address_id, billing_address_id, modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::ResponseUpdate { // amount, // currency, status, amount_captured, fingerprint_id, // customer_id, updated_by, incremental_authorization_allowed, feature_metadata, } => Self { // amount, // currency: Some(currency), status: Some(status), amount_captured, fingerprint_id, // customer_id, return_url: None, modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, amount: None, currency: None, customer_id: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, authorization_count: None, session_expiry: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, attempt_count, updated_by, } => Self { active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::StatusAndAttemptUpdate { status, active_attempt_id, attempt_count, updated_by, } => Self { status: Some(status), active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::ApproveUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::RejectUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable, updated_by, } => Self { surcharge_applicable, updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self { amount: Some(amount), currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count, } => Self { authorization_count: Some(authorization_count), amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::CompleteAuthorizeUpdate { shipping_address_id, } => Self { shipping_address_id, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self { status, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::SessionResponseUpdate { tax_details, shipping_address_id, updated_by, shipping_details, } => Self { shipping_address_id, amount: None, tax_details: Some(tax_details), currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details, is_payment_processor_token_flow: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, } } } mod tests { #[test] fn test_backwards_compatibility() { let serialized_payment_intent = r#"{ "payment_id": "payment_12345", "merchant_id": "merchant_67890", "status": "succeeded", "amount": 10000, "currency": "USD", "amount_captured": null, "customer_id": "cust_123456", "description": "Test Payment", "return_url": "https://example.com/return", "metadata": null, "connector_id": "connector_001", "shipping_address_id": null, "billing_address_id": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "created_at": "2024-02-01T12:00:00Z", "modified_at": "2024-02-01T12:00:00Z", "last_synced": null, "setup_future_usage": null, "off_session": null, "client_secret": "sec_abcdef1234567890", "active_attempt_id": "attempt_123", "business_country": "US", "business_label": null, "order_details": null, "allowed_payment_method_types": "credit", "connector_metadata": null, "feature_metadata": null, "attempt_count": 1, "profile_id": null, "merchant_decision": null, "payment_link_id": null, "payment_confirm_source": null, "updated_by": "admin", "surcharge_applicable": null, "request_incremental_authorization": null, "incremental_authorization_allowed": null, "authorization_count": null, "session_expiry": null, "fingerprint_id": null, "frm_metadata": null }"#; let deserialized_payment_intent = serde_json::from_str::<super::PaymentIntent>(serialized_payment_intent); assert!(deserialized_payment_intent.is_ok()); } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/payment_intent.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 14, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_727145689123776161
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/capture.rs // Contains: 3 structs, 1 enums use common_utils::types::{ConnectorTransactionId, MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::captures}; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = captures, primary_key(capture_id), check_for_backend(diesel::pg::Pg))] pub struct Capture { pub capture_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::CaptureStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub connector: String, pub error_message: Option<String>, pub error_code: Option<String>, pub error_reason: Option<String>, pub tax_amount: Option<MinorUnit>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub authorized_attempt_id: String, pub connector_capture_id: Option<ConnectorTransactionId>, pub capture_sequence: i16, // reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// INFO: This field is deprecated and replaced by processor_capture_data pub connector_capture_data: Option<String>, pub processor_capture_data: Option<String>, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = captures)] pub struct CaptureNew { pub capture_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::CaptureStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub connector: String, pub error_message: Option<String>, pub error_code: Option<String>, pub error_reason: Option<String>, pub tax_amount: Option<MinorUnit>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub authorized_attempt_id: String, pub connector_capture_id: Option<ConnectorTransactionId>, pub capture_sequence: i16, pub connector_response_reference_id: Option<String>, /// INFO: This field is deprecated and replaced by processor_capture_data pub connector_capture_data: Option<String>, pub processor_capture_data: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum CaptureUpdate { ResponseUpdate { status: storage_enums::CaptureStatus, connector_capture_id: Option<ConnectorTransactionId>, connector_response_reference_id: Option<String>, processor_capture_data: Option<String>, }, ErrorUpdate { status: storage_enums::CaptureStatus, error_code: Option<String>, error_message: Option<String>, error_reason: Option<String>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = captures)] pub struct CaptureUpdateInternal { pub status: Option<storage_enums::CaptureStatus>, pub error_message: Option<String>, pub error_code: Option<String>, pub error_reason: Option<String>, pub modified_at: Option<PrimitiveDateTime>, pub connector_capture_id: Option<ConnectorTransactionId>, pub connector_response_reference_id: Option<String>, pub processor_capture_data: Option<String>, } impl CaptureUpdate { pub fn apply_changeset(self, source: Capture) -> Capture { let CaptureUpdateInternal { status, error_message, error_code, error_reason, modified_at: _, connector_capture_id, connector_response_reference_id, processor_capture_data, } = self.into(); Capture { status: status.unwrap_or(source.status), error_message: error_message.or(source.error_message), error_code: error_code.or(source.error_code), error_reason: error_reason.or(source.error_reason), modified_at: common_utils::date_time::now(), connector_capture_id: connector_capture_id.or(source.connector_capture_id), connector_response_reference_id: connector_response_reference_id .or(source.connector_response_reference_id), processor_capture_data: processor_capture_data.or(source.processor_capture_data), ..source } } } impl From<CaptureUpdate> for CaptureUpdateInternal { fn from(payment_attempt_child_update: CaptureUpdate) -> Self { let now = Some(common_utils::date_time::now()); match payment_attempt_child_update { CaptureUpdate::ResponseUpdate { status, connector_capture_id: connector_transaction_id, connector_response_reference_id, processor_capture_data, } => Self { status: Some(status), connector_capture_id: connector_transaction_id, modified_at: now, connector_response_reference_id, processor_capture_data, ..Self::default() }, CaptureUpdate::ErrorUpdate { status, error_code, error_message, error_reason, } => Self { status: Some(status), error_code, error_message, error_reason, modified_at: now, ..Self::default() }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/capture.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_4326490515528395244
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/authorization.rs // Contains: 3 structs, 1 enums use common_utils::types::MinorUnit; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::incremental_authorization}; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, Hash, )] #[diesel(table_name = incremental_authorization, primary_key(authorization_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct Authorization { pub authorization_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: common_utils::id_type::PaymentId, pub amount: MinorUnit, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub status: storage_enums::AuthorizationStatus, pub error_code: Option<String>, pub error_message: Option<String>, pub connector_authorization_id: Option<String>, pub previously_authorized_amount: MinorUnit, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = incremental_authorization)] pub struct AuthorizationNew { pub authorization_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: common_utils::id_type::PaymentId, pub amount: MinorUnit, pub status: storage_enums::AuthorizationStatus, pub error_code: Option<String>, pub error_message: Option<String>, pub connector_authorization_id: Option<String>, pub previously_authorized_amount: MinorUnit, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum AuthorizationUpdate { StatusUpdate { status: storage_enums::AuthorizationStatus, error_code: Option<String>, error_message: Option<String>, connector_authorization_id: Option<String>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = incremental_authorization)] pub struct AuthorizationUpdateInternal { pub status: Option<storage_enums::AuthorizationStatus>, pub error_code: Option<String>, pub error_message: Option<String>, pub modified_at: Option<PrimitiveDateTime>, pub connector_authorization_id: Option<String>, } impl AuthorizationUpdateInternal { pub fn create_authorization(self, source: Authorization) -> Authorization { Authorization { status: self.status.unwrap_or(source.status), error_code: self.error_code.or(source.error_code), error_message: self.error_message.or(source.error_message), modified_at: self.modified_at.unwrap_or(common_utils::date_time::now()), connector_authorization_id: self .connector_authorization_id .or(source.connector_authorization_id), ..source } } } impl From<AuthorizationUpdate> for AuthorizationUpdateInternal { fn from(authorization_child_update: AuthorizationUpdate) -> Self { let now = Some(common_utils::date_time::now()); match authorization_child_update { AuthorizationUpdate::StatusUpdate { status, error_code, error_message, connector_authorization_id, } => Self { status: Some(status), error_code, error_message, connector_authorization_id, modified_at: now, }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/authorization.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-4308031231633404065
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/payment_methods_session.rs // Contains: 1 structs, 0 enums use common_utils::pii; #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodSession { pub id: common_utils::id_type::GlobalPaymentMethodSessionId, pub customer_id: common_utils::id_type::GlobalCustomerId, pub billing: Option<common_utils::encryption::Encryption>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, pub tokenization_data: Option<pii::SecretSerdeValue>, pub return_url: Option<common_utils::types::Url>, #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_at: time::PrimitiveDateTime, pub associated_payment_methods: Option<Vec<String>>, pub associated_payment: Option<common_utils::id_type::GlobalPaymentId>, pub associated_token_id: Option<common_utils::id_type::GlobalTokenId>, } #[cfg(feature = "v2")] impl PaymentMethodSession { pub fn apply_changeset(self, update_session: PaymentMethodsSessionUpdateInternal) -> Self { let Self { id, customer_id, billing, psp_tokenization, network_tokenization, tokenization_data, expires_at, return_url, associated_payment_methods, associated_payment, associated_token_id, } = self; Self { id, customer_id, billing: update_session.billing.or(billing), psp_tokenization: update_session.psp_tokenization.or(psp_tokenization), network_tokenization: update_session.network_tokenization.or(network_tokenization), tokenization_data: update_session.tokenzation_data.or(tokenization_data), expires_at, return_url, associated_payment_methods, associated_payment, associated_token_id, } } } #[cfg(feature = "v2")] pub struct PaymentMethodsSessionUpdateInternal { pub billing: Option<common_utils::encryption::Encryption>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, pub tokenzation_data: Option<masking::Secret<serde_json::Value>>, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/payment_methods_session.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_1252014060936777672
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/user_authentication_method.rs // Contains: 3 structs, 0 enums use common_utils::encryption::Encryption; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::user_authentication_methods}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = user_authentication_methods, check_for_backend(diesel::pg::Pg))] pub struct UserAuthenticationMethod { pub id: String, pub auth_id: String, pub owner_id: String, pub owner_type: enums::Owner, pub auth_type: enums::UserAuthType, pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub allow_signup: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub email_domain: String, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = user_authentication_methods)] pub struct UserAuthenticationMethodNew { pub id: String, pub auth_id: String, pub owner_id: String, pub owner_type: enums::Owner, pub auth_type: enums::UserAuthType, pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub allow_signup: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub email_domain: String, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = user_authentication_methods)] pub struct OrgAuthenticationMethodUpdateInternal { pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub last_modified_at: PrimitiveDateTime, pub email_domain: Option<String>, } pub enum UserAuthenticationMethodUpdate { UpdateConfig { private_config: Option<Encryption>, public_config: Option<serde_json::Value>, }, EmailDomain { email_domain: String, }, } impl From<UserAuthenticationMethodUpdate> for OrgAuthenticationMethodUpdateInternal { fn from(value: UserAuthenticationMethodUpdate) -> Self { let last_modified_at = common_utils::date_time::now(); match value { UserAuthenticationMethodUpdate::UpdateConfig { private_config, public_config, } => Self { private_config, public_config, last_modified_at, email_domain: None, }, UserAuthenticationMethodUpdate::EmailDomain { email_domain } => Self { private_config: None, public_config: None, last_modified_at, email_domain: Some(email_domain), }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/user_authentication_method.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_7226791687147623452
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/file.rs // Contains: 3 structs, 1 enums use common_utils::custom_serde; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::{Deserialize, Serialize}; use crate::schema::file_metadata; #[derive(Clone, Debug, Deserialize, Insertable, Serialize, router_derive::DebugAsDisplay)] #[diesel(table_name = file_metadata)] #[serde(deny_unknown_fields)] pub struct FileMetadataNew { pub file_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub file_name: Option<String>, pub file_size: i32, pub file_type: String, pub provider_file_id: Option<String>, pub file_upload_provider: Option<common_enums::FileUploadProvider>, pub available: bool, pub connector_label: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable, Selectable)] #[diesel(table_name = file_metadata, primary_key(file_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct FileMetadata { #[serde(skip_serializing)] pub file_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub file_name: Option<String>, pub file_size: i32, pub file_type: String, pub provider_file_id: Option<String>, pub file_upload_provider: Option<common_enums::FileUploadProvider>, pub available: bool, #[serde(with = "custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, pub connector_label: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug)] pub enum FileMetadataUpdate { Update { provider_file_id: Option<String>, file_upload_provider: Option<common_enums::FileUploadProvider>, available: bool, profile_id: Option<common_utils::id_type::ProfileId>, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = file_metadata)] pub struct FileMetadataUpdateInternal { provider_file_id: Option<String>, file_upload_provider: Option<common_enums::FileUploadProvider>, available: bool, profile_id: Option<common_utils::id_type::ProfileId>, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } impl From<FileMetadataUpdate> for FileMetadataUpdateInternal { fn from(merchant_account_update: FileMetadataUpdate) -> Self { match merchant_account_update { FileMetadataUpdate::Update { provider_file_id, file_upload_provider, available, profile_id, merchant_connector_id, } => Self { provider_file_id, file_upload_provider, available, profile_id, merchant_connector_id, }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/file.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_2698415017799226280
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/user/theme.rs // Contains: 3 structs, 1 enums use common_enums::EntityType; use common_utils::{ date_time, id_type, types::user::{EmailThemeConfig, ThemeLineage}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use router_derive::DebugAsDisplay; use time::PrimitiveDateTime; use crate::schema::themes; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = themes, primary_key(theme_id), check_for_backend(diesel::pg::Pg))] pub struct Theme { pub theme_id: String, 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 created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub entity_type: EntityType, pub theme_name: String, pub email_primary_color: String, pub email_foreground_color: String, pub email_background_color: String, pub email_entity_name: String, pub email_entity_logo_url: String, } #[derive(Clone, Debug, Insertable, DebugAsDisplay)] #[diesel(table_name = themes)] pub struct ThemeNew { pub theme_id: String, 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 created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub entity_type: EntityType, pub theme_name: String, pub email_primary_color: String, pub email_foreground_color: String, pub email_background_color: String, pub email_entity_name: String, pub email_entity_logo_url: String, } impl ThemeNew { pub fn new( theme_id: String, theme_name: String, lineage: ThemeLineage, email_config: EmailThemeConfig, ) -> Self { let now = date_time::now(); Self { theme_id, theme_name, tenant_id: lineage.tenant_id().to_owned(), org_id: lineage.org_id().cloned(), merchant_id: lineage.merchant_id().cloned(), profile_id: lineage.profile_id().cloned(), entity_type: lineage.entity_type(), created_at: now, last_modified_at: now, email_primary_color: email_config.primary_color, email_foreground_color: email_config.foreground_color, email_background_color: email_config.background_color, email_entity_name: email_config.entity_name, email_entity_logo_url: email_config.entity_logo_url, } } } impl Theme { pub fn email_config(&self) -> EmailThemeConfig { EmailThemeConfig { primary_color: self.email_primary_color.clone(), foreground_color: self.email_foreground_color.clone(), background_color: self.email_background_color.clone(), entity_name: self.email_entity_name.clone(), entity_logo_url: self.email_entity_logo_url.clone(), } } } #[derive(Clone, Debug, Default, AsChangeset, DebugAsDisplay)] #[diesel(table_name = themes)] pub struct ThemeUpdateInternal { pub email_primary_color: Option<String>, pub email_foreground_color: Option<String>, pub email_background_color: Option<String>, pub email_entity_name: Option<String>, pub email_entity_logo_url: Option<String>, } #[derive(Clone)] pub enum ThemeUpdate { EmailConfig { email_config: EmailThemeConfig }, } impl From<ThemeUpdate> for ThemeUpdateInternal { fn from(value: ThemeUpdate) -> Self { match value { ThemeUpdate::EmailConfig { email_config } => Self { email_primary_color: Some(email_config.primary_color), email_foreground_color: Some(email_config.foreground_color), email_background_color: Some(email_config.background_color), email_entity_name: Some(email_config.entity_name), email_entity_logo_url: Some(email_config.entity_logo_url), }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/user/theme.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-4468288212361529933
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/user/dashboard_metadata.rs // Contains: 3 structs, 1 enums use common_utils::id_type; use diesel::{query_builder::AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; use crate::{enums, schema::dashboard_metadata}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = dashboard_metadata, check_for_backend(diesel::pg::Pg))] pub struct DashboardMetadata { pub id: i32, pub user_id: Option<String>, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, pub data_key: enums::DashboardMetadata, pub data_value: Secret<serde_json::Value>, pub created_by: String, pub created_at: PrimitiveDateTime, pub last_modified_by: String, pub last_modified_at: PrimitiveDateTime, } #[derive( router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay, AsChangeset, )] #[diesel(table_name = dashboard_metadata)] pub struct DashboardMetadataNew { pub user_id: Option<String>, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, pub data_key: enums::DashboardMetadata, pub data_value: Secret<serde_json::Value>, pub created_by: String, pub created_at: PrimitiveDateTime, pub last_modified_by: String, pub last_modified_at: PrimitiveDateTime, } #[derive( router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay, AsChangeset, )] #[diesel(table_name = dashboard_metadata)] pub struct DashboardMetadataUpdateInternal { pub data_key: enums::DashboardMetadata, pub data_value: Secret<serde_json::Value>, pub last_modified_by: String, pub last_modified_at: PrimitiveDateTime, } #[derive(Debug)] pub enum DashboardMetadataUpdate { UpdateData { data_key: enums::DashboardMetadata, data_value: Secret<serde_json::Value>, last_modified_by: String, }, } impl From<DashboardMetadataUpdate> for DashboardMetadataUpdateInternal { fn from(metadata_update: DashboardMetadataUpdate) -> Self { let last_modified_at = common_utils::date_time::now(); match metadata_update { DashboardMetadataUpdate::UpdateData { data_key, data_value, last_modified_by, } => Self { data_key, data_value, last_modified_by, last_modified_at, }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/user/dashboard_metadata.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_diesel_models_-2772300347371185767
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/user/sample_data.rs // Contains: 1 structs, 0 enums #[cfg(feature = "v1")] use common_enums::{ AttemptStatus, AuthenticationType, CaptureMethod, Currency, PaymentExperience, PaymentMethod, PaymentMethodType, }; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; #[cfg(feature = "v1")] use common_utils::types::{ConnectorTransactionId, MinorUnit}; #[cfg(feature = "v1")] use serde::{Deserialize, Serialize}; #[cfg(feature = "v1")] use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::{ enums::{MandateDataType, MandateDetails}, schema::payment_attempt, ConnectorMandateReferenceId, NetworkDetails, PaymentAttemptNew, }; // #[cfg(feature = "v2")] // #[derive( // Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, // )] // #[diesel(table_name = payment_attempt)] // pub struct PaymentAttemptBatchNew { // pub payment_id: common_utils::id_type::PaymentId, // pub merchant_id: common_utils::id_type::MerchantId, // pub status: AttemptStatus, // pub error_message: Option<String>, // pub surcharge_amount: Option<i64>, // pub tax_on_surcharge: Option<i64>, // pub payment_method_id: Option<String>, // pub authentication_type: Option<AuthenticationType>, // #[serde(with = "common_utils::custom_serde::iso8601")] // pub created_at: PrimitiveDateTime, // #[serde(with = "common_utils::custom_serde::iso8601")] // pub modified_at: PrimitiveDateTime, // #[serde(default, with = "common_utils::custom_serde::iso8601::option")] // pub last_synced: Option<PrimitiveDateTime>, // pub cancellation_reason: Option<String>, // pub browser_info: Option<serde_json::Value>, // pub payment_token: Option<String>, // pub error_code: Option<String>, // pub connector_metadata: Option<serde_json::Value>, // pub payment_experience: Option<PaymentExperience>, // pub payment_method_data: Option<serde_json::Value>, // pub preprocessing_step_id: Option<String>, // pub error_reason: Option<String>, // pub connector_response_reference_id: Option<String>, // pub multiple_capture_count: Option<i16>, // pub amount_capturable: i64, // pub updated_by: String, // pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, // pub authentication_data: Option<serde_json::Value>, // pub encoded_data: Option<String>, // pub unified_code: Option<String>, // pub unified_message: Option<String>, // pub net_amount: Option<i64>, // pub external_three_ds_authentication_attempted: Option<bool>, // pub authentication_connector: Option<String>, // pub authentication_id: Option<String>, // pub fingerprint_id: Option<String>, // pub charge_id: Option<String>, // pub client_source: Option<String>, // pub client_version: Option<String>, // pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>, // pub profile_id: common_utils::id_type::ProfileId, // pub organization_id: common_utils::id_type::OrganizationId, // } // #[cfg(feature = "v2")] // #[allow(dead_code)] // impl PaymentAttemptBatchNew { // // Used to verify compatibility with PaymentAttemptTable // fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew { // // PaymentAttemptNew { // // payment_id: self.payment_id, // // merchant_id: self.merchant_id, // // status: self.status, // // error_message: self.error_message, // // surcharge_amount: self.surcharge_amount, // // tax_amount: self.tax_amount, // // payment_method_id: self.payment_method_id, // // confirm: self.confirm, // // authentication_type: self.authentication_type, // // created_at: self.created_at, // // modified_at: self.modified_at, // // last_synced: self.last_synced, // // cancellation_reason: self.cancellation_reason, // // browser_info: self.browser_info, // // payment_token: self.payment_token, // // error_code: self.error_code, // // connector_metadata: self.connector_metadata, // // payment_experience: self.payment_experience, // // card_network: self // // .payment_method_data // // .as_ref() // // .and_then(|data| data.as_object()) // // .and_then(|card| card.get("card")) // // .and_then(|v| v.as_object()) // // .and_then(|v| v.get("card_network")) // // .and_then(|network| network.as_str()) // // .map(|network| network.to_string()), // // payment_method_data: self.payment_method_data, // // straight_through_algorithm: self.straight_through_algorithm, // // preprocessing_step_id: self.preprocessing_step_id, // // error_reason: self.error_reason, // // multiple_capture_count: self.multiple_capture_count, // // connector_response_reference_id: self.connector_response_reference_id, // // amount_capturable: self.amount_capturable, // // updated_by: self.updated_by, // // merchant_connector_id: self.merchant_connector_id, // // authentication_data: self.authentication_data, // // encoded_data: self.encoded_data, // // unified_code: self.unified_code, // // unified_message: self.unified_message, // // net_amount: self.net_amount, // // external_three_ds_authentication_attempted: self // // .external_three_ds_authentication_attempted, // // authentication_connector: self.authentication_connector, // // authentication_id: self.authentication_id, // // payment_method_billing_address_id: self.payment_method_billing_address_id, // // fingerprint_id: self.fingerprint_id, // // charge_id: self.charge_id, // // client_source: self.client_source, // // client_version: self.client_version, // // customer_acceptance: self.customer_acceptance, // // profile_id: self.profile_id, // // organization_id: self.organization_id, // // } // todo!() // } // } #[cfg(feature = "v1")] #[derive( Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptBatchNew { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub status: AttemptStatus, pub amount: MinorUnit, pub currency: Option<Currency>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, pub offer_amount: Option<MinorUnit>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<PaymentMethod>, pub capture_method: Option<CaptureMethod>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<AuthenticationType>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub payment_token: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub payment_experience: Option<PaymentExperience>, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: Option<serde_json::Value>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, pub mandate_details: Option<MandateDataType>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub connector_transaction_id: Option<ConnectorTransactionId>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub updated_by: String, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub net_amount: Option<MinorUnit>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<common_utils::id_type::AuthenticationId>, pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, pub charge_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>, pub profile_id: common_utils::id_type::ProfileId, pub organization_id: common_utils::id_type::OrganizationId, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub processor_transaction_data: Option<String>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, pub created_by: Option<String>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, pub routing_approach: Option<common_enums::RoutingApproach>, pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub network_details: Option<NetworkDetails>, pub is_stored_credential: Option<bool>, pub authorized_amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[allow(dead_code)] impl PaymentAttemptBatchNew { // Used to verify compatibility with PaymentAttemptTable fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew { PaymentAttemptNew { payment_id: self.payment_id, merchant_id: self.merchant_id, attempt_id: self.attempt_id, status: self.status, amount: self.amount, currency: self.currency, save_to_locker: self.save_to_locker, connector: self.connector, error_message: self.error_message, offer_amount: self.offer_amount, surcharge_amount: self.surcharge_amount, tax_amount: self.tax_amount, payment_method_id: self.payment_method_id, payment_method: self.payment_method, capture_method: self.capture_method, capture_on: self.capture_on, confirm: self.confirm, authentication_type: self.authentication_type, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, amount_to_capture: self.amount_to_capture, mandate_id: self.mandate_id, browser_info: self.browser_info, payment_token: self.payment_token, error_code: self.error_code, connector_metadata: self.connector_metadata, payment_experience: self.payment_experience, payment_method_type: self.payment_method_type, card_network: self .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|v| v.as_object()) .and_then(|v| v.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), payment_method_data: self.payment_method_data, business_sub_label: self.business_sub_label, straight_through_algorithm: self.straight_through_algorithm, preprocessing_step_id: self.preprocessing_step_id, mandate_details: self.mandate_details, error_reason: self.error_reason, multiple_capture_count: self.multiple_capture_count, connector_response_reference_id: self.connector_response_reference_id, amount_capturable: self.amount_capturable, updated_by: self.updated_by, merchant_connector_id: self.merchant_connector_id, authentication_data: self.authentication_data, encoded_data: self.encoded_data, unified_code: self.unified_code, unified_message: self.unified_message, net_amount: self.net_amount, external_three_ds_authentication_attempted: self .external_three_ds_authentication_attempted, authentication_connector: self.authentication_connector, authentication_id: self.authentication_id, mandate_data: self.mandate_data, payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, client_source: self.client_source, client_version: self.client_version, customer_acceptance: self.customer_acceptance, profile_id: self.profile_id, organization_id: self.organization_id, shipping_cost: self.shipping_cost, order_tax_amount: self.order_tax_amount, connector_mandate_detail: self.connector_mandate_detail, request_extended_authorization: self.request_extended_authorization, extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, card_discovery: self.card_discovery, processor_merchant_id: self.processor_merchant_id, created_by: self.created_by, setup_future_usage_applied: self.setup_future_usage_applied, routing_approach: self.routing_approach, connector_request_reference_id: self.connector_request_reference_id, network_transaction_id: self.network_transaction_id, network_details: self.network_details, is_stored_credential: self.is_stored_credential, authorized_amount: self.authorized_amount, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/user/sample_data.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_scheduler_5786783722312284601
clm
file
// Repository: hyperswitch // Crate: scheduler // File: crates/scheduler/src/settings.rs // Contains: 3 structs, 0 enums use common_utils::ext_traits::ConfigExt; use serde::Deserialize; use storage_impl::errors::ApplicationError; pub use crate::configs::settings::SchedulerSettings; #[derive(Debug, Clone, Deserialize)] pub struct ProducerSettings { pub upper_fetch_limit: i64, pub lower_fetch_limit: i64, pub lock_key: String, pub lock_ttl: i64, pub batch_size: usize, } #[derive(Debug, Clone, Deserialize)] pub struct ConsumerSettings { pub disabled: bool, pub consumer_group: String, } #[cfg(feature = "kv_store")] #[derive(Debug, Clone, Deserialize)] pub struct DrainerSettings { pub stream_name: String, pub num_partitions: u8, pub max_read_count: u64, pub shutdown_interval: u32, // in milliseconds pub loop_interval: u32, // in milliseconds } impl ProducerSettings { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.lock_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "producer lock key must not be empty".into(), )) }) } } #[cfg(feature = "kv_store")] impl DrainerSettings { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "drainer stream name must not be empty".into(), )) }) } } impl Default for ProducerSettings { fn default() -> Self { Self { upper_fetch_limit: 0, lower_fetch_limit: 1800, lock_key: "PRODUCER_LOCKING_KEY".into(), lock_ttl: 160, batch_size: 200, } } } impl Default for ConsumerSettings { fn default() -> Self { Self { disabled: false, consumer_group: "SCHEDULER_GROUP".into(), } } } #[cfg(feature = "kv_store")] impl Default for DrainerSettings { fn default() -> Self { Self { stream_name: "DRAINER_STREAM".into(), num_partitions: 64, max_read_count: 100, shutdown_interval: 1000, loop_interval: 500, } } }
{ "crate": "scheduler", "file": "crates/scheduler/src/settings.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_scheduler_7177750396832730221
clm
file
// Repository: hyperswitch // Crate: scheduler // File: crates/scheduler/src/configs/settings.rs // Contains: 4 structs, 0 enums pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use serde::Deserialize; #[derive(Debug, Clone, Deserialize)] #[serde(default)] pub struct SchedulerSettings { pub stream: String, pub producer: ProducerSettings, pub consumer: ConsumerSettings, pub loop_interval: u64, pub graceful_shutdown_interval: u64, pub server: Server, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Server { pub port: u16, pub workers: usize, pub host: String, } #[derive(Debug, Clone, Deserialize)] #[serde(default)] pub struct ProducerSettings { pub upper_fetch_limit: i64, pub lower_fetch_limit: i64, pub lock_key: String, pub lock_ttl: i64, pub batch_size: usize, } #[derive(Debug, Clone, Deserialize)] #[serde(default)] pub struct ConsumerSettings { pub disabled: bool, pub consumer_group: String, }
{ "crate": "scheduler", "file": "crates/scheduler/src/configs/settings.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_scheduler_-342653190067380620
clm
file
// Repository: hyperswitch // Crate: scheduler // File: crates/scheduler/src/consumer/types/batch.rs // Contains: 1 structs, 0 enums use std::collections::HashMap; use common_utils::{errors::CustomResult, ext_traits::OptionExt}; use diesel_models::process_tracker::ProcessTracker; use error_stack::ResultExt; use time::PrimitiveDateTime; use crate::errors; #[derive(Debug, Clone)] pub struct ProcessTrackerBatch { pub id: String, pub group_name: String, pub stream_name: String, pub connection_name: String, pub created_time: PrimitiveDateTime, pub rule: String, // is it required? pub trackers: Vec<ProcessTracker>, /* FIXME: Add sized also here, list */ } impl ProcessTrackerBatch { pub fn to_redis_field_value_pairs( &self, ) -> CustomResult<Vec<(&str, String)>, errors::ProcessTrackerError> { Ok(vec![ ("id", self.id.to_string()), ("group_name", self.group_name.to_string()), ("stream_name", self.stream_name.to_string()), ("connection_name", self.connection_name.to_string()), ( "created_time", self.created_time.assume_utc().unix_timestamp().to_string(), ), ("rule", self.rule.to_string()), ( "trackers", serde_json::to_string(&self.trackers) .change_context(errors::ProcessTrackerError::SerializationFailed) .attach_printable_lazy(|| { format!("Unable to stringify trackers: {:?}", self.trackers) })?, ), ]) } pub fn from_redis_stream_entry( entry: HashMap<String, Option<String>>, ) -> CustomResult<Self, errors::ProcessTrackerError> { let mut entry = entry; let id = entry .remove("id") .flatten() .get_required_value("id") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let group_name = entry .remove("group_name") .flatten() .get_required_value("group_name") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let stream_name = entry .remove("stream_name") .flatten() .get_required_value("stream_name") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let connection_name = entry .remove("connection_name") .flatten() .get_required_value("connection_name") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let created_time = entry .remove("created_time") .flatten() .get_required_value("created_time") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; //make it parser error let created_time = { let offset_date_time = time::OffsetDateTime::from_unix_timestamp( created_time .as_str() .parse::<i64>() .change_context(errors::ParsingError::UnknownError) .change_context(errors::ProcessTrackerError::DeserializationFailed)?, ) .attach_printable_lazy(|| format!("Unable to parse time {}", &created_time)) .change_context(errors::ProcessTrackerError::MissingRequiredField)?; PrimitiveDateTime::new(offset_date_time.date(), offset_date_time.time()) }; let rule = entry .remove("rule") .flatten() .get_required_value("rule") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let trackers = entry .remove("trackers") .flatten() .get_required_value("trackers") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let trackers = serde_json::from_str::<Vec<ProcessTracker>>(trackers.as_str()) .change_context(errors::ParsingError::UnknownError) .attach_printable_lazy(|| { format!("Unable to parse trackers from JSON string: {trackers:?}") }) .change_context(errors::ProcessTrackerError::DeserializationFailed) .attach_printable("Error parsing ProcessTracker from redis stream entry")?; Ok(Self { id, group_name, stream_name, connection_name, created_time, rule, trackers, }) } }
{ "crate": "scheduler", "file": "crates/scheduler/src/consumer/types/batch.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_scheduler_-4049434687443619087
clm
file
// Repository: hyperswitch // Crate: scheduler // File: crates/scheduler/src/consumer/types/process_data.rs // Contains: 6 structs, 0 enums use std::collections::HashMap; use diesel_models::enums; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct RetryMapping { pub start_after: i32, pub frequencies: Vec<(i32, i32)>, // (frequency, count) } #[derive(Serialize, Deserialize)] pub struct ConnectorPTMapping { pub default_mapping: RetryMapping, pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>, pub max_retries_count: i32, } impl Default for ConnectorPTMapping { fn default() -> Self { Self { custom_merchant_mapping: HashMap::new(), default_mapping: RetryMapping { start_after: 60, frequencies: vec![(300, 5)], }, max_retries_count: 5, } } } #[derive(Serialize, Deserialize)] pub struct SubscriptionInvoiceSyncPTMapping { pub default_mapping: RetryMapping, pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>, pub max_retries_count: i32, } impl Default for SubscriptionInvoiceSyncPTMapping { fn default() -> Self { Self { custom_merchant_mapping: HashMap::new(), default_mapping: RetryMapping { start_after: 60, frequencies: vec![(300, 5)], }, max_retries_count: 5, } } } #[derive(Serialize, Deserialize)] pub struct PaymentMethodsPTMapping { pub default_mapping: RetryMapping, pub custom_pm_mapping: HashMap<enums::PaymentMethod, RetryMapping>, pub max_retries_count: i32, } impl Default for PaymentMethodsPTMapping { fn default() -> Self { Self { custom_pm_mapping: HashMap::new(), default_mapping: RetryMapping { start_after: 900, frequencies: vec![(300, 5)], }, max_retries_count: 5, } } } /// Configuration for outgoing webhook retries. #[derive(Debug, Serialize, Deserialize)] pub struct OutgoingWebhookRetryProcessTrackerMapping { /// Default (fallback) retry configuration used when no merchant-specific retry configuration /// exists. pub default_mapping: RetryMapping, /// Merchant-specific retry configuration. pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>, } impl Default for OutgoingWebhookRetryProcessTrackerMapping { fn default() -> Self { Self { default_mapping: RetryMapping { // 1st attempt happens after 1 minute start_after: 60, frequencies: vec![ // 2nd and 3rd attempts happen at intervals of 5 minutes each (60 * 5, 2), // 4th, 5th, 6th, 7th and 8th attempts happen at intervals of 10 minutes each (60 * 10, 5), // 9th, 10th, 11th, 12th and 13th attempts happen at intervals of 1 hour each (60 * 60, 5), // 14th, 15th and 16th attempts happen at intervals of 6 hours each (60 * 60 * 6, 3), ], }, custom_merchant_mapping: HashMap::new(), } } } /// Configuration for outgoing webhook retries. #[derive(Debug, Serialize, Deserialize)] pub struct RevenueRecoveryPaymentProcessTrackerMapping { /// Default (fallback) retry configuration used when no merchant-specific retry configuration /// exists. pub default_mapping: RetryMapping, /// Merchant-specific retry configuration. pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>, } impl Default for RevenueRecoveryPaymentProcessTrackerMapping { fn default() -> Self { Self { default_mapping: RetryMapping { // 1st attempt happens after 1 minute of it being start_after: 60, frequencies: vec![ // 2nd and 3rd attempts happen at intervals of 3 hours each (60 * 60 * 3, 2), // 4th, 5th, 6th attempts happen at intervals of 6 hours each (60 * 60 * 6, 3), // 7th, 8th, 9th attempts happen at intervals of 9 hour each (60 * 60 * 9, 3), // 10th, 11th and 12th attempts happen at intervals of 12 hours each (60 * 60 * 12, 3), // 13th, 14th and 15th attempts happen at intervals of 18 hours each (60 * 60 * 18, 3), ], }, custom_merchant_mapping: HashMap::new(), } } }
{ "crate": "scheduler", "file": "crates/scheduler/src/consumer/types/process_data.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_smithy-generator_-8451817214803621882
clm
file
// Repository: hyperswitch // Crate: smithy-generator // File: crates/smithy-generator/build.rs // Contains: 1 structs, 0 enums // crates/smithy-generator/build.rs use std::{fs, path::Path}; use regex::Regex; fn main() -> Result<(), Box<dyn std::error::Error>> { println!("cargo:rerun-if-changed=../"); run_build() } fn run_build() -> Result<(), Box<dyn std::error::Error>> { let workspace_root = get_workspace_root()?; let mut smithy_models = Vec::new(); // Scan all crates in the workspace for SmithyModel derives let crates_dir = workspace_root.join("crates"); if let Ok(entries) = fs::read_dir(&crates_dir) { for entry in entries.flatten() { if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) { let crate_path = entry.path(); let crate_name = match crate_path.file_name() { Some(name) => name.to_string_lossy(), None => { println!( "cargo:warning=Skipping crate with invalid path: {}", crate_path.display() ); continue; } }; // Skip the smithy crate itself to avoid self-dependency if crate_name == "smithy" || crate_name == "smithy-core" || crate_name == "smithy-generator" { continue; } if let Err(e) = scan_crate_for_smithy_models(&crate_path, &crate_name, &mut smithy_models) { println!("cargo:warning=Failed to scan crate {}: {}", crate_name, e); } } } } // Generate the registry file generate_model_registry(&smithy_models)?; Ok(()) } fn get_workspace_root() -> Result<std::path::PathBuf, Box<dyn std::error::Error>> { let manifest_dir = std::env::var("CARGO_MANIFEST_DIR") .map_err(|_| "CARGO_MANIFEST_DIR environment variable not set")?; let manifest_path = Path::new(&manifest_dir); let parent1 = manifest_path .parent() .ok_or("Cannot get parent directory of CARGO_MANIFEST_DIR")?; let workspace_root = parent1 .parent() .ok_or("Cannot get workspace root directory")?; Ok(workspace_root.to_path_buf()) } fn scan_crate_for_smithy_models( crate_path: &Path, crate_name: &str, models: &mut Vec<SmithyModelInfo>, ) -> Result<(), Box<dyn std::error::Error>> { let src_path = crate_path.join("src"); if !src_path.exists() { return Ok(()); } scan_directory(&src_path, crate_name, "", models)?; Ok(()) } fn scan_directory( dir: &Path, crate_name: &str, module_path: &str, models: &mut Vec<SmithyModelInfo>, ) -> Result<(), Box<dyn std::error::Error>> { if let Ok(entries) = fs::read_dir(dir) { for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { let dir_name = match path.file_name() { Some(name) => name.to_string_lossy(), None => { println!( "cargo:warning=Skipping directory with invalid name: {}", path.display() ); continue; } }; let new_module_path = if module_path.is_empty() { dir_name.to_string() } else { format!("{}::{}", module_path, dir_name) }; scan_directory(&path, crate_name, &new_module_path, models)?; } else if path.extension().map(|ext| ext == "rs").unwrap_or(false) { if let Err(e) = scan_rust_file(&path, crate_name, module_path, models) { println!( "cargo:warning=Failed to scan Rust file {}: {}", path.display(), e ); } } } } Ok(()) } fn scan_rust_file( file_path: &Path, crate_name: &str, module_path: &str, models: &mut Vec<SmithyModelInfo>, ) -> Result<(), Box<dyn std::error::Error>> { if let Ok(content) = fs::read_to_string(file_path) { // Enhanced regex that handles comments, doc comments, and multiple attributes // between derive and struct/enum declarations let re = Regex::new(r"(?ms)^#\[derive\(([^)]*(?:\([^)]*\))*[^)]*)\)\]\s*(?:(?:#\[[^\]]*\]\s*)|(?://[^\r\n]*\s*)|(?:///[^\r\n]*\s*)|(?:/\*.*?\*/\s*))*(?:pub\s+)?(?:struct|enum)\s+([A-Z][A-Za-z0-9_]*)\s*[<\{\(]") .map_err(|e| format!("Failed to compile regex: {}", e))?; for captures in re.captures_iter(&content) { let derive_content = match captures.get(1) { Some(capture) => capture.as_str(), None => { println!( "cargo:warning=Missing derive content in regex capture for {}", file_path.display() ); continue; } }; let item_name = match captures.get(2) { Some(capture) => capture.as_str(), None => { println!( "cargo:warning=Missing item name in regex capture for {}", file_path.display() ); continue; } }; // Check if "SmithyModel" is present in the derive macro's content. if derive_content.contains("SmithyModel") { // Validate that the item name is a valid Rust identifier if is_valid_rust_identifier(item_name) { let full_module_path = create_module_path(file_path, crate_name, module_path)?; models.push(SmithyModelInfo { struct_name: item_name.to_string(), module_path: full_module_path, }); } else { println!( "cargo:warning=Skipping invalid identifier: {} in {}", item_name, file_path.display() ); } } } } Ok(()) } fn is_valid_rust_identifier(name: &str) -> bool { if name.is_empty() { return false; } // Rust identifiers must start with a letter or underscore let first_char = match name.chars().next() { Some(ch) => ch, None => return false, // This shouldn't happen since we checked is_empty above, but being safe }; if !first_char.is_ascii_alphabetic() && first_char != '_' { return false; } // Must not be a Rust keyword let keywords = [ "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while", "async", "await", "dyn", "is", "abstract", "become", "box", "do", "final", "macro", "override", "priv", "typeof", "unsized", "virtual", "yield", "try", ]; if keywords.contains(&name) { return false; } // All other characters must be alphanumeric or underscore name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') } fn create_module_path( file_path: &Path, crate_name: &str, module_path: &str, ) -> Result<String, Box<dyn std::error::Error>> { let file_name = file_path .file_stem() .and_then(|s| s.to_str()) .ok_or_else(|| { format!( "Cannot extract file name from path: {}", file_path.display() ) })?; let crate_name_normalized = crate_name.replace('-', "_"); let result = if file_name == "lib" || file_name == "mod" { if module_path.is_empty() { crate_name_normalized } else { format!("{}::{}", crate_name_normalized, module_path) } } else if module_path.is_empty() { format!("{}::{}", crate_name_normalized, file_name) } else { format!("{}::{}::{}", crate_name_normalized, module_path, file_name) }; Ok(result) } #[derive(Debug)] struct SmithyModelInfo { struct_name: String, module_path: String, } fn generate_model_registry(models: &[SmithyModelInfo]) -> Result<(), Box<dyn std::error::Error>> { let out_dir = std::env::var("OUT_DIR").map_err(|_| "OUT_DIR environment variable not set")?; let registry_path = Path::new(&out_dir).join("model_registry.rs"); let mut content = String::new(); content.push_str("// Auto-generated model registry\n"); content.push_str("// DO NOT EDIT - This file is generated by build.rs\n\n"); if !models.is_empty() { content.push_str("use smithy_core::{SmithyModel, SmithyModelGenerator};\n\n"); // Generate imports for model in models { content.push_str(&format!( "use {}::{};\n", model.module_path, model.struct_name )); } content.push_str("\npub fn discover_smithy_models() -> Vec<SmithyModel> {\n"); content.push_str(" let mut models = Vec::new();\n\n"); // Generate model collection calls for model in models { content.push_str(&format!( " models.push({}::generate_smithy_model());\n", model.struct_name )); } content.push_str("\n models\n"); content.push_str("}\n"); } else { // Generate empty function if no models found content.push_str("use smithy_core::SmithyModel;\n\n"); content.push_str("pub fn discover_smithy_models() -> Vec<SmithyModel> {\n"); content.push_str( " router_env::logger::info!(\"No SmithyModel structs found in workspace\");\n", ); content.push_str(" Vec::new()\n"); content.push_str("}\n"); } fs::write(&registry_path, content).map_err(|e| { format!( "Failed to write model registry to {}: {}", registry_path.display(), e ) })?; Ok(()) }
{ "crate": "smithy-generator", "file": "crates/smithy-generator/build.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_drainer_-191993876264187747
clm
file
// Repository: hyperswitch // Crate: drainer // File: crates/drainer/src/types.rs // Contains: 1 structs, 0 enums use std::collections::HashMap; use common_utils::errors; use error_stack::ResultExt; use serde::{de::value::MapDeserializer, Deserialize, Serialize}; use crate::{ kv, utils::{deserialize_db_op, deserialize_i64}, }; #[derive(Deserialize, Serialize)] pub struct StreamData { pub request_id: String, pub global_id: String, #[serde(deserialize_with = "deserialize_db_op")] pub typed_sql: kv::DBOperation, #[serde(deserialize_with = "deserialize_i64")] pub pushed_at: i64, } impl StreamData { pub fn from_hashmap( hashmap: HashMap<String, String>, ) -> errors::CustomResult<Self, errors::ParsingError> { let iter = MapDeserializer::< '_, std::collections::hash_map::IntoIter<String, String>, serde_json::error::Error, >::new(hashmap.into_iter()); Self::deserialize(iter) .change_context(errors::ParsingError::StructParseFailure("StreamData")) } }
{ "crate": "drainer", "file": "crates/drainer/src/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_drainer_2643812079853217401
clm
file
// Repository: hyperswitch // Crate: drainer // File: crates/drainer/src/handler.rs // Contains: 1 structs, 0 enums use std::{ collections::HashMap, sync::{atomic, Arc}, }; use common_utils::id_type; use router_env::tracing::Instrument; use tokio::{ sync::{mpsc, oneshot}, time::{self, Duration}, }; use crate::{ errors, instrument, logger, metrics, query::ExecuteQuery, tracing, utils, DrainerSettings, Store, StreamData, }; /// Handler handles the spawning and closing of drainer /// Arc is used to enable creating a listener for graceful shutdown #[derive(Clone)] pub struct Handler { inner: Arc<HandlerInner>, } impl std::ops::Deref for Handler { type Target = HandlerInner; fn deref(&self) -> &Self::Target { &self.inner } } pub struct HandlerInner { shutdown_interval: Duration, loop_interval: Duration, active_tasks: Arc<atomic::AtomicU64>, conf: DrainerSettings, stores: HashMap<id_type::TenantId, Arc<Store>>, running: Arc<atomic::AtomicBool>, } impl Handler { pub fn from_conf( conf: DrainerSettings, stores: HashMap<id_type::TenantId, Arc<Store>>, ) -> Self { let shutdown_interval = Duration::from_millis(conf.shutdown_interval.into()); let loop_interval = Duration::from_millis(conf.loop_interval.into()); let active_tasks = Arc::new(atomic::AtomicU64::new(0)); let running = Arc::new(atomic::AtomicBool::new(true)); let handler = HandlerInner { shutdown_interval, loop_interval, active_tasks, conf, stores, running, }; Self { inner: Arc::new(handler), } } pub fn close(&self) { self.running.store(false, atomic::Ordering::SeqCst); } pub async fn spawn(&self) -> errors::DrainerResult<()> { let mut stream_index: u8 = 0; let jobs_picked = Arc::new(atomic::AtomicU8::new(0)); while self.running.load(atomic::Ordering::SeqCst) { metrics::DRAINER_HEALTH.add(1, &[]); for store in self.stores.values() { if store.is_stream_available(stream_index).await { let _task_handle = tokio::spawn( drainer_handler( store.clone(), stream_index, self.conf.max_read_count, self.active_tasks.clone(), jobs_picked.clone(), ) .in_current_span(), ); } } stream_index = utils::increment_stream_index( (stream_index, jobs_picked.clone()), self.conf.num_partitions, ) .await; time::sleep(self.loop_interval).await; } Ok(()) } pub(crate) async fn shutdown_listener(&self, mut rx: mpsc::Receiver<()>) { while let Some(_c) = rx.recv().await { logger::info!("Awaiting shutdown!"); metrics::SHUTDOWN_SIGNAL_RECEIVED.add(1, &[]); let shutdown_started = time::Instant::now(); rx.close(); //Check until the active tasks are zero. This does not include the tasks in the stream. while self.active_tasks.load(atomic::Ordering::SeqCst) != 0 { time::sleep(self.shutdown_interval).await; } logger::info!("Terminating drainer"); metrics::SUCCESSFUL_SHUTDOWN.add(1, &[]); let shutdown_ended = shutdown_started.elapsed().as_secs_f64() * 1000f64; metrics::CLEANUP_TIME.record(shutdown_ended, &[]); self.close(); } logger::info!( tasks_remaining = self.active_tasks.load(atomic::Ordering::SeqCst), "Drainer shutdown successfully" ) } pub fn spawn_error_handlers(&self, tx: mpsc::Sender<()>) -> errors::DrainerResult<()> { let (redis_error_tx, redis_error_rx) = oneshot::channel(); let redis_conn_clone = self .stores .values() .next() .map(|store| store.redis_conn.clone()); match redis_conn_clone { None => { logger::error!("No redis connection found"); Err( errors::DrainerError::UnexpectedError("No redis connection found".to_string()) .into(), ) } Some(redis_conn_clone) => { // Spawn a task to monitor if redis is down or not let _task_handle = tokio::spawn( async move { redis_conn_clone.on_error(redis_error_tx).await } .in_current_span(), ); //Spawns a task to send shutdown signal if redis goes down let _task_handle = tokio::spawn(redis_error_receiver(redis_error_rx, tx).in_current_span()); Ok(()) } } } } pub async fn redis_error_receiver(rx: oneshot::Receiver<()>, shutdown_channel: mpsc::Sender<()>) { match rx.await { Ok(_) => { logger::error!("The redis server failed"); let _ = shutdown_channel.send(()).await.map_err(|err| { logger::error!("Failed to send signal to the shutdown channel {err}") }); } Err(err) => { logger::error!("Channel receiver error {err}"); } } } #[router_env::instrument(skip_all)] async fn drainer_handler( store: Arc<Store>, stream_index: u8, max_read_count: u64, active_tasks: Arc<atomic::AtomicU64>, jobs_picked: Arc<atomic::AtomicU8>, ) -> errors::DrainerResult<()> { active_tasks.fetch_add(1, atomic::Ordering::Release); let stream_name = store.get_drainer_stream_name(stream_index); let drainer_result = Box::pin(drainer( store.clone(), max_read_count, stream_name.as_str(), jobs_picked, )) .await; if let Err(error) = drainer_result { logger::error!(?error) } let flag_stream_name = store.get_stream_key_flag(stream_index); let output = store.make_stream_available(flag_stream_name.as_str()).await; active_tasks.fetch_sub(1, atomic::Ordering::Release); output.inspect_err(|err| logger::error!(operation = "unlock_stream", err=?err)) } #[instrument(skip_all, fields(global_id, request_id, session_id))] async fn drainer( store: Arc<Store>, max_read_count: u64, stream_name: &str, jobs_picked: Arc<atomic::AtomicU8>, ) -> errors::DrainerResult<()> { let stream_read = match store.read_from_stream(stream_name, max_read_count).await { Ok(result) => { jobs_picked.fetch_add(1, atomic::Ordering::SeqCst); result } Err(error) => { if let errors::DrainerError::RedisError(redis_err) = error.current_context() { if let redis_interface::errors::RedisError::StreamEmptyOrNotAvailable = redis_err.current_context() { metrics::STREAM_EMPTY.add(1, &[]); return Ok(()); } else { return Err(error); } } else { return Err(error); } } }; // parse_stream_entries returns error if no entries is found, handle it let entries = utils::parse_stream_entries( &stream_read, store.redis_conn.add_prefix(stream_name).as_str(), )?; let read_count = entries.len(); metrics::JOBS_PICKED_PER_STREAM.add( u64::try_from(read_count).unwrap_or(u64::MIN), router_env::metric_attributes!(("stream", stream_name.to_owned())), ); let session_id = common_utils::generate_id_with_default_len("drainer_session"); let mut last_processed_id = String::new(); for (entry_id, entry) in entries.clone() { let data = match StreamData::from_hashmap(entry) { Ok(data) => data, Err(err) => { logger::error!(operation = "deserialization", err=?err); metrics::STREAM_PARSE_FAIL.add( 1, router_env::metric_attributes!(("operation", "deserialization")), ); // break from the loop in case of a deser error break; } }; tracing::Span::current().record("request_id", data.request_id); tracing::Span::current().record("global_id", data.global_id); tracing::Span::current().record("session_id", &session_id); match data.typed_sql.execute_query(&store, data.pushed_at).await { Ok(_) => { last_processed_id = entry_id; } Err(err) => match err.current_context() { // In case of Uniqueviolation we can't really do anything to fix it so just clear // it from the stream diesel_models::errors::DatabaseError::UniqueViolation => { last_processed_id = entry_id; } // break from the loop in case of an error in query _ => break, }, } if store.use_legacy_version() { store .delete_from_stream(stream_name, &last_processed_id) .await?; } } if !(last_processed_id.is_empty() || store.use_legacy_version()) { let entries_trimmed = store .trim_from_stream(stream_name, &last_processed_id) .await?; if read_count != entries_trimmed { logger::error!( read_entries = %read_count, trimmed_entries = %entries_trimmed, ?entries, "Assertion Failed no. of entries read from the stream doesn't match no. of entries trimmed" ); } } else { logger::error!(read_entries = %read_count,?entries,"No streams were processed in this session"); } Ok(()) }
{ "crate": "drainer", "file": "crates/drainer/src/handler.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_drainer_5296136559143663995
clm
file
// Repository: hyperswitch // Crate: drainer // File: crates/drainer/src/services.rs // Contains: 2 structs, 0 enums use std::sync::Arc; use actix_web::{body, HttpResponse, ResponseError}; use error_stack::Report; use redis_interface::RedisConnectionPool; use crate::{ connection::{diesel_make_pg_pool, PgPool}, logger, settings::Tenant, }; #[derive(Clone)] pub struct Store { pub master_pool: PgPool, pub redis_conn: Arc<RedisConnectionPool>, pub config: StoreConfig, pub request_id: Option<String>, } #[derive(Clone)] pub struct StoreConfig { pub drainer_stream_name: String, pub drainer_num_partitions: u8, pub use_legacy_version: bool, } impl Store { /// # Panics /// /// Panics if there is a failure while obtaining the HashiCorp client using the provided configuration. /// This panic indicates a critical failure in setting up external services, and the application cannot proceed without a valid HashiCorp client. pub async fn new(config: &crate::Settings, test_transaction: bool, tenant: &Tenant) -> Self { let redis_conn = crate::connection::redis_connection(config).await; Self { master_pool: diesel_make_pg_pool( config.master_database.get_inner(), test_transaction, &tenant.schema, ) .await, redis_conn: Arc::new(RedisConnectionPool::clone( &redis_conn, &tenant.redis_key_prefix, )), config: StoreConfig { drainer_stream_name: config.drainer.stream_name.clone(), drainer_num_partitions: config.drainer.num_partitions, use_legacy_version: config.redis.use_legacy_version, }, request_id: None, } } pub fn use_legacy_version(&self) -> bool { self.config.use_legacy_version } } pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse where T: error_stack::Context + ResponseError + Clone, { logger::error!(?error); let body = serde_json::json!({ "message": error.to_string() }) .to_string(); HttpResponse::InternalServerError() .content_type(mime::APPLICATION_JSON) .body(body) } pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse { HttpResponse::Ok() .content_type(mime::APPLICATION_JSON) .body(response) }
{ "crate": "drainer", "file": "crates/drainer/src/services.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_drainer_8537027464423134633
clm
file
// Repository: hyperswitch // Crate: drainer // File: crates/drainer/src/health_check.rs // Contains: 1 structs, 2 enums use std::{collections::HashMap, sync::Arc}; use actix_web::{web, Scope}; use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; use common_utils::{errors::CustomResult, id_type}; use diesel_models::{Config, ConfigNew}; use error_stack::ResultExt; use router_env::{instrument, logger, tracing}; use crate::{ connection::pg_connection, errors::HealthCheckError, services::{self, log_and_return_error_response, Store}, Settings, }; pub const TEST_STREAM_NAME: &str = "TEST_STREAM_0"; pub const TEST_STREAM_DATA: &[(&str, &str)] = &[("data", "sample_data")]; pub struct Health; impl Health { pub fn server(conf: Settings, stores: HashMap<id_type::TenantId, Arc<Store>>) -> Scope { web::scope("health") .app_data(web::Data::new(conf)) .app_data(web::Data::new(stores)) .service(web::resource("").route(web::get().to(health))) .service(web::resource("/ready").route(web::get().to(deep_health_check))) } } #[instrument(skip_all)] pub async fn health() -> impl actix_web::Responder { logger::info!("Drainer health was called"); actix_web::HttpResponse::Ok().body("Drainer health is good") } #[instrument(skip_all)] pub async fn deep_health_check( conf: web::Data<Settings>, stores: web::Data<HashMap<String, Arc<Store>>>, ) -> impl actix_web::Responder { let mut deep_health_res = HashMap::new(); for (tenant, store) in stores.iter() { logger::info!("Tenant: {:?}", tenant); let response = match deep_health_check_func(conf.clone(), store).await { Ok(response) => serde_json::to_string(&response) .map_err(|err| { logger::error!(serialization_error=?err); }) .unwrap_or_default(), Err(err) => return log_and_return_error_response(err), }; deep_health_res.insert(tenant.clone(), response); } services::http_response_json( serde_json::to_string(&deep_health_res) .map_err(|err| { logger::error!(serialization_error=?err); }) .unwrap_or_default(), ) } #[instrument(skip_all)] pub async fn deep_health_check_func( conf: web::Data<Settings>, store: &Arc<Store>, ) -> Result<DrainerHealthCheckResponse, error_stack::Report<HealthCheckError>> { logger::info!("Deep health check was called"); logger::debug!("Database health check begin"); let db_status = store .health_check_db() .await .map(|_| true) .map_err(|error| { let message = error.to_string(); error.change_context(HealthCheckError::DbError { message }) })?; logger::debug!("Database health check end"); logger::debug!("Redis health check begin"); let redis_status = store .health_check_redis(&conf.into_inner()) .await .map(|_| true) .map_err(|error| { let message = error.to_string(); error.change_context(HealthCheckError::RedisError { message }) })?; logger::debug!("Redis health check end"); Ok(DrainerHealthCheckResponse { database: db_status, redis: redis_status, }) } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DrainerHealthCheckResponse { pub database: bool, pub redis: bool, } #[async_trait::async_trait] pub trait HealthCheckInterface { async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError>; async fn health_check_redis(&self, conf: &Settings) -> CustomResult<(), HealthCheckRedisError>; } #[async_trait::async_trait] impl HealthCheckInterface for Store { async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError> { let conn = pg_connection(&self.master_pool).await; conn .transaction_async(|conn| { Box::pin(async move { let query = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1")); let _x: i32 = query.get_result_async(&conn).await.map_err(|err| { logger::error!(read_err=?err,"Error while reading element in the database"); HealthCheckDBError::DbReadError })?; logger::debug!("Database read was successful"); let config = ConfigNew { key: "test_key".to_string(), config: "test_value".to_string(), }; config.insert(&conn).await.map_err(|err| { logger::error!(write_err=?err,"Error while writing to database"); HealthCheckDBError::DbWriteError })?; logger::debug!("Database write was successful"); Config::delete_by_key(&conn, "test_key").await.map_err(|err| { logger::error!(delete_err=?err,"Error while deleting element in the database"); HealthCheckDBError::DbDeleteError })?; logger::debug!("Database delete was successful"); Ok::<_, HealthCheckDBError>(()) }) }) .await?; Ok(()) } async fn health_check_redis( &self, _conf: &Settings, ) -> CustomResult<(), HealthCheckRedisError> { let redis_conn = self.redis_conn.clone(); redis_conn .serialize_and_set_key_with_expiry(&"test_key".into(), "test_value", 30) .await .change_context(HealthCheckRedisError::SetFailed)?; logger::debug!("Redis set_key was successful"); redis_conn .get_key::<()>(&"test_key".into()) .await .change_context(HealthCheckRedisError::GetFailed)?; logger::debug!("Redis get_key was successful"); redis_conn .delete_key(&"test_key".into()) .await .change_context(HealthCheckRedisError::DeleteFailed)?; logger::debug!("Redis delete_key was successful"); redis_conn .stream_append_entry( &TEST_STREAM_NAME.into(), &redis_interface::RedisEntryId::AutoGeneratedID, TEST_STREAM_DATA.to_vec(), ) .await .change_context(HealthCheckRedisError::StreamAppendFailed)?; logger::debug!("Stream append succeeded"); let output = redis_conn .stream_read_entries(TEST_STREAM_NAME, "0-0", Some(10)) .await .change_context(HealthCheckRedisError::StreamReadFailed)?; logger::debug!("Stream read succeeded"); let (_, id_to_trim) = output .get(&redis_conn.add_prefix(TEST_STREAM_NAME)) .and_then(|entries| { entries .last() .map(|last_entry| (entries, last_entry.0.clone())) }) .ok_or(error_stack::report!( HealthCheckRedisError::StreamReadFailed ))?; logger::debug!("Stream parse succeeded"); redis_conn .stream_trim_entries( &TEST_STREAM_NAME.into(), ( redis_interface::StreamCapKind::MinID, redis_interface::StreamCapTrim::Exact, id_to_trim, ), ) .await .change_context(HealthCheckRedisError::StreamTrimFailed)?; logger::debug!("Stream trim succeeded"); Ok(()) } } #[allow(clippy::enum_variant_names)] #[derive(Debug, thiserror::Error)] pub enum HealthCheckDBError { #[error("Error while connecting to database")] DbError, #[error("Error while writing to database")] DbWriteError, #[error("Error while reading element in the database")] DbReadError, #[error("Error while deleting element in the database")] DbDeleteError, #[error("Unpredictable error occurred")] UnknownError, #[error("Error in database transaction")] TransactionError, } impl From<diesel::result::Error> for HealthCheckDBError { fn from(error: diesel::result::Error) -> Self { match error { diesel::result::Error::DatabaseError(_, _) => Self::DbError, diesel::result::Error::RollbackErrorOnCommit { .. } | diesel::result::Error::RollbackTransaction | diesel::result::Error::AlreadyInTransaction | diesel::result::Error::NotInTransaction | diesel::result::Error::BrokenTransactionManager => Self::TransactionError, _ => Self::UnknownError, } } } #[allow(clippy::enum_variant_names)] #[derive(Debug, thiserror::Error)] pub enum HealthCheckRedisError { #[error("Failed to set key value in Redis")] SetFailed, #[error("Failed to get key value in Redis")] GetFailed, #[error("Failed to delete key value in Redis")] DeleteFailed, #[error("Failed to append data to the stream in Redis")] StreamAppendFailed, #[error("Failed to read data from the stream in Redis")] StreamReadFailed, #[error("Failed to trim data from the stream in Redis")] StreamTrimFailed, }
{ "crate": "drainer", "file": "crates/drainer/src/health_check.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_drainer_8293235997084370197
clm
file
// Repository: hyperswitch // Crate: drainer // File: crates/drainer/src/settings.rs // Contains: 10 structs, 0 enums use std::{collections::HashMap, path::PathBuf, sync::Arc}; use common_utils::{ext_traits::ConfigExt, id_type, DbConnectionParams}; use config::{Environment, File}; use external_services::managers::{ encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig, }; use hyperswitch_interfaces::{ encryption_interface::EncryptionManagementInterface, secrets_interface::secret_state::{ RawSecret, SecretState, SecretStateContainer, SecuredSecret, }, }; use masking::Secret; use redis_interface as redis; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use router_env::{env, logger}; use serde::Deserialize; use crate::{errors, secrets_transformers}; #[derive(clap::Parser, Default)] #[cfg_attr(feature = "vergen", command(version = router_env::version!()))] pub struct CmdLineConf { /// Config file. /// Application will look for "config/config.toml" if this option isn't specified. #[arg(short = 'f', long, value_name = "FILE")] pub config_path: Option<PathBuf>, } #[derive(Clone)] pub struct AppState { pub conf: Arc<Settings<RawSecret>>, pub encryption_client: Arc<dyn EncryptionManagementInterface>, } impl AppState { /// # Panics /// /// Panics if secret or encryption management client cannot be initiated pub async fn new(conf: Settings<SecuredSecret>) -> Self { #[allow(clippy::expect_used)] let secret_management_client = conf .secrets_management .get_secret_management_client() .await .expect("Failed to create secret management client"); let raw_conf = secrets_transformers::fetch_raw_secrets(conf, &*secret_management_client).await; #[allow(clippy::expect_used)] let encryption_client = raw_conf .encryption_management .get_encryption_management_client() .await .expect("Failed to create encryption management client"); Self { conf: Arc::new(raw_conf), encryption_client, } } } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Settings<S: SecretState> { pub server: Server, pub master_database: SecretStateContainer<Database, S>, pub redis: redis::RedisSettings, pub log: Log, pub drainer: DrainerSettings, pub encryption_management: EncryptionManagementConfig, pub secrets_management: SecretsManagementConfig, pub multitenancy: Multitenancy, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Database { pub username: String, pub password: Secret<String>, pub host: String, pub port: u16, pub dbname: String, pub pool_size: u32, pub connection_timeout: u64, } impl DbConnectionParams for Database { fn get_username(&self) -> &str { &self.username } fn get_password(&self) -> Secret<String> { self.password.clone() } fn get_host(&self) -> &str { &self.host } fn get_port(&self) -> u16 { self.port } fn get_dbname(&self) -> &str { &self.dbname } } #[derive(Debug, Clone, Deserialize)] #[serde(default)] pub struct DrainerSettings { pub stream_name: String, pub num_partitions: u8, pub max_read_count: u64, pub shutdown_interval: u32, // in milliseconds pub loop_interval: u32, // in milliseconds } #[derive(Debug, Deserialize, Clone, Default)] pub struct Multitenancy { pub enabled: bool, pub tenants: TenantConfig, } impl Multitenancy { pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> { &self.tenants.0 } pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> { self.tenants .0 .values() .map(|tenant| tenant.tenant_id.clone()) .collect() } pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> { self.tenants.0.get(tenant_id) } } #[derive(Debug, Clone, Default)] pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>); impl<'de> Deserialize<'de> for TenantConfig { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] struct Inner { base_url: String, schema: String, accounts_schema: String, redis_key_prefix: String, clickhouse_database: String, } let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?; Ok(Self( hashmap .into_iter() .map(|(key, value)| { ( key.clone(), Tenant { tenant_id: key, base_url: value.base_url, schema: value.schema, accounts_schema: value.accounts_schema, redis_key_prefix: value.redis_key_prefix, clickhouse_database: value.clickhouse_database, }, ) }) .collect(), )) } } #[derive(Debug, Deserialize, Clone)] pub struct Tenant { pub tenant_id: id_type::TenantId, pub base_url: String, pub schema: String, pub accounts_schema: String, pub redis_key_prefix: String, pub clickhouse_database: String, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Server { pub port: u16, pub workers: usize, pub host: String, } impl Server { pub fn validate(&self) -> Result<(), errors::DrainerError> { common_utils::fp_utils::when(self.host.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "server host must not be empty".into(), )) }) } } impl Default for Database { fn default() -> Self { Self { username: String::new(), password: String::new().into(), host: "localhost".into(), port: 5432, dbname: String::new(), pool_size: 5, connection_timeout: 10, } } } impl Default for DrainerSettings { fn default() -> Self { Self { stream_name: "DRAINER_STREAM".into(), num_partitions: 64, max_read_count: 100, shutdown_interval: 1000, // in milliseconds loop_interval: 100, // in milliseconds } } } impl Default for Server { fn default() -> Self { Self { host: "127.0.0.1".to_string(), port: 8080, workers: 1, } } } impl Database { fn validate(&self) -> Result<(), errors::DrainerError> { use common_utils::fp_utils::when; when(self.host.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "database host must not be empty".into(), )) })?; when(self.dbname.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "database name must not be empty".into(), )) })?; when(self.username.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "database user username must not be empty".into(), )) })?; when(self.password.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "database user password must not be empty".into(), )) }) } } impl DrainerSettings { fn validate(&self) -> Result<(), errors::DrainerError> { common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "drainer stream name must not be empty".into(), )) }) } } impl Settings<SecuredSecret> { pub fn new() -> Result<Self, errors::DrainerError> { Self::with_config_path(None) } pub fn with_config_path(config_path: Option<PathBuf>) -> Result<Self, errors::DrainerError> { // 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 `DRAINER` and each level separated by double // underscores. // // Values in config file override the defaults in `Default` trait, and the values set using // environment variables override both the defaults and the config file values. let environment = env::which(); let config_path = router_env::Config::config_path(&environment.to_string(), config_path); let config = router_env::Config::builder(&environment.to_string())? .add_source(File::from(config_path).required(false)) .add_source( Environment::with_prefix("DRAINER") .try_parsing(true) .separator("__") .list_separator(",") .with_list_parse_key("redis.cluster_urls"), ) .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| { logger::error!(%error, "Unable to deserialize application configuration"); eprintln!("Unable to deserialize application configuration: {error}"); errors::DrainerError::from(error.into_inner()) }) } pub fn validate(&self) -> Result<(), errors::DrainerError> { self.server.validate()?; self.master_database.get_inner().validate()?; // The logger may not yet be initialized when validating the application configuration #[allow(clippy::print_stderr)] self.redis.validate().map_err(|error| { eprintln!("{error}"); errors::DrainerError::ConfigParsingError("invalid Redis configuration".into()) })?; self.drainer.validate()?; // The logger may not yet be initialized when validating the application configuration #[allow(clippy::print_stderr)] self.secrets_management.validate().map_err(|error| { eprintln!("{error}"); errors::DrainerError::ConfigParsingError( "invalid secrets management configuration".into(), ) })?; // The logger may not yet be initialized when validating the application configuration #[allow(clippy::print_stderr)] self.encryption_management.validate().map_err(|error| { eprintln!("{error}"); errors::DrainerError::ConfigParsingError( "invalid encryption management configuration".into(), ) })?; Ok(()) } }
{ "crate": "drainer", "file": "crates/drainer/src/settings.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 10, "num_tables": null, "score": null, "total_crates": null }
file_router_derive_-8072241050114342058
clm
file
// Repository: hyperswitch // Crate: router_derive // File: crates/router_derive/src/macros/operation.rs // Contains: 1 structs, 3 enums use std::str::FromStr; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use strum::IntoEnumIterator; use syn::{self, parse::Parse, DeriveInput}; use crate::macros::helpers; #[derive(Debug, Clone, Copy, strum::EnumString, strum::EnumIter, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum Derives { Sync, Cancel, Reject, Capture, ApproveData, Authorize, AuthorizeData, SyncData, CancelData, CancelPostCapture, CancelPostCaptureData, CaptureData, CompleteAuthorizeData, RejectData, SetupMandateData, Start, Verify, Session, SessionData, IncrementalAuthorization, IncrementalAuthorizationData, ExtendAuthorization, ExtendAuthorizationData, SdkSessionUpdate, SdkSessionUpdateData, PostSessionTokens, PostSessionTokensData, UpdateMetadata, UpdateMetadataData, } impl Derives { fn to_operation( self, fns: impl Iterator<Item = TokenStream> + Clone, struct_name: &syn::Ident, ) -> TokenStream { let req_type = Conversion::get_req_type(self); quote! { #[automatically_derived] impl<F:Send+Clone+Sync> Operation<F,#req_type> for #struct_name { type Data = PaymentData<F>; #(#fns)* } } } fn to_ref_operation( self, ref_fns: impl Iterator<Item = TokenStream> + Clone, struct_name: &syn::Ident, ) -> TokenStream { let req_type = Conversion::get_req_type(self); quote! { #[automatically_derived] impl<F:Send+Clone+Sync> Operation<F,#req_type> for &#struct_name { type Data = PaymentData<F>; #(#ref_fns)* } } } } #[derive(Debug, Clone, strum::EnumString, strum::EnumIter, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum Conversion { ValidateRequest, GetTracker, Domain, UpdateTracker, PostUpdateTracker, All, Invalid(String), } impl Conversion { fn get_req_type(ident: Derives) -> syn::Ident { match ident { Derives::Authorize => syn::Ident::new("PaymentsRequest", Span::call_site()), Derives::AuthorizeData => syn::Ident::new("PaymentsAuthorizeData", Span::call_site()), Derives::Sync => syn::Ident::new("PaymentsRetrieveRequest", Span::call_site()), Derives::SyncData => syn::Ident::new("PaymentsSyncData", Span::call_site()), Derives::Cancel => syn::Ident::new("PaymentsCancelRequest", Span::call_site()), Derives::CancelData => syn::Ident::new("PaymentsCancelData", Span::call_site()), Derives::ApproveData => syn::Ident::new("PaymentsApproveData", Span::call_site()), Derives::Reject => syn::Ident::new("PaymentsRejectRequest", Span::call_site()), Derives::RejectData => syn::Ident::new("PaymentsRejectData", Span::call_site()), Derives::Capture => syn::Ident::new("PaymentsCaptureRequest", Span::call_site()), Derives::CaptureData => syn::Ident::new("PaymentsCaptureData", Span::call_site()), Derives::CompleteAuthorizeData => { syn::Ident::new("CompleteAuthorizeData", Span::call_site()) } Derives::Start => syn::Ident::new("PaymentsStartRequest", Span::call_site()), Derives::Verify => syn::Ident::new("VerifyRequest", Span::call_site()), Derives::SetupMandateData => { syn::Ident::new("SetupMandateRequestData", Span::call_site()) } Derives::Session => syn::Ident::new("PaymentsSessionRequest", Span::call_site()), Derives::SessionData => syn::Ident::new("PaymentsSessionData", Span::call_site()), Derives::IncrementalAuthorization => { syn::Ident::new("PaymentsIncrementalAuthorizationRequest", Span::call_site()) } Derives::IncrementalAuthorizationData => { syn::Ident::new("PaymentsIncrementalAuthorizationData", Span::call_site()) } Derives::SdkSessionUpdate => { syn::Ident::new("PaymentsDynamicTaxCalculationRequest", Span::call_site()) } Derives::SdkSessionUpdateData => { syn::Ident::new("SdkPaymentsSessionUpdateData", Span::call_site()) } Derives::PostSessionTokens => { syn::Ident::new("PaymentsPostSessionTokensRequest", Span::call_site()) } Derives::PostSessionTokensData => { syn::Ident::new("PaymentsPostSessionTokensData", Span::call_site()) } Derives::UpdateMetadata => { syn::Ident::new("PaymentsUpdateMetadataRequest", Span::call_site()) } Derives::UpdateMetadataData => { syn::Ident::new("PaymentsUpdateMetadataData", Span::call_site()) } Derives::CancelPostCapture => { syn::Ident::new("PaymentsCancelPostCaptureRequest", Span::call_site()) } Derives::CancelPostCaptureData => { syn::Ident::new("PaymentsCancelPostCaptureData", Span::call_site()) } Derives::ExtendAuthorization => { syn::Ident::new("PaymentsExtendAuthorizationRequest", Span::call_site()) } Derives::ExtendAuthorizationData => { syn::Ident::new("PaymentsExtendAuthorizationData", Span::call_site()) } } } fn to_function(&self, ident: Derives) -> TokenStream { let req_type = Self::get_req_type(ident); match self { Self::ValidateRequest => quote! { fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type, Self::Data> + Send + Sync)> { Ok(self) } }, Self::GetTracker => quote! { fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(self) } }, Self::Domain => quote! { fn to_domain(&self) -> RouterResult<&dyn Domain<F,#req_type, Self::Data>> { Ok(self) } }, Self::UpdateTracker => quote! { fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(self) } }, Self::PostUpdateTracker => quote! { fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(self) } }, Self::Invalid(s) => { helpers::syn_error(Span::call_site(), &format!("Invalid identifier {s}")) .to_compile_error() } Self::All => { let validate_request = Self::ValidateRequest.to_function(ident); let get_tracker = Self::GetTracker.to_function(ident); let domain = Self::Domain.to_function(ident); let update_tracker = Self::UpdateTracker.to_function(ident); quote! { #validate_request #get_tracker #domain #update_tracker } } } } fn to_ref_function(&self, ident: Derives) -> TokenStream { let req_type = Self::get_req_type(ident); match self { Self::ValidateRequest => quote! { fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F, #req_type, Self::Data> + Send + Sync)> { Ok(*self) } }, Self::GetTracker => quote! { fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data,#req_type> + Send + Sync)> { Ok(*self) } }, Self::Domain => quote! { fn to_domain(&self) -> RouterResult<&(dyn Domain<F,#req_type, Self::Data>)> { Ok(*self) } }, Self::UpdateTracker => quote! { fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F, Self::Data,#req_type> + Send + Sync)> { Ok(*self) } }, Self::PostUpdateTracker => quote! { fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(*self) } }, Self::Invalid(s) => { helpers::syn_error(Span::call_site(), &format!("Invalid identifier {s}")) .to_compile_error() } Self::All => { let validate_request = Self::ValidateRequest.to_ref_function(ident); let get_tracker = Self::GetTracker.to_ref_function(ident); let domain = Self::Domain.to_ref_function(ident); let update_tracker = Self::UpdateTracker.to_ref_function(ident); quote! { #validate_request #get_tracker #domain #update_tracker } } } } } mod operations_keyword { use syn::custom_keyword; custom_keyword!(operations); custom_keyword!(flow); } #[derive(Debug)] pub enum OperationsEnumMeta { Operations { keyword: operations_keyword::operations, value: Vec<Conversion>, }, Flow { keyword: operations_keyword::flow, value: Vec<Derives>, }, } #[derive(Clone)] pub struct OperationProperties { operations: Vec<Conversion>, flows: Vec<Derives>, } fn get_operation_properties( operation_enums: Vec<OperationsEnumMeta>, ) -> syn::Result<OperationProperties> { let mut operations = vec![]; let mut flows = vec![]; for operation in operation_enums { match operation { OperationsEnumMeta::Operations { value, .. } => { operations = value; } OperationsEnumMeta::Flow { value, .. } => { flows = value; } } } if operations.is_empty() { Err(syn::Error::new( Span::call_site(), "atleast one operation must be specitied", ))?; } if flows.is_empty() { Err(syn::Error::new( Span::call_site(), "atleast one flow must be specitied", ))?; } Ok(OperationProperties { operations, flows }) } impl Parse for Derives { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let text = input.parse::<syn::LitStr>()?; let value = text.value(); value.as_str().parse().map_err(|_| { syn::Error::new_spanned( &text, format!( "Unexpected value for flow: `{value}`. Possible values are `{}`", helpers::get_possible_values_for_enum::<Self>() ), ) }) } } impl Parse for Conversion { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let text = input.parse::<syn::LitStr>()?; let value = text.value(); value.as_str().parse().map_err(|_| { syn::Error::new_spanned( &text, format!( "Unexpected value for operation: `{value}`. Possible values are `{}`", helpers::get_possible_values_for_enum::<Self>() ), ) }) } } fn parse_list_string<T>(list_string: String, keyword: &str) -> syn::Result<Vec<T>> where T: FromStr + IntoEnumIterator + ToString, { list_string .split(',') .map(str::trim) .map(T::from_str) .map(|result| { result.map_err(|_| { syn::Error::new( Span::call_site(), format!( "Unexpected {keyword}, possible values are {}", helpers::get_possible_values_for_enum::<T>() ), ) }) }) .collect() } fn get_conversions(input: syn::parse::ParseStream<'_>) -> syn::Result<Vec<Conversion>> { let lit_str_list = input.parse::<syn::LitStr>()?; parse_list_string(lit_str_list.value(), "operation") } fn get_derives(input: syn::parse::ParseStream<'_>) -> syn::Result<Vec<Derives>> { let lit_str_list = input.parse::<syn::LitStr>()?; parse_list_string(lit_str_list.value(), "flow") } impl Parse for OperationsEnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(operations_keyword::operations) { let keyword = input.parse()?; input.parse::<syn::Token![=]>()?; let value = get_conversions(input)?; Ok(Self::Operations { keyword, value }) } else if lookahead.peek(operations_keyword::flow) { let keyword = input.parse()?; input.parse::<syn::Token![=]>()?; let value = get_derives(input)?; Ok(Self::Flow { keyword, value }) } else { Err(lookahead.error()) } } } trait OperationsDeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<OperationsEnumMeta>>; } impl OperationsDeriveInputExt for DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<OperationsEnumMeta>> { helpers::get_metadata_inner("operation", &self.attrs) } } impl ToTokens for OperationsEnumMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::Operations { keyword, .. } => keyword.to_tokens(tokens), Self::Flow { keyword, .. } => keyword.to_tokens(tokens), } } } pub fn operation_derive_inner(input: DeriveInput) -> syn::Result<proc_macro::TokenStream> { let struct_name = &input.ident; let operations_meta = input.get_metadata()?; let operation_properties = get_operation_properties(operations_meta)?; let current_crate = syn::Ident::new("crate", Span::call_site()); let trait_derive = operation_properties .clone() .flows .into_iter() .map(|derive| { let fns = operation_properties .operations .iter() .map(|conversion| conversion.to_function(derive)); derive.to_operation(fns, struct_name) }) .collect::<Vec<_>>(); let ref_trait_derive = operation_properties .flows .into_iter() .map(|derive| { let fns = operation_properties .operations .iter() .map(|conversion| conversion.to_ref_function(derive)); derive.to_ref_operation(fns, struct_name) }) .collect::<Vec<_>>(); let trait_derive = quote! { #(#ref_trait_derive)* #(#trait_derive)* }; let output = quote! { const _: () = { use #current_crate::core::errors::RouterResult; use #current_crate::core::payments::{PaymentData,operations::{ ValidateRequest, PostUpdateTracker, GetTracker, UpdateTracker, }}; use #current_crate::types::{ SetupMandateRequestData, PaymentsSyncData, PaymentsCaptureData, PaymentsCancelData, PaymentsApproveData, PaymentsRejectData, PaymentsAuthorizeData, PaymentsSessionData, CompleteAuthorizeData, PaymentsIncrementalAuthorizationData, SdkPaymentsSessionUpdateData, PaymentsPostSessionTokensData, PaymentsUpdateMetadataData, PaymentsCancelPostCaptureData, PaymentsExtendAuthorizationData, api::{ PaymentsCaptureRequest, PaymentsCancelRequest, PaymentsApproveRequest, PaymentsRejectRequest, PaymentsRetrieveRequest, PaymentsRequest, PaymentsStartRequest, PaymentsSessionRequest, VerifyRequest, PaymentsDynamicTaxCalculationRequest, PaymentsIncrementalAuthorizationRequest, PaymentsPostSessionTokensRequest, PaymentsUpdateMetadataRequest, PaymentsCancelPostCaptureRequest, PaymentsExtendAuthorizationRequest, } }; #trait_derive }; }; Ok(proc_macro::TokenStream::from(output)) }
{ "crate": "router_derive", "file": "crates/router_derive/src/macros/operation.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_derive_8999687691063768587
clm
file
// Repository: hyperswitch // Crate: router_derive // File: crates/router_derive/src/macros/try_get_enum.rs // Contains: 1 structs, 0 enums use proc_macro2::Span; use quote::ToTokens; use syn::{parse::Parse, punctuated::Punctuated}; mod try_get_keyword { use syn::custom_keyword; custom_keyword!(error_type); } #[derive(Debug)] pub struct TryGetEnumMeta { error_type: syn::Ident, variant: syn::Ident, } impl Parse for TryGetEnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let error_type = input.parse()?; _ = input.parse::<syn::Token![::]>()?; let variant = input.parse()?; Ok(Self { error_type, variant, }) } } trait TryGetDeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<TryGetEnumMeta>>; } impl TryGetDeriveInputExt for syn::DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<TryGetEnumMeta>> { super::helpers::get_metadata_inner("error", &self.attrs) } } impl ToTokens for TryGetEnumMeta { fn to_tokens(&self, _: &mut proc_macro2::TokenStream) {} } /// Try and get the variants for an enum pub fn try_get_enum_variant( input: syn::DeriveInput, ) -> Result<proc_macro2::TokenStream, syn::Error> { let name = &input.ident; let parsed_error_type = input.get_metadata()?; let (error_type, error_variant) = parsed_error_type .first() .ok_or(syn::Error::new( Span::call_site(), "One error should be specified", )) .map(|error_struct| (&error_struct.error_type, &error_struct.variant))?; let (impl_generics, generics, where_clause) = input.generics.split_for_impl(); let variants = get_enum_variants(&input.data)?; let try_into_fns = variants.iter().map(|variant| { let variant_name = &variant.ident; let variant_field = get_enum_variant_field(variant)?; let variant_types = variant_field.iter().map(|f|f.ty.clone()); let try_into_fn = syn::Ident::new( &format!("try_into_{}", variant_name.to_string().to_lowercase()), Span::call_site(), ); Ok(quote::quote! { pub fn #try_into_fn(self)->Result<(#(#variant_types),*),error_stack::Report<#error_type>> { match self { Self::#variant_name(inner) => Ok(inner), _=> Err(error_stack::report!(#error_type::#error_variant)), } } }) }).collect::<Result<Vec<proc_macro2::TokenStream>,syn::Error>>()?; let expanded = quote::quote! { impl #impl_generics #name #generics #where_clause { #(#try_into_fns)* } }; Ok(expanded) } /// Get variants from Enum fn get_enum_variants(data: &syn::Data) -> syn::Result<Punctuated<syn::Variant, syn::token::Comma>> { if let syn::Data::Enum(syn::DataEnum { variants, .. }) = data { Ok(variants.clone()) } else { Err(super::helpers::non_enum_error()) } } /// Get Field from an enum variant fn get_enum_variant_field( variant: &syn::Variant, ) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> { let field = match variant.fields.clone() { syn::Fields::Unnamed(un) => un.unnamed, syn::Fields::Named(n) => n.named, syn::Fields::Unit => { return Err(super::helpers::syn_error( Span::call_site(), "The enum is a unit variant it's not supported", )) } }; Ok(field) }
{ "crate": "router_derive", "file": "crates/router_derive/src/macros/try_get_enum.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_derive_6196711816154371421
clm
file
// Repository: hyperswitch // Crate: router_derive // File: crates/router_derive/src/macros/generate_schema.rs // Contains: 1 structs, 0 enums use std::collections::{HashMap, HashSet}; use indexmap::IndexMap; use syn::{self, parse::Parse, parse_quote, punctuated::Punctuated, Token}; use crate::macros::helpers; /// Parse schemas from attribute /// Example /// /// #[mandatory_in(PaymentsCreateRequest, PaymentsUpdateRequest)] /// would return /// /// [PaymentsCreateRequest, PaymentsUpdateRequest] fn get_inner_path_ident(attribute: &syn::Attribute) -> syn::Result<Vec<syn::Ident>> { Ok(attribute .parse_args_with(Punctuated::<syn::Ident, Token![,]>::parse_terminated)? .into_iter() .collect::<Vec<_>>()) } #[allow(dead_code)] /// Get the type of field fn get_field_type(field_type: syn::Type) -> syn::Result<syn::Ident> { if let syn::Type::Path(path) = field_type { path.path .segments .last() .map(|last_path_segment| last_path_segment.ident.to_owned()) .ok_or(syn::Error::new( proc_macro2::Span::call_site(), "Atleast one ident must be specified", )) } else { Err(syn::Error::new( proc_macro2::Span::call_site(), "Only path fields are supported", )) } } #[allow(dead_code)] /// Get the inner type of option fn get_inner_option_type(field: &syn::Type) -> syn::Result<syn::Ident> { if let syn::Type::Path(ref path) = &field { if let Some(segment) = path.path.segments.last() { if let syn::PathArguments::AngleBracketed(ref args) = &segment.arguments { if let Some(syn::GenericArgument::Type(ty)) = args.args.first() { return get_field_type(ty.clone()); } } } } Err(syn::Error::new( proc_macro2::Span::call_site(), "Only path fields are supported", )) } mod schema_keyword { use syn::custom_keyword; custom_keyword!(schema); } #[derive(Debug, Clone)] pub struct SchemaMeta { struct_name: syn::Ident, type_ident: syn::Ident, } /// parse #[mandatory_in(PaymentsCreateRequest = u64)] impl Parse for SchemaMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let struct_name = input.parse::<syn::Ident>()?; input.parse::<syn::Token![=]>()?; let type_ident = input.parse::<syn::Ident>()?; Ok(Self { struct_name, type_ident, }) } } impl quote::ToTokens for SchemaMeta { fn to_tokens(&self, _: &mut proc_macro2::TokenStream) {} } pub fn polymorphic_macro_derive_inner( input: syn::DeriveInput, ) -> syn::Result<proc_macro2::TokenStream> { let schemas_to_create = helpers::get_metadata_inner::<syn::Ident>("generate_schemas", &input.attrs)?; let fields = helpers::get_struct_fields(input.data) .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?; // Go through all the fields and create a mapping of required fields for a schema // PaymentsCreate -> ["amount","currency"] // This will be stored in the hashmap with key as // required_fields -> ((amount, PaymentsCreate), (currency, PaymentsCreate)) // and values as the type // // (amount, PaymentsCreate) -> Amount let mut required_fields = HashMap::<(syn::Ident, syn::Ident), syn::Ident>::new(); // These fields will be removed in the schema // PaymentsUpdate -> ["client_secret"] // This will be stored in a hashset // hide_fields -> ((client_secret, PaymentsUpdate)) let mut hide_fields = HashSet::<(syn::Ident, syn::Ident)>::new(); let mut all_fields = IndexMap::<syn::Field, Vec<syn::Attribute>>::new(); for field in fields { // Partition the attributes of a field into two vectors // One with #[mandatory_in] attributes present // Rest of the attributes ( include only the schema attribute, serde is not required) let (mandatory_attribute, other_attributes) = field .attrs .iter() .partition::<Vec<_>, _>(|attribute| attribute.path().is_ident("mandatory_in")); let hidden_fields = field .attrs .iter() .filter(|attribute| attribute.path().is_ident("remove_in")) .collect::<Vec<_>>(); // Other attributes ( schema ) are to be printed as is other_attributes .iter() .filter(|attribute| { attribute.path().is_ident("schema") || attribute.path().is_ident("doc") }) .for_each(|attribute| { // Since attributes will be modified, the field should not contain any attributes // So create a field, with previous attributes removed let mut field_without_attributes = field.clone(); field_without_attributes.attrs.clear(); all_fields .entry(field_without_attributes.to_owned()) .or_default() .push(attribute.to_owned().to_owned()); }); // Mandatory attributes are to be inserted into hashset // The hashset will store it in this format // ("amount", PaymentsCreateRequest) // ("currency", PaymentsConfirmRequest) // // For these attributes, we need to later add #[schema(required = true)] attribute let field_ident = field.ident.ok_or(syn::Error::new( proc_macro2::Span::call_site(), "Cannot use `mandatory_in` on unnamed fields", ))?; // Parse the #[mandatory_in(PaymentsCreateRequest = u64)] and insert into hashmap // key -> ("amount", PaymentsCreateRequest) // value -> u64 if let Some(mandatory_in_attribute) = helpers::get_metadata_inner::<SchemaMeta>("mandatory_in", mandatory_attribute)?.first() { let key = ( field_ident.clone(), mandatory_in_attribute.struct_name.clone(), ); let value = mandatory_in_attribute.type_ident.clone(); required_fields.insert(key, value); } // Hidden fields are to be inserted in the Hashset // The hashset will store it in this format // ("client_secret", PaymentsUpdate) // // These fields will not be added to the struct _ = hidden_fields .iter() // Filter only #[mandatory_in] attributes .map(|&attribute| get_inner_path_ident(attribute)) .try_for_each(|schemas| { let res = schemas .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))? .iter() .map(|schema| (field_ident.clone(), schema.to_owned())) .collect::<HashSet<_>>(); hide_fields.extend(res); Ok::<_, syn::Error>(()) }); } // iterate over the schemas and build them with their fields let schemas = schemas_to_create .iter() .map(|schema| { let fields = all_fields .iter() .filter_map(|(field, attributes)| { let mut final_attributes = attributes.clone(); if let Some(field_ident) = field.ident.to_owned() { // If the field is required for this schema, then add // #[schema(value_type = type)] for this field if let Some(required_field_type) = required_fields.get(&(field_ident.clone(), schema.to_owned())) { // This is a required field in the Schema // Add the value type and remove original value type ( if present ) let attribute_without_schema_type = attributes .iter() .filter(|attribute| !attribute.path().is_ident("schema")) .map(Clone::clone) .collect::<Vec<_>>(); final_attributes = attribute_without_schema_type; let value_type_attribute: syn::Attribute = parse_quote!(#[schema(value_type = #required_field_type)]); final_attributes.push(value_type_attribute); } } // If the field is to be not shown then let is_hidden_field = field .ident .clone() .map(|field_ident| hide_fields.contains(&(field_ident, schema.to_owned()))) .unwrap_or(false); if is_hidden_field { None } else { Some(quote::quote! { #(#final_attributes)* #field, }) } }) .collect::<Vec<_>>(); quote::quote! { #[derive(utoipa::ToSchema)] pub struct #schema { #(#fields)* } } }) .collect::<Vec<_>>(); Ok(quote::quote! { #(#schemas)* }) }
{ "crate": "router_derive", "file": "crates/router_derive/src/macros/generate_schema.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_router_derive_4405642777013022869
clm
file
// Repository: hyperswitch // Crate: router_derive // File: crates/router_derive/src/macros/api_error/helpers.rs // Contains: 2 structs, 0 enums use proc_macro2::TokenStream; use quote::ToTokens; use syn::{ parse::Parse, spanned::Spanned, DeriveInput, Field, Fields, LitStr, Token, TypePath, Variant, }; use crate::macros::helpers::{get_metadata_inner, occurrence_error}; mod keyword { use syn::custom_keyword; // Enum metadata custom_keyword!(error_type_enum); // Variant metadata custom_keyword!(error_type); custom_keyword!(code); custom_keyword!(message); custom_keyword!(ignore); } enum EnumMeta { ErrorTypeEnum { keyword: keyword::error_type_enum, value: TypePath, }, } impl Parse for EnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(keyword::error_type_enum) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::ErrorTypeEnum { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for EnumMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::ErrorTypeEnum { keyword, .. } => keyword.to_tokens(tokens), } } } trait DeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<EnumMeta>>; } impl DeriveInputExt for DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<EnumMeta>> { get_metadata_inner("error", &self.attrs) } } pub(super) trait HasErrorTypeProperties { fn get_type_properties(&self) -> syn::Result<ErrorTypeProperties>; } #[derive(Clone, Debug, Default)] pub(super) struct ErrorTypeProperties { pub error_type_enum: Option<TypePath>, } impl HasErrorTypeProperties for DeriveInput { fn get_type_properties(&self) -> syn::Result<ErrorTypeProperties> { let mut output = ErrorTypeProperties::default(); let mut error_type_enum_keyword = None; for meta in self.get_metadata()? { match meta { EnumMeta::ErrorTypeEnum { keyword, value } => { if let Some(first_keyword) = error_type_enum_keyword { return Err(occurrence_error(first_keyword, keyword, "error_type_enum")); } error_type_enum_keyword = Some(keyword); output.error_type_enum = Some(value); } } } if output.error_type_enum.is_none() { return Err(syn::Error::new( self.span(), "error(error_type_enum) attribute not found", )); } Ok(output) } } enum VariantMeta { ErrorType { keyword: keyword::error_type, value: TypePath, }, Code { keyword: keyword::code, value: LitStr, }, Message { keyword: keyword::message, value: LitStr, }, Ignore { keyword: keyword::ignore, value: LitStr, }, } impl Parse for VariantMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(keyword::error_type) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::ErrorType { keyword, value }) } else if lookahead.peek(keyword::code) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Code { keyword, value }) } else if lookahead.peek(keyword::message) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Message { keyword, value }) } else if lookahead.peek(keyword::ignore) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Ignore { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for VariantMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::ErrorType { keyword, .. } => keyword.to_tokens(tokens), Self::Code { keyword, .. } => keyword.to_tokens(tokens), Self::Message { keyword, .. } => keyword.to_tokens(tokens), Self::Ignore { keyword, .. } => keyword.to_tokens(tokens), } } } trait VariantExt { /// Get all the error metadata associated with an enum variant. fn get_metadata(&self) -> syn::Result<Vec<VariantMeta>>; } impl VariantExt for Variant { fn get_metadata(&self) -> syn::Result<Vec<VariantMeta>> { get_metadata_inner("error", &self.attrs) } } pub(super) trait HasErrorVariantProperties { fn get_variant_properties(&self) -> syn::Result<ErrorVariantProperties>; } #[derive(Clone, Debug, Default, Eq, PartialEq)] pub(super) struct ErrorVariantProperties { pub error_type: Option<TypePath>, pub code: Option<LitStr>, pub message: Option<LitStr>, pub ignore: std::collections::HashSet<String>, } impl HasErrorVariantProperties for Variant { fn get_variant_properties(&self) -> syn::Result<ErrorVariantProperties> { let mut output = ErrorVariantProperties::default(); let mut error_type_keyword = None; let mut code_keyword = None; let mut message_keyword = None; let mut ignore_keyword = None; for meta in self.get_metadata()? { match meta { VariantMeta::ErrorType { keyword, value } => { if let Some(first_keyword) = error_type_keyword { return Err(occurrence_error(first_keyword, keyword, "error_type")); } error_type_keyword = Some(keyword); output.error_type = Some(value); } VariantMeta::Code { keyword, value } => { if let Some(first_keyword) = code_keyword { return Err(occurrence_error(first_keyword, keyword, "code")); } code_keyword = Some(keyword); output.code = Some(value); } VariantMeta::Message { keyword, value } => { if let Some(first_keyword) = message_keyword { return Err(occurrence_error(first_keyword, keyword, "message")); } message_keyword = Some(keyword); output.message = Some(value); } VariantMeta::Ignore { keyword, value } => { if let Some(first_keyword) = ignore_keyword { return Err(occurrence_error(first_keyword, keyword, "ignore")); } ignore_keyword = Some(keyword); output.ignore = value .value() .replace(' ', "") .split(',') .map(ToString::to_string) .collect(); } } } Ok(output) } } fn missing_attribute_error(variant: &Variant, attr: &str) -> syn::Error { syn::Error::new_spanned(variant, format!("{attr} must be specified")) } pub(super) fn check_missing_attributes( variant: &Variant, variant_properties: &ErrorVariantProperties, ) -> syn::Result<()> { if variant_properties.error_type.is_none() { return Err(missing_attribute_error(variant, "error_type")); } if variant_properties.code.is_none() { return Err(missing_attribute_error(variant, "code")); } if variant_properties.message.is_none() { return Err(missing_attribute_error(variant, "message")); } Ok(()) } /// Get all the fields not used in the error message. pub(super) fn get_unused_fields( fields: &Fields, message: &str, ignore: &std::collections::HashSet<String>, ) -> Vec<Field> { let fields = match fields { Fields::Unit => Vec::new(), Fields::Unnamed(_) => Vec::new(), Fields::Named(fields) => fields.named.iter().cloned().collect(), }; fields .iter() .filter(|&field| { // Safety: Named fields are guaranteed to have an identifier. #[allow(clippy::unwrap_used)] let field_name = format!("{}", field.ident.as_ref().unwrap()); !message.contains(&field_name) && !ignore.contains(&field_name) }) .cloned() .collect() }
{ "crate": "router_derive", "file": "crates/router_derive/src/macros/api_error/helpers.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_router_derive_3183000914407538237
clm
file
// Repository: hyperswitch // Crate: router_derive // File: crates/router_derive/src/macros/schema/helpers.rs // Contains: 1 structs, 1 enums use proc_macro2::TokenStream; use quote::ToTokens; use syn::{parse::Parse, Field, LitInt, LitStr, Token, TypePath}; use crate::macros::helpers::{get_metadata_inner, occurrence_error}; mod keyword { use syn::custom_keyword; // Schema metadata custom_keyword!(value_type); custom_keyword!(min_length); custom_keyword!(max_length); custom_keyword!(example); } pub enum SchemaParameterVariant { ValueType { keyword: keyword::value_type, value: TypePath, }, MinLength { keyword: keyword::min_length, value: LitInt, }, MaxLength { keyword: keyword::max_length, value: LitInt, }, Example { keyword: keyword::example, value: LitStr, }, } impl Parse for SchemaParameterVariant { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(keyword::value_type) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::ValueType { keyword, value }) } else if lookahead.peek(keyword::min_length) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::MinLength { keyword, value }) } else if lookahead.peek(keyword::max_length) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::MaxLength { keyword, value }) } else if lookahead.peek(keyword::example) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::Example { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for SchemaParameterVariant { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::ValueType { keyword, .. } => keyword.to_tokens(tokens), Self::MinLength { keyword, .. } => keyword.to_tokens(tokens), Self::MaxLength { keyword, .. } => keyword.to_tokens(tokens), Self::Example { keyword, .. } => keyword.to_tokens(tokens), } } } pub trait FieldExt { /// Get all the schema metadata associated with a field. fn get_schema_metadata(&self) -> syn::Result<Vec<SchemaParameterVariant>>; } impl FieldExt for Field { fn get_schema_metadata(&self) -> syn::Result<Vec<SchemaParameterVariant>> { get_metadata_inner("schema", &self.attrs) } } #[derive(Clone, Debug, Default)] pub struct SchemaParameters { pub value_type: Option<TypePath>, pub min_length: Option<usize>, pub max_length: Option<usize>, pub example: Option<String>, } pub trait HasSchemaParameters { fn get_schema_parameters(&self) -> syn::Result<SchemaParameters>; } impl HasSchemaParameters for Field { fn get_schema_parameters(&self) -> syn::Result<SchemaParameters> { let mut output = SchemaParameters::default(); let mut value_type_keyword = None; let mut min_length_keyword = None; let mut max_length_keyword = None; let mut example_keyword = None; for meta in self.get_schema_metadata()? { match meta { SchemaParameterVariant::ValueType { keyword, value } => { if let Some(first_keyword) = value_type_keyword { return Err(occurrence_error(first_keyword, keyword, "value_type")); } value_type_keyword = Some(keyword); output.value_type = Some(value); } SchemaParameterVariant::MinLength { keyword, value } => { if let Some(first_keyword) = min_length_keyword { return Err(occurrence_error(first_keyword, keyword, "min_length")); } min_length_keyword = Some(keyword); let min_length = value.base10_parse::<usize>()?; output.min_length = Some(min_length); } SchemaParameterVariant::MaxLength { keyword, value } => { if let Some(first_keyword) = max_length_keyword { return Err(occurrence_error(first_keyword, keyword, "max_length")); } max_length_keyword = Some(keyword); let max_length = value.base10_parse::<usize>()?; output.max_length = Some(max_length); } SchemaParameterVariant::Example { keyword, value } => { if let Some(first_keyword) = example_keyword { return Err(occurrence_error(first_keyword, keyword, "example")); } example_keyword = Some(keyword); output.example = Some(value.value()); } } } Ok(output) } } /// Check if the field is applicable for running validations #[derive(PartialEq)] pub enum IsSchemaFieldApplicableForValidation { /// Not applicable for running validation checks Invalid, /// Applicable for running validation checks Valid, /// Applicable for validation but field is optional - this is needed for generating validation code only if the value of the field is present ValidOptional, } /// From implementation for checking if the field type is applicable for running schema validations impl From<&syn::Type> for IsSchemaFieldApplicableForValidation { fn from(ty: &syn::Type) -> Self { if let syn::Type::Path(type_path) = ty { if let Some(segment) = type_path.path.segments.last() { let ident = &segment.ident; if ident == "String" || ident == "Url" { return Self::Valid; } if ident == "Option" { if let syn::PathArguments::AngleBracketed(generic_args) = &segment.arguments { if let Some(syn::GenericArgument::Type(syn::Type::Path(inner_path))) = generic_args.args.first() { if let Some(inner_segment) = inner_path.path.segments.last() { if inner_segment.ident == "String" || inner_segment.ident == "Url" { return Self::ValidOptional; } } } } } } } Self::Invalid } }
{ "crate": "router_derive", "file": "crates/router_derive/src/macros/schema/helpers.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_subscriptions_-8805393128983549759
clm
file
// Repository: hyperswitch // Crate: subscriptions // File: crates/subscriptions/src/state.rs // Contains: 1 structs, 0 enums use common_utils::types::keymanager; use hyperswitch_domain_models::{ business_profile, configs as domain_configs, customer, invoice as invoice_domain, master_key, merchant_account, merchant_connector_account, merchant_key_store, subscription as subscription_domain, }; use hyperswitch_interfaces::configs; use router_env::tracing_actix_web::RequestId; use storage_impl::{errors, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore}; #[async_trait::async_trait] pub trait SubscriptionStorageInterface: Send + Sync + dyn_clone::DynClone + master_key::MasterKeyInterface + scheduler::SchedulerInterface + subscription_domain::SubscriptionInterface<Error = errors::StorageError> + invoice_domain::InvoiceInterface<Error = errors::StorageError> + business_profile::ProfileInterface<Error = errors::StorageError> + domain_configs::ConfigInterface<Error = errors::StorageError> + customer::CustomerInterface<Error = errors::StorageError> + merchant_account::MerchantAccountInterface<Error = errors::StorageError> + merchant_key_store::MerchantKeyStoreInterface<Error = errors::StorageError> + merchant_connector_account::MerchantConnectorAccountInterface<Error = errors::StorageError> + 'static { } dyn_clone::clone_trait_object!(SubscriptionStorageInterface); #[async_trait::async_trait] impl SubscriptionStorageInterface for MockDb {} #[async_trait::async_trait] impl<T: DatabaseStore + 'static> SubscriptionStorageInterface for RouterStore<T> where Self: scheduler::SchedulerInterface + master_key::MasterKeyInterface { } #[async_trait::async_trait] impl<T: DatabaseStore + 'static> SubscriptionStorageInterface for KVRouterStore<T> where Self: scheduler::SchedulerInterface + master_key::MasterKeyInterface { } pub struct SubscriptionState { pub store: Box<dyn SubscriptionStorageInterface>, pub key_store: Option<merchant_key_store::MerchantKeyStore>, pub key_manager_state: keymanager::KeyManagerState, pub api_client: Box<dyn hyperswitch_interfaces::api_client::ApiClient>, pub conf: SubscriptionConfig, pub tenant: configs::Tenant, pub event_handler: Box<dyn hyperswitch_interfaces::events::EventHandlerInterface>, pub connector_converter: Box<dyn hyperswitch_interfaces::api_client::ConnectorConverter>, } #[derive(Clone)] pub struct SubscriptionConfig { pub proxy: hyperswitch_interfaces::types::Proxy, pub internal_merchant_id_profile_id_auth: configs::InternalMerchantIdProfileIdAuthSettings, pub internal_services: configs::InternalServicesConfig, pub connectors: configs::Connectors, } impl From<&SubscriptionState> for keymanager::KeyManagerState { fn from(state: &SubscriptionState) -> Self { state.key_manager_state.clone() } } impl hyperswitch_interfaces::api_client::ApiClientWrapper for SubscriptionState { fn get_proxy(&self) -> hyperswitch_interfaces::types::Proxy { self.conf.proxy.clone() } fn get_api_client(&self) -> &dyn hyperswitch_interfaces::api_client::ApiClient { self.api_client.as_ref() } fn get_request_id(&self) -> Option<RequestId> { self.api_client.get_request_id() } fn get_request_id_str(&self) -> Option<String> { self.api_client .get_request_id() .map(|req_id| req_id.as_hyphenated().to_string()) } fn get_tenant(&self) -> configs::Tenant { self.tenant.clone() } fn get_connectors(&self) -> configs::Connectors { self.conf.connectors.clone() } fn event_handler(&self) -> &dyn hyperswitch_interfaces::events::EventHandlerInterface { self.event_handler.as_ref() } }
{ "crate": "subscriptions", "file": "crates/subscriptions/src/state.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_subscriptions_4455174963177153005
clm
file
// Repository: hyperswitch // Crate: subscriptions // File: crates/subscriptions/src/types/storage/invoice_sync.rs // Contains: 2 structs, 1 enums use api_models::enums as api_enums; use common_utils::id_type; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct InvoiceSyncTrackingData { pub subscription_id: id_type::SubscriptionId, pub invoice_id: id_type::InvoiceId, pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub customer_id: id_type::CustomerId, // connector_invoice_id is optional because in some cases (Trial/Future), the invoice might not have been created in the connector yet. pub connector_invoice_id: Option<id_type::InvoiceId>, pub connector_name: api_enums::Connector, // The connector to which the invoice belongs } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct InvoiceSyncRequest { pub subscription_id: id_type::SubscriptionId, pub invoice_id: id_type::InvoiceId, pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub customer_id: id_type::CustomerId, pub connector_invoice_id: Option<id_type::InvoiceId>, pub connector_name: api_enums::Connector, } impl From<InvoiceSyncRequest> for InvoiceSyncTrackingData { fn from(item: InvoiceSyncRequest) -> Self { Self { subscription_id: item.subscription_id, invoice_id: item.invoice_id, merchant_id: item.merchant_id, profile_id: item.profile_id, customer_id: item.customer_id, connector_invoice_id: item.connector_invoice_id, connector_name: item.connector_name, } } } impl InvoiceSyncRequest { #[allow(clippy::too_many_arguments)] pub fn new( subscription_id: id_type::SubscriptionId, invoice_id: id_type::InvoiceId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, customer_id: id_type::CustomerId, connector_invoice_id: Option<id_type::InvoiceId>, connector_name: api_enums::Connector, ) -> Self { Self { subscription_id, invoice_id, merchant_id, profile_id, customer_id, connector_invoice_id, connector_name, } } } impl InvoiceSyncTrackingData { #[allow(clippy::too_many_arguments)] pub fn new( subscription_id: id_type::SubscriptionId, invoice_id: id_type::InvoiceId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, customer_id: id_type::CustomerId, connector_invoice_id: Option<id_type::InvoiceId>, connector_name: api_enums::Connector, ) -> Self { Self { subscription_id, invoice_id, merchant_id, profile_id, customer_id, connector_invoice_id, connector_name, } } } #[derive(Debug, Clone)] pub enum InvoiceSyncPaymentStatus { PaymentSucceeded, PaymentProcessing, PaymentFailed, } impl From<common_enums::IntentStatus> for InvoiceSyncPaymentStatus { fn from(value: common_enums::IntentStatus) -> Self { match value { common_enums::IntentStatus::Succeeded => Self::PaymentSucceeded, common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresPaymentMethod => Self::PaymentProcessing, _ => Self::PaymentFailed, } } } impl From<InvoiceSyncPaymentStatus> for common_enums::connector_enums::InvoiceStatus { fn from(value: InvoiceSyncPaymentStatus) -> Self { match value { InvoiceSyncPaymentStatus::PaymentSucceeded => Self::InvoicePaid, InvoiceSyncPaymentStatus::PaymentProcessing => Self::PaymentPending, InvoiceSyncPaymentStatus::PaymentFailed => Self::PaymentFailed, } } }
{ "crate": "subscriptions", "file": "crates/subscriptions/src/types/storage/invoice_sync.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_subscriptions_-7598076780018828417
clm
file
// Repository: hyperswitch // Crate: subscriptions // File: crates/subscriptions/src/core/payments_api_client.rs // Contains: 2 structs, 0 enums use api_models::subscription as subscription_types; use common_utils::{ext_traits::BytesExt, request as services}; use error_stack::ResultExt; use hyperswitch_interfaces::api_client as api; use crate::{core::errors, helpers, state::SubscriptionState as SessionState}; pub struct PaymentsApiClient; #[derive(Debug, serde::Deserialize)] pub struct ErrorResponse { error: ErrorResponseDetails, } #[derive(Debug, serde::Deserialize)] pub struct ErrorResponseDetails { #[serde(rename = "type")] error_type: Option<String>, code: String, message: String, } impl PaymentsApiClient { fn get_internal_auth_headers( state: &SessionState, merchant_id: &str, profile_id: &str, ) -> Vec<(String, masking::Maskable<String>)> { vec![ ( helpers::X_INTERNAL_API_KEY.to_string(), masking::Maskable::Masked( state .conf .internal_merchant_id_profile_id_auth .internal_api_key .clone(), ), ), ( helpers::X_TENANT_ID.to_string(), masking::Maskable::Normal(state.tenant.tenant_id.get_string_repr().to_string()), ), ( helpers::X_MERCHANT_ID.to_string(), masking::Maskable::Normal(merchant_id.to_string()), ), ( helpers::X_PROFILE_ID.to_string(), masking::Maskable::Normal(profile_id.to_string()), ), ] } /// Generic method to handle payment API calls with different HTTP methods and URL patterns async fn make_payment_api_call( state: &SessionState, method: services::Method, url: String, request_body: Option<common_utils::request::RequestContent>, operation_name: &str, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let subscription_error = errors::ApiErrorResponse::SubscriptionError { operation: operation_name.to_string(), }; let headers = Self::get_internal_auth_headers(state, merchant_id, profile_id); let mut request_builder = services::RequestBuilder::new() .method(method) .url(&url) .headers(headers); // Add request body only if provided (for POST requests) if let Some(body) = request_body { request_builder = request_builder.set_body(body); } let request = request_builder.build(); let response = api::call_connector_api(state, request, "Subscription Payments") .await .change_context(subscription_error.clone())?; match response { Ok(res) => { let api_response: subscription_types::PaymentResponseData = res .response .parse_struct(std::any::type_name::<subscription_types::PaymentResponseData>()) .change_context(subscription_error)?; Ok(api_response) } Err(err) => { let error_response: ErrorResponse = err .response .parse_struct(std::any::type_name::<ErrorResponse>()) .change_context(subscription_error)?; Err(errors::ApiErrorResponse::ExternalConnectorError { code: error_response.error.code, message: error_response.error.message, connector: "payments_microservice".to_string(), status_code: err.status_code, reason: error_response.error.error_type, } .into()) } } } pub async fn create_cit_payment( state: &SessionState, request: subscription_types::CreatePaymentsRequestData, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments", base_url); Self::make_payment_api_call( state, services::Method::Post, url, Some(common_utils::request::RequestContent::Json(Box::new( request, ))), "Create Payment", merchant_id, profile_id, ) .await } pub async fn create_and_confirm_payment( state: &SessionState, request: subscription_types::CreateAndConfirmPaymentsRequestData, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments", base_url); Self::make_payment_api_call( state, services::Method::Post, url, Some(common_utils::request::RequestContent::Json(Box::new( request, ))), "Create And Confirm Payment", merchant_id, profile_id, ) .await } pub async fn confirm_payment( state: &SessionState, request: subscription_types::ConfirmPaymentsRequestData, payment_id: String, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments/{}/confirm", base_url, payment_id); Self::make_payment_api_call( state, services::Method::Post, url, Some(common_utils::request::RequestContent::Json(Box::new( request, ))), "Confirm Payment", merchant_id, profile_id, ) .await } pub async fn sync_payment( state: &SessionState, payment_id: String, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments/{}", base_url, payment_id); Self::make_payment_api_call( state, services::Method::Get, url, None, "Sync Payment", merchant_id, profile_id, ) .await } pub async fn create_mit_payment( state: &SessionState, request: subscription_types::CreateMitPaymentRequestData, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments", base_url); Self::make_payment_api_call( state, services::Method::Post, url, Some(common_utils::request::RequestContent::Json(Box::new( request, ))), "Create MIT Payment", merchant_id, profile_id, ) .await } pub async fn update_payment( state: &SessionState, request: subscription_types::CreatePaymentsRequestData, payment_id: String, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments/{}", base_url, payment_id); Self::make_payment_api_call( state, services::Method::Post, url, Some(common_utils::request::RequestContent::Json(Box::new( request, ))), "Update Payment", merchant_id, profile_id, ) .await } }
{ "crate": "subscriptions", "file": "crates/subscriptions/src/core/payments_api_client.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_hsdev_7489480386155775295
clm
file
// Repository: hyperswitch // Crate: hsdev // File: crates/hsdev/src/main.rs // Contains: 1 structs, 0 enums #![allow(clippy::print_stdout, clippy::print_stderr)] use clap::{Parser, ValueHint}; use diesel::{pg::PgConnection, Connection}; use diesel_migrations::{FileBasedMigrations, HarnessWithOutput, MigrationHarness}; use toml::Value; mod input_file; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { #[arg(short, long, value_hint = ValueHint::FilePath)] toml_file: std::path::PathBuf, #[arg(long, default_value_t = String::from(""))] toml_table: String, } fn main() { let args = Args::parse(); let toml_file = &args.toml_file; let table_name = &args.toml_table; let toml_contents = match std::fs::read_to_string(toml_file) { Ok(contents) => contents, Err(e) => { eprintln!("Error reading TOML file: {e}"); return; } }; let toml_data: Value = match toml_contents.parse() { Ok(data) => data, Err(e) => { eprintln!("Error parsing TOML file: {e}"); return; } }; let table = get_toml_table(table_name, &toml_data); let input = match input_file::InputData::read(table) { Ok(data) => data, Err(e) => { eprintln!("Error loading TOML file: {e}"); return; } }; let db_url = input.postgres_url(); println!("Attempting to connect to {db_url}"); let mut conn = match PgConnection::establish(&db_url) { Ok(value) => value, Err(_) => { eprintln!("Unable to establish database connection"); return; } }; let migrations = match FileBasedMigrations::find_migrations_directory() { Ok(value) => value, Err(_) => { eprintln!("Could not find migrations directory"); return; } }; let mut harness = HarnessWithOutput::write_to_stdout(&mut conn); match harness.run_pending_migrations(migrations) { Ok(_) => println!("Successfully ran migrations"), Err(_) => eprintln!("Couldn't run migrations"), }; } pub fn get_toml_table<'a>(table_name: &'a str, toml_data: &'a Value) -> &'a Value { if !table_name.is_empty() { match toml_data.get(table_name) { Some(value) => value, None => { eprintln!("Unable to find toml table: \"{}\"", &table_name); std::process::abort() } } } else { toml_data } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use std::str::FromStr; use toml::Value; use crate::{get_toml_table, input_file::InputData}; #[test] fn test_input_file() { let toml_str = r#"username = "db_user" password = "db_pass" dbname = "db_name" host = "localhost" port = 5432"#; let toml_value = Value::from_str(toml_str); assert!(toml_value.is_ok()); let toml_value = toml_value.unwrap(); let toml_table = InputData::read(&toml_value); assert!(toml_table.is_ok()); let toml_table = toml_table.unwrap(); let db_url = toml_table.postgres_url(); assert_eq!("postgres://db_user:db_pass@localhost:5432/db_name", db_url); } #[test] fn test_given_toml() { let toml_str_table = r#"[database] username = "db_user" password = "db_pass" dbname = "db_name" host = "localhost" port = 5432"#; let table_name = "database"; let toml_value = Value::from_str(toml_str_table).unwrap(); let table = get_toml_table(table_name, &toml_value); assert!(table.is_table()); let table_name = ""; let table = get_toml_table(table_name, &toml_value); assert!(table.is_table()); } }
{ "crate": "hsdev", "file": "crates/hsdev/src/main.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_hsdev_-1061152469412517307
clm
file
// Repository: hyperswitch // Crate: hsdev // File: crates/hsdev/src/input_file.rs // Contains: 1 structs, 0 enums use std::string::String; use serde::Deserialize; use toml::Value; #[derive(Deserialize)] pub struct InputData { username: String, password: String, dbname: String, host: String, port: u16, } impl InputData { pub fn read(db_table: &Value) -> Result<Self, toml::de::Error> { db_table.clone().try_into() } pub fn postgres_url(&self) -> String { format!( "postgres://{}:{}@{}:{}/{}", self.username, self.password, self.host, self.port, self.dbname ) } }
{ "crate": "hsdev", "file": "crates/hsdev/src/input_file.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_euclid_2646311811679223571
clm
file
// Repository: hyperswitch // Crate: euclid // File: crates/euclid/src/types.rs // Contains: 4 structs, 4 enums pub mod transformers; use common_utils::types::MinorUnit; use euclid_macros::EnumNums; use serde::{Deserialize, Serialize}; use strum::VariantNames; use crate::{ dssa::types::EuclidAnalysable, enums, frontend::{ ast, dir::{ enums::{CustomerDeviceDisplaySize, CustomerDevicePlatform, CustomerDeviceType}, DirKeyKind, DirValue, EuclidDirFilter, }, }, }; pub type Metadata = std::collections::HashMap<String, serde_json::Value>; #[derive( Debug, Clone, EnumNums, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumString, )] pub enum EuclidKey { #[strum(serialize = "payment_method")] PaymentMethod, #[strum(serialize = "card_bin")] CardBin, #[strum(serialize = "metadata")] Metadata, #[strum(serialize = "mandate_type")] MandateType, #[strum(serialize = "mandate_acceptance_type")] MandateAcceptanceType, #[strum(serialize = "payment_type")] PaymentType, #[strum(serialize = "payment_method_type")] PaymentMethodType, #[strum(serialize = "card_network")] CardNetwork, #[strum(serialize = "authentication_type")] AuthenticationType, #[strum(serialize = "capture_method")] CaptureMethod, #[strum(serialize = "amount")] PaymentAmount, #[strum(serialize = "currency")] PaymentCurrency, #[cfg(feature = "payouts")] #[strum(serialize = "payout_currency")] PayoutCurrency, #[strum(serialize = "country", to_string = "business_country")] BusinessCountry, #[strum(serialize = "billing_country")] BillingCountry, #[strum(serialize = "business_label")] BusinessLabel, #[strum(serialize = "setup_future_usage")] SetupFutureUsage, #[strum(serialize = "issuer_name")] IssuerName, #[strum(serialize = "issuer_country")] IssuerCountry, #[strum(serialize = "acquirer_country")] AcquirerCountry, #[strum(serialize = "acquirer_fraud_rate")] AcquirerFraudRate, #[strum(serialize = "customer_device_type")] CustomerDeviceType, #[strum(serialize = "customer_device_display_size")] CustomerDeviceDisplaySize, #[strum(serialize = "customer_device_platform")] CustomerDevicePlatform, } impl EuclidDirFilter for DummyOutput { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::AuthenticationType, DirKeyKind::PaymentMethod, DirKeyKind::CardType, DirKeyKind::PaymentCurrency, DirKeyKind::CaptureMethod, DirKeyKind::AuthenticationType, DirKeyKind::CardBin, DirKeyKind::PayLaterType, DirKeyKind::PaymentAmount, DirKeyKind::MetaData, DirKeyKind::MandateAcceptanceType, DirKeyKind::MandateType, DirKeyKind::PaymentType, DirKeyKind::SetupFutureUsage, ]; } impl EuclidAnalysable for DummyOutput { fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(DirValue, Metadata)> { self.outputs .iter() .map(|dummyc| { let metadata_key = "MetadataKey".to_string(); let metadata_value = dummyc; ( DirValue::MetaData(MetadataValue { key: metadata_key.clone(), value: metadata_value.clone(), }), std::collections::HashMap::from_iter([( "DUMMY_OUTPUT".to_string(), serde_json::json!({ "rule_name":rule_name, "Metadata_Key" :metadata_key, "Metadata_Value" : metadata_value, }), )]), ) }) .collect() } } #[derive(Debug, Clone, Serialize)] pub struct DummyOutput { pub outputs: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, strum::Display)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DataType { Number, EnumVariant, MetadataValue, StrValue, } impl EuclidKey { pub fn key_type(&self) -> DataType { match self { Self::PaymentMethod => DataType::EnumVariant, Self::CardBin => DataType::StrValue, Self::Metadata => DataType::MetadataValue, Self::PaymentMethodType => DataType::EnumVariant, Self::CardNetwork => DataType::EnumVariant, Self::AuthenticationType => DataType::EnumVariant, Self::CaptureMethod => DataType::EnumVariant, Self::PaymentAmount => DataType::Number, Self::PaymentCurrency => DataType::EnumVariant, #[cfg(feature = "payouts")] Self::PayoutCurrency => DataType::EnumVariant, Self::BusinessCountry => DataType::EnumVariant, Self::BillingCountry => DataType::EnumVariant, Self::MandateType => DataType::EnumVariant, Self::MandateAcceptanceType => DataType::EnumVariant, Self::PaymentType => DataType::EnumVariant, Self::BusinessLabel => DataType::StrValue, Self::SetupFutureUsage => DataType::EnumVariant, Self::IssuerName => DataType::StrValue, Self::IssuerCountry => DataType::EnumVariant, Self::AcquirerCountry => DataType::EnumVariant, Self::AcquirerFraudRate => DataType::Number, Self::CustomerDeviceType => DataType::EnumVariant, Self::CustomerDeviceDisplaySize => DataType::EnumVariant, Self::CustomerDevicePlatform => DataType::EnumVariant, } } } enums::collect_variants!(EuclidKey); #[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum NumValueRefinement { NotEqual, GreaterThan, LessThan, GreaterThanEqual, LessThanEqual, } impl From<ast::ComparisonType> for Option<NumValueRefinement> { fn from(comp_type: ast::ComparisonType) -> Self { match comp_type { ast::ComparisonType::Equal => None, ast::ComparisonType::NotEqual => Some(NumValueRefinement::NotEqual), ast::ComparisonType::GreaterThan => Some(NumValueRefinement::GreaterThan), ast::ComparisonType::LessThan => Some(NumValueRefinement::LessThan), ast::ComparisonType::LessThanEqual => Some(NumValueRefinement::LessThanEqual), ast::ComparisonType::GreaterThanEqual => Some(NumValueRefinement::GreaterThanEqual), } } } impl From<NumValueRefinement> for ast::ComparisonType { fn from(value: NumValueRefinement) -> Self { match value { NumValueRefinement::NotEqual => Self::NotEqual, NumValueRefinement::LessThan => Self::LessThan, NumValueRefinement::GreaterThan => Self::GreaterThan, NumValueRefinement::GreaterThanEqual => Self::GreaterThanEqual, NumValueRefinement::LessThanEqual => Self::LessThanEqual, } } } #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct StrValue { pub value: String, } #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct MetadataValue { pub key: String, pub value: String, } #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct NumValue { pub number: MinorUnit, pub refinement: Option<NumValueRefinement>, } impl NumValue { pub fn fits(&self, other: &Self) -> bool { let this_num = self.number; let other_num = other.number; match (&self.refinement, &other.refinement) { (None, None) => this_num == other_num, (Some(NumValueRefinement::GreaterThan), None) => other_num > this_num, (Some(NumValueRefinement::LessThan), None) => other_num < this_num, (Some(NumValueRefinement::NotEqual), Some(NumValueRefinement::NotEqual)) => { other_num == this_num } (Some(NumValueRefinement::GreaterThan), Some(NumValueRefinement::GreaterThan)) => { other_num > this_num } (Some(NumValueRefinement::LessThan), Some(NumValueRefinement::LessThan)) => { other_num < this_num } (Some(NumValueRefinement::GreaterThanEqual), None) => other_num >= this_num, (Some(NumValueRefinement::LessThanEqual), None) => other_num <= this_num, ( Some(NumValueRefinement::GreaterThanEqual), Some(NumValueRefinement::GreaterThanEqual), ) => other_num >= this_num, (Some(NumValueRefinement::LessThanEqual), Some(NumValueRefinement::LessThanEqual)) => { other_num <= this_num } _ => false, } } } #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum EuclidValue { PaymentMethod(enums::PaymentMethod), CardBin(StrValue), Metadata(MetadataValue), PaymentMethodType(enums::PaymentMethodType), CardNetwork(enums::CardNetwork), AuthenticationType(enums::AuthenticationType), CaptureMethod(enums::CaptureMethod), PaymentType(enums::PaymentType), MandateAcceptanceType(enums::MandateAcceptanceType), MandateType(enums::MandateType), PaymentAmount(NumValue), PaymentCurrency(enums::Currency), #[cfg(feature = "payouts")] PayoutCurrency(enums::Currency), BusinessCountry(enums::Country), BillingCountry(enums::Country), BusinessLabel(StrValue), SetupFutureUsage(enums::SetupFutureUsage), IssuerName(StrValue), IssuerCountry(enums::Country), AcquirerCountry(enums::Country), AcquirerFraudRate(NumValue), CustomerDeviceType(CustomerDeviceType), CustomerDeviceDisplaySize(CustomerDeviceDisplaySize), CustomerDevicePlatform(CustomerDevicePlatform), } impl EuclidValue { pub fn get_num_value(&self) -> Option<NumValue> { match self { Self::PaymentAmount(val) => Some(val.clone()), _ => None, } } pub fn get_key(&self) -> EuclidKey { match self { Self::PaymentMethod(_) => EuclidKey::PaymentMethod, Self::CardBin(_) => EuclidKey::CardBin, Self::Metadata(_) => EuclidKey::Metadata, Self::PaymentMethodType(_) => EuclidKey::PaymentMethodType, Self::MandateType(_) => EuclidKey::MandateType, Self::PaymentType(_) => EuclidKey::PaymentType, Self::MandateAcceptanceType(_) => EuclidKey::MandateAcceptanceType, Self::CardNetwork(_) => EuclidKey::CardNetwork, Self::AuthenticationType(_) => EuclidKey::AuthenticationType, Self::CaptureMethod(_) => EuclidKey::CaptureMethod, Self::PaymentAmount(_) => EuclidKey::PaymentAmount, Self::PaymentCurrency(_) => EuclidKey::PaymentCurrency, #[cfg(feature = "payouts")] Self::PayoutCurrency(_) => EuclidKey::PayoutCurrency, Self::BusinessCountry(_) => EuclidKey::BusinessCountry, Self::BillingCountry(_) => EuclidKey::BillingCountry, Self::BusinessLabel(_) => EuclidKey::BusinessLabel, Self::SetupFutureUsage(_) => EuclidKey::SetupFutureUsage, Self::IssuerName(_) => EuclidKey::IssuerName, Self::IssuerCountry(_) => EuclidKey::IssuerCountry, Self::AcquirerCountry(_) => EuclidKey::AcquirerCountry, Self::AcquirerFraudRate(_) => EuclidKey::AcquirerFraudRate, Self::CustomerDeviceType(_) => EuclidKey::CustomerDeviceType, Self::CustomerDeviceDisplaySize(_) => EuclidKey::CustomerDeviceDisplaySize, Self::CustomerDevicePlatform(_) => EuclidKey::CustomerDevicePlatform, } } } #[cfg(test)] mod global_type_tests { use super::*; #[test] fn test_num_value_fits_greater_than() { let val1 = NumValue { number: MinorUnit::new(10), refinement: Some(NumValueRefinement::GreaterThan), }; let val2 = NumValue { number: MinorUnit::new(30), refinement: Some(NumValueRefinement::GreaterThan), }; assert!(val1.fits(&val2)) } #[test] fn test_num_value_fits_less_than() { let val1 = NumValue { number: MinorUnit::new(30), refinement: Some(NumValueRefinement::LessThan), }; let val2 = NumValue { number: MinorUnit::new(10), refinement: Some(NumValueRefinement::LessThan), }; assert!(val1.fits(&val2)); } }
{ "crate": "euclid", "file": "crates/euclid/src/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 4, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_euclid_-4792896587506338825
clm
file
// Repository: hyperswitch // Crate: euclid // File: crates/euclid/src/backend.rs // Contains: 1 structs, 0 enums pub mod inputs; pub mod interpreter; #[cfg(feature = "valued_jit")] pub mod vir_interpreter; pub use inputs::BackendInput; pub use interpreter::InterpreterBackend; #[cfg(feature = "valued_jit")] pub use vir_interpreter::VirInterpreterBackend; use crate::frontend::ast; #[derive(Debug, Clone, serde::Serialize)] pub struct BackendOutput<O> { pub rule_name: Option<String>, pub connector_selection: O, } impl<O> BackendOutput<O> { // get_connector_selection pub fn get_output(&self) -> &O { &self.connector_selection } } pub trait EuclidBackend<O>: Sized { type Error: serde::Serialize; fn with_program(program: ast::Program<O>) -> Result<Self, Self::Error>; fn execute(&self, input: BackendInput) -> Result<BackendOutput<O>, Self::Error>; }
{ "crate": "euclid", "file": "crates/euclid/src/backend.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_euclid_-4593858384555371407
clm
file
// Repository: hyperswitch // Crate: euclid // File: crates/euclid/src/frontend/vir.rs // Contains: 4 structs, 1 enums //! Valued Intermediate Representation use serde::{Deserialize, Serialize}; use crate::types::{EuclidValue, Metadata}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ValuedComparisonLogic { NegativeConjunction, PositiveDisjunction, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedComparison { pub values: Vec<EuclidValue>, pub logic: ValuedComparisonLogic, pub metadata: Metadata, } pub type ValuedIfCondition = Vec<ValuedComparison>; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedIfStatement { pub condition: ValuedIfCondition, pub nested: Option<Vec<ValuedIfStatement>>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedRule<O> { pub name: String, pub connector_selection: O, pub statements: Vec<ValuedIfStatement>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedProgram<O> { pub default_selection: O, pub rules: Vec<ValuedRule<O>>, pub metadata: Metadata, }
{ "crate": "euclid", "file": "crates/euclid/src/frontend/vir.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_euclid_-4921660127807392940
clm
file
// Repository: hyperswitch // Crate: euclid // File: crates/euclid/src/frontend/dir.rs // Contains: 5 structs, 5 enums //! Domain Intermediate Representation pub mod enums; pub mod lowering; pub mod transformers; use strum::IntoEnumIterator; // use common_utils::types::MinorUnit; use crate::{enums as euclid_enums, frontend::ast, types}; #[macro_export] macro_rules! dirval { (Connector = $name:ident) => { $crate::frontend::dir::DirValue::Connector(Box::new( $crate::frontend::ast::ConnectorChoice { connector: $crate::enums::RoutableConnectors::$name, }, )) }; ($key:ident = $val:ident) => {{ pub use $crate::frontend::dir::enums::*; $crate::frontend::dir::DirValue::$key($key::$val) }}; ($key:ident = $num:literal) => {{ $crate::frontend::dir::DirValue::$key($crate::types::NumValue { number: common_utils::types::MinorUnit::new($num), refinement: None, }) }}; ($key:ident s= $str:literal) => {{ $crate::frontend::dir::DirValue::$key($crate::types::StrValue { value: $str.to_string(), }) }}; ($key:literal = $str:literal) => {{ $crate::frontend::dir::DirValue::MetaData($crate::types::MetadataValue { key: $key.to_string(), value: $str.to_string(), }) }}; } #[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize)] pub struct DirKey { pub kind: DirKeyKind, pub value: Option<String>, } impl DirKey { pub fn new(kind: DirKeyKind, value: Option<String>) -> Self { Self { kind, value } } } #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::EnumIter, strum::VariantNames, strum::EnumString, strum::EnumMessage, strum::EnumProperty, )] pub enum DirKeyKind { #[strum( serialize = "payment_method", detailed_message = "Different modes of payment - eg. cards, wallets, banks", props(Category = "Payment Methods") )] #[serde(rename = "payment_method")] PaymentMethod, #[strum( serialize = "card_bin", detailed_message = "First 4 to 6 digits of a payment card number", props(Category = "Payment Methods") )] #[serde(rename = "card_bin")] CardBin, #[strum( serialize = "card_type", detailed_message = "Type of the payment card - eg. credit, debit", props(Category = "Payment Methods") )] #[serde(rename = "card_type")] CardType, #[strum( serialize = "card_network", detailed_message = "Network that facilitates payment card transactions", props(Category = "Payment Methods") )] #[serde(rename = "card_network")] CardNetwork, #[strum( serialize = "pay_later", detailed_message = "Supported types of Pay Later payment method", props(Category = "Payment Method Types") )] #[serde(rename = "pay_later")] PayLaterType, #[strum( serialize = "gift_card", detailed_message = "Supported types of Gift Card payment method", props(Category = "Payment Method Types") )] #[serde(rename = "gift_card")] GiftCardType, #[strum( serialize = "mandate_acceptance_type", detailed_message = "Mode of customer acceptance for mandates - online and offline", props(Category = "Payments") )] #[serde(rename = "mandate_acceptance_type")] MandateAcceptanceType, #[strum( serialize = "mandate_type", detailed_message = "Type of mandate acceptance - single use and multi use", props(Category = "Payments") )] #[serde(rename = "mandate_type")] MandateType, #[strum( serialize = "payment_type", detailed_message = "Indicates if a payment is mandate or non-mandate", props(Category = "Payments") )] #[serde(rename = "payment_type")] PaymentType, #[strum( serialize = "wallet", detailed_message = "Supported types of Wallet payment method", props(Category = "Payment Method Types") )] #[serde(rename = "wallet")] WalletType, #[strum( serialize = "upi", detailed_message = "Supported types of UPI payment method", props(Category = "Payment Method Types") )] #[serde(rename = "upi")] UpiType, #[strum( serialize = "voucher", detailed_message = "Supported types of Voucher payment method", props(Category = "Payment Method Types") )] #[serde(rename = "voucher")] VoucherType, #[strum( serialize = "bank_transfer", detailed_message = "Supported types of Bank Transfer payment method", props(Category = "Payment Method Types") )] #[serde(rename = "bank_transfer")] BankTransferType, #[strum( serialize = "bank_redirect", detailed_message = "Supported types of Bank Redirect payment methods", props(Category = "Payment Method Types") )] #[serde(rename = "bank_redirect")] BankRedirectType, #[strum( serialize = "bank_debit", detailed_message = "Supported types of Bank Debit payment method", props(Category = "Payment Method Types") )] #[serde(rename = "bank_debit")] BankDebitType, #[strum( serialize = "crypto", detailed_message = "Supported types of Crypto payment method", props(Category = "Payment Method Types") )] #[serde(rename = "crypto")] CryptoType, #[strum( serialize = "metadata", detailed_message = "Aribitrary Key and value pair", props(Category = "Metadata") )] #[serde(rename = "metadata")] MetaData, #[strum( serialize = "reward", detailed_message = "Supported types of Reward payment method", props(Category = "Payment Method Types") )] #[serde(rename = "reward")] RewardType, #[strum( serialize = "amount", detailed_message = "Value of the transaction", props(Category = "Payments") )] #[serde(rename = "amount")] PaymentAmount, #[strum( serialize = "currency", detailed_message = "Currency used for the payment", props(Category = "Payments") )] #[serde(rename = "currency")] PaymentCurrency, #[strum( serialize = "authentication_type", detailed_message = "Type of authentication for the payment", props(Category = "Payments") )] #[serde(rename = "authentication_type")] AuthenticationType, #[strum( serialize = "capture_method", detailed_message = "Modes of capturing a payment", props(Category = "Payments") )] #[serde(rename = "capture_method")] CaptureMethod, #[strum( serialize = "country", serialize = "business_country", detailed_message = "Country of the business unit", props(Category = "Merchant") )] #[serde(rename = "business_country", alias = "country")] BusinessCountry, #[strum( serialize = "billing_country", detailed_message = "Country of the billing address of the customer", props(Category = "Customer") )] #[serde(rename = "billing_country")] BillingCountry, #[serde(skip_deserializing, rename = "connector")] Connector, #[strum( serialize = "business_label", detailed_message = "Identifier for business unit", props(Category = "Merchant") )] #[serde(rename = "business_label")] BusinessLabel, #[strum( serialize = "setup_future_usage", detailed_message = "Identifier for recurring payments", props(Category = "Payments") )] #[serde(rename = "setup_future_usage")] SetupFutureUsage, #[strum( serialize = "card_redirect", detailed_message = "Supported types of Card Redirect payment method", props(Category = "Payment Method Types") )] #[serde(rename = "card_redirect")] CardRedirectType, #[serde(rename = "real_time_payment")] #[strum( serialize = "real_time_payment", detailed_message = "Supported types of real time payment method", props(Category = "Payment Method Types") )] RealTimePaymentType, #[serde(rename = "open_banking")] #[strum( serialize = "open_banking", detailed_message = "Supported types of open banking payment method", props(Category = "Payment Method Types") )] OpenBankingType, #[serde(rename = "mobile_payment")] #[strum( serialize = "mobile_payment", detailed_message = "Supported types of mobile payment method", props(Category = "Payment Method Types") )] MobilePaymentType, #[strum( serialize = "issuer_name", detailed_message = "Name of the card issuing bank", props(Category = "3DS Decision") )] #[serde(rename = "issuer_name")] IssuerName, #[strum( serialize = "issuer_country", detailed_message = "Country of the card issuing bank", props(Category = "3DS Decision") )] #[serde(rename = "issuer_country")] IssuerCountry, #[strum( serialize = "customer_device_platform", detailed_message = "Platform of the customer's device (Web, Android, iOS)", props(Category = "3DS Decision") )] #[serde(rename = "customer_device_platform")] CustomerDevicePlatform, #[strum( serialize = "customer_device_type", detailed_message = "Type of the customer's device (Mobile, Tablet, Desktop, Gaming Console)", props(Category = "3DS Decision") )] #[serde(rename = "customer_device_type")] CustomerDeviceType, #[strum( serialize = "customer_device_display_size", detailed_message = "Display size of the customer's device (e.g., 500x600)", props(Category = "3DS Decision") )] #[serde(rename = "customer_device_display_size")] CustomerDeviceDisplaySize, #[strum( serialize = "acquirer_country", detailed_message = "Country of the acquiring bank", props(Category = "3DS Decision") )] #[serde(rename = "acquirer_country")] AcquirerCountry, #[strum( serialize = "acquirer_fraud_rate", detailed_message = "Fraud rate of the acquiring bank", props(Category = "3DS Decision") )] #[serde(rename = "acquirer_fraud_rate")] AcquirerFraudRate, } pub trait EuclidDirFilter: Sized where Self: 'static, { const ALLOWED: &'static [DirKeyKind]; fn get_allowed_keys() -> &'static [DirKeyKind] { Self::ALLOWED } fn is_key_allowed(key: &DirKeyKind) -> bool { Self::ALLOWED.contains(key) } } impl DirKeyKind { pub fn get_type(&self) -> types::DataType { match self { Self::PaymentMethod => types::DataType::EnumVariant, Self::CardBin => types::DataType::StrValue, Self::CardType => types::DataType::EnumVariant, Self::CardNetwork => types::DataType::EnumVariant, Self::MetaData => types::DataType::MetadataValue, Self::MandateType => types::DataType::EnumVariant, Self::PaymentType => types::DataType::EnumVariant, Self::MandateAcceptanceType => types::DataType::EnumVariant, Self::PayLaterType => types::DataType::EnumVariant, Self::WalletType => types::DataType::EnumVariant, Self::UpiType => types::DataType::EnumVariant, Self::VoucherType => types::DataType::EnumVariant, Self::BankTransferType => types::DataType::EnumVariant, Self::GiftCardType => types::DataType::EnumVariant, Self::BankRedirectType => types::DataType::EnumVariant, Self::CryptoType => types::DataType::EnumVariant, Self::RewardType => types::DataType::EnumVariant, Self::PaymentAmount => types::DataType::Number, Self::PaymentCurrency => types::DataType::EnumVariant, Self::AuthenticationType => types::DataType::EnumVariant, Self::CaptureMethod => types::DataType::EnumVariant, Self::BusinessCountry => types::DataType::EnumVariant, Self::BillingCountry => types::DataType::EnumVariant, Self::Connector => types::DataType::EnumVariant, Self::BankDebitType => types::DataType::EnumVariant, Self::BusinessLabel => types::DataType::StrValue, Self::SetupFutureUsage => types::DataType::EnumVariant, Self::CardRedirectType => types::DataType::EnumVariant, Self::RealTimePaymentType => types::DataType::EnumVariant, Self::OpenBankingType => types::DataType::EnumVariant, Self::MobilePaymentType => types::DataType::EnumVariant, Self::IssuerName => types::DataType::StrValue, Self::IssuerCountry => types::DataType::EnumVariant, Self::CustomerDevicePlatform => types::DataType::EnumVariant, Self::CustomerDeviceType => types::DataType::EnumVariant, Self::CustomerDeviceDisplaySize => types::DataType::EnumVariant, Self::AcquirerCountry => types::DataType::EnumVariant, Self::AcquirerFraudRate => types::DataType::Number, } } pub fn get_value_set(&self) -> Option<Vec<DirValue>> { match self { Self::PaymentMethod => Some( enums::PaymentMethod::iter() .map(DirValue::PaymentMethod) .collect(), ), Self::CardBin => None, Self::CardType => Some(enums::CardType::iter().map(DirValue::CardType).collect()), Self::MandateAcceptanceType => Some( euclid_enums::MandateAcceptanceType::iter() .map(DirValue::MandateAcceptanceType) .collect(), ), Self::PaymentType => Some( euclid_enums::PaymentType::iter() .map(DirValue::PaymentType) .collect(), ), Self::MandateType => Some( euclid_enums::MandateType::iter() .map(DirValue::MandateType) .collect(), ), Self::CardNetwork => Some( enums::CardNetwork::iter() .map(DirValue::CardNetwork) .collect(), ), Self::PayLaterType => Some( enums::PayLaterType::iter() .map(DirValue::PayLaterType) .collect(), ), Self::MetaData => None, Self::WalletType => Some( enums::WalletType::iter() .map(DirValue::WalletType) .collect(), ), Self::UpiType => Some(enums::UpiType::iter().map(DirValue::UpiType).collect()), Self::VoucherType => Some( enums::VoucherType::iter() .map(DirValue::VoucherType) .collect(), ), Self::BankTransferType => Some( enums::BankTransferType::iter() .map(DirValue::BankTransferType) .collect(), ), Self::GiftCardType => Some( enums::GiftCardType::iter() .map(DirValue::GiftCardType) .collect(), ), Self::BankRedirectType => Some( enums::BankRedirectType::iter() .map(DirValue::BankRedirectType) .collect(), ), Self::CryptoType => Some( enums::CryptoType::iter() .map(DirValue::CryptoType) .collect(), ), Self::RewardType => Some( enums::RewardType::iter() .map(DirValue::RewardType) .collect(), ), Self::PaymentAmount => None, Self::PaymentCurrency => Some( enums::PaymentCurrency::iter() .map(DirValue::PaymentCurrency) .collect(), ), Self::AuthenticationType => Some( enums::AuthenticationType::iter() .map(DirValue::AuthenticationType) .collect(), ), Self::CaptureMethod => Some( enums::CaptureMethod::iter() .map(DirValue::CaptureMethod) .collect(), ), Self::BankDebitType => Some( enums::BankDebitType::iter() .map(DirValue::BankDebitType) .collect(), ), Self::BusinessCountry => Some( enums::Country::iter() .map(DirValue::BusinessCountry) .collect(), ), Self::BillingCountry => Some( enums::Country::iter() .map(DirValue::BillingCountry) .collect(), ), Self::Connector => Some( common_enums::RoutableConnectors::iter() .map(|connector| { DirValue::Connector(Box::new(ast::ConnectorChoice { connector })) }) .collect(), ), Self::BusinessLabel => None, Self::SetupFutureUsage => Some( enums::SetupFutureUsage::iter() .map(DirValue::SetupFutureUsage) .collect(), ), Self::CardRedirectType => Some( enums::CardRedirectType::iter() .map(DirValue::CardRedirectType) .collect(), ), Self::RealTimePaymentType => Some( enums::RealTimePaymentType::iter() .map(DirValue::RealTimePaymentType) .collect(), ), Self::OpenBankingType => Some( enums::OpenBankingType::iter() .map(DirValue::OpenBankingType) .collect(), ), Self::MobilePaymentType => Some( enums::MobilePaymentType::iter() .map(DirValue::MobilePaymentType) .collect(), ), Self::IssuerName => None, Self::IssuerCountry => Some( enums::Country::iter() .map(DirValue::IssuerCountry) .collect(), ), Self::CustomerDevicePlatform => Some( enums::CustomerDevicePlatform::iter() .map(DirValue::CustomerDevicePlatform) .collect(), ), Self::CustomerDeviceType => Some( enums::CustomerDeviceType::iter() .map(DirValue::CustomerDeviceType) .collect(), ), Self::CustomerDeviceDisplaySize => Some( enums::CustomerDeviceDisplaySize::iter() .map(DirValue::CustomerDeviceDisplaySize) .collect(), ), Self::AcquirerCountry => Some( enums::Country::iter() .map(DirValue::AcquirerCountry) .collect(), ), Self::AcquirerFraudRate => None, } } } #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::VariantNames, )] #[serde(tag = "key", content = "value")] pub enum DirValue { #[serde(rename = "payment_method")] PaymentMethod(enums::PaymentMethod), #[serde(rename = "card_bin")] CardBin(types::StrValue), #[serde(rename = "card_type")] CardType(enums::CardType), #[serde(rename = "card_network")] CardNetwork(enums::CardNetwork), #[serde(rename = "metadata")] MetaData(types::MetadataValue), #[serde(rename = "pay_later")] PayLaterType(enums::PayLaterType), #[serde(rename = "wallet")] WalletType(enums::WalletType), #[serde(rename = "acceptance_type")] MandateAcceptanceType(euclid_enums::MandateAcceptanceType), #[serde(rename = "mandate_type")] MandateType(euclid_enums::MandateType), #[serde(rename = "payment_type")] PaymentType(euclid_enums::PaymentType), #[serde(rename = "upi")] UpiType(enums::UpiType), #[serde(rename = "voucher")] VoucherType(enums::VoucherType), #[serde(rename = "bank_transfer")] BankTransferType(enums::BankTransferType), #[serde(rename = "bank_redirect")] BankRedirectType(enums::BankRedirectType), #[serde(rename = "bank_debit")] BankDebitType(enums::BankDebitType), #[serde(rename = "crypto")] CryptoType(enums::CryptoType), #[serde(rename = "reward")] RewardType(enums::RewardType), #[serde(rename = "gift_card")] GiftCardType(enums::GiftCardType), #[serde(rename = "amount")] PaymentAmount(types::NumValue), #[serde(rename = "currency")] PaymentCurrency(enums::PaymentCurrency), #[serde(rename = "authentication_type")] AuthenticationType(enums::AuthenticationType), #[serde(rename = "capture_method")] CaptureMethod(enums::CaptureMethod), #[serde(rename = "business_country", alias = "country")] BusinessCountry(enums::Country), #[serde(rename = "billing_country")] BillingCountry(enums::Country), #[serde(skip_deserializing, rename = "connector")] Connector(Box<ast::ConnectorChoice>), #[serde(rename = "business_label")] BusinessLabel(types::StrValue), #[serde(rename = "setup_future_usage")] SetupFutureUsage(enums::SetupFutureUsage), #[serde(rename = "card_redirect")] CardRedirectType(enums::CardRedirectType), #[serde(rename = "real_time_payment")] RealTimePaymentType(enums::RealTimePaymentType), #[serde(rename = "open_banking")] OpenBankingType(enums::OpenBankingType), #[serde(rename = "mobile_payment")] MobilePaymentType(enums::MobilePaymentType), #[serde(rename = "issuer_name")] IssuerName(types::StrValue), #[serde(rename = "issuer_country")] IssuerCountry(enums::Country), #[serde(rename = "customer_device_platform")] CustomerDevicePlatform(enums::CustomerDevicePlatform), #[serde(rename = "customer_device_type")] CustomerDeviceType(enums::CustomerDeviceType), #[serde(rename = "customer_device_display_size")] CustomerDeviceDisplaySize(enums::CustomerDeviceDisplaySize), #[serde(rename = "acquirer_country")] AcquirerCountry(enums::Country), #[serde(rename = "acquirer_fraud_rate")] AcquirerFraudRate(types::NumValue), } impl DirValue { pub fn get_key(&self) -> DirKey { let (kind, data) = match self { Self::PaymentMethod(_) => (DirKeyKind::PaymentMethod, None), Self::CardBin(_) => (DirKeyKind::CardBin, None), Self::RewardType(_) => (DirKeyKind::RewardType, None), Self::BusinessCountry(_) => (DirKeyKind::BusinessCountry, None), Self::BillingCountry(_) => (DirKeyKind::BillingCountry, None), Self::BankTransferType(_) => (DirKeyKind::BankTransferType, None), Self::UpiType(_) => (DirKeyKind::UpiType, None), Self::CardType(_) => (DirKeyKind::CardType, None), Self::CardNetwork(_) => (DirKeyKind::CardNetwork, None), Self::MetaData(met) => (DirKeyKind::MetaData, Some(met.key.clone())), Self::PayLaterType(_) => (DirKeyKind::PayLaterType, None), Self::WalletType(_) => (DirKeyKind::WalletType, None), Self::BankRedirectType(_) => (DirKeyKind::BankRedirectType, None), Self::CryptoType(_) => (DirKeyKind::CryptoType, None), Self::AuthenticationType(_) => (DirKeyKind::AuthenticationType, None), Self::CaptureMethod(_) => (DirKeyKind::CaptureMethod, None), Self::PaymentAmount(_) => (DirKeyKind::PaymentAmount, None), Self::PaymentCurrency(_) => (DirKeyKind::PaymentCurrency, None), Self::Connector(_) => (DirKeyKind::Connector, None), Self::BankDebitType(_) => (DirKeyKind::BankDebitType, None), Self::MandateAcceptanceType(_) => (DirKeyKind::MandateAcceptanceType, None), Self::MandateType(_) => (DirKeyKind::MandateType, None), Self::PaymentType(_) => (DirKeyKind::PaymentType, None), Self::BusinessLabel(_) => (DirKeyKind::BusinessLabel, None), Self::SetupFutureUsage(_) => (DirKeyKind::SetupFutureUsage, None), Self::CardRedirectType(_) => (DirKeyKind::CardRedirectType, None), Self::VoucherType(_) => (DirKeyKind::VoucherType, None), Self::GiftCardType(_) => (DirKeyKind::GiftCardType, None), Self::RealTimePaymentType(_) => (DirKeyKind::RealTimePaymentType, None), Self::OpenBankingType(_) => (DirKeyKind::OpenBankingType, None), Self::MobilePaymentType(_) => (DirKeyKind::MobilePaymentType, None), Self::IssuerName(_) => (DirKeyKind::IssuerName, None), Self::IssuerCountry(_) => (DirKeyKind::IssuerCountry, None), Self::CustomerDevicePlatform(_) => (DirKeyKind::CustomerDevicePlatform, None), Self::CustomerDeviceType(_) => (DirKeyKind::CustomerDeviceType, None), Self::CustomerDeviceDisplaySize(_) => (DirKeyKind::CustomerDeviceDisplaySize, None), Self::AcquirerCountry(_) => (DirKeyKind::AcquirerCountry, None), Self::AcquirerFraudRate(_) => (DirKeyKind::AcquirerFraudRate, None), }; DirKey::new(kind, data) } pub fn get_metadata_val(&self) -> Option<types::MetadataValue> { match self { Self::MetaData(val) => Some(val.clone()), Self::PaymentMethod(_) => None, Self::CardBin(_) => None, Self::CardType(_) => None, Self::CardNetwork(_) => None, Self::PayLaterType(_) => None, Self::WalletType(_) => None, Self::BankRedirectType(_) => None, Self::CryptoType(_) => None, Self::AuthenticationType(_) => None, Self::CaptureMethod(_) => None, Self::GiftCardType(_) => None, Self::PaymentAmount(_) => None, Self::PaymentCurrency(_) => None, Self::BusinessCountry(_) => None, Self::BillingCountry(_) => None, Self::Connector(_) => None, Self::BankTransferType(_) => None, Self::UpiType(_) => None, Self::BankDebitType(_) => None, Self::RewardType(_) => None, Self::VoucherType(_) => None, Self::MandateAcceptanceType(_) => None, Self::MandateType(_) => None, Self::PaymentType(_) => None, Self::BusinessLabel(_) => None, Self::SetupFutureUsage(_) => None, Self::CardRedirectType(_) => None, Self::RealTimePaymentType(_) => None, Self::OpenBankingType(_) => None, Self::MobilePaymentType(_) => None, Self::IssuerName(_) => None, Self::IssuerCountry(_) => None, Self::CustomerDevicePlatform(_) => None, Self::CustomerDeviceType(_) => None, Self::CustomerDeviceDisplaySize(_) => None, Self::AcquirerCountry(_) => None, Self::AcquirerFraudRate(_) => None, } } pub fn get_str_val(&self) -> Option<types::StrValue> { match self { Self::CardBin(val) => Some(val.clone()), Self::IssuerName(val) => Some(val.clone()), _ => None, } } pub fn get_num_value(&self) -> Option<types::NumValue> { match self { Self::PaymentAmount(val) => Some(val.clone()), Self::AcquirerFraudRate(val) => Some(val.clone()), _ => None, } } pub fn check_equality(v1: &Self, v2: &Self) -> bool { match (v1, v2) { (Self::PaymentMethod(pm1), Self::PaymentMethod(pm2)) => pm1 == pm2, (Self::CardType(ct1), Self::CardType(ct2)) => ct1 == ct2, (Self::CardNetwork(cn1), Self::CardNetwork(cn2)) => cn1 == cn2, (Self::MetaData(md1), Self::MetaData(md2)) => md1 == md2, (Self::PayLaterType(plt1), Self::PayLaterType(plt2)) => plt1 == plt2, (Self::WalletType(wt1), Self::WalletType(wt2)) => wt1 == wt2, (Self::BankDebitType(bdt1), Self::BankDebitType(bdt2)) => bdt1 == bdt2, (Self::BankRedirectType(brt1), Self::BankRedirectType(brt2)) => brt1 == brt2, (Self::BankTransferType(btt1), Self::BankTransferType(btt2)) => btt1 == btt2, (Self::GiftCardType(gct1), Self::GiftCardType(gct2)) => gct1 == gct2, (Self::CryptoType(ct1), Self::CryptoType(ct2)) => ct1 == ct2, (Self::AuthenticationType(at1), Self::AuthenticationType(at2)) => at1 == at2, (Self::CaptureMethod(cm1), Self::CaptureMethod(cm2)) => cm1 == cm2, (Self::PaymentCurrency(pc1), Self::PaymentCurrency(pc2)) => pc1 == pc2, (Self::BusinessCountry(c1), Self::BusinessCountry(c2)) => c1 == c2, (Self::BillingCountry(c1), Self::BillingCountry(c2)) => c1 == c2, (Self::PaymentType(pt1), Self::PaymentType(pt2)) => pt1 == pt2, (Self::MandateType(mt1), Self::MandateType(mt2)) => mt1 == mt2, (Self::MandateAcceptanceType(mat1), Self::MandateAcceptanceType(mat2)) => mat1 == mat2, (Self::RewardType(rt1), Self::RewardType(rt2)) => rt1 == rt2, (Self::RealTimePaymentType(rtp1), Self::RealTimePaymentType(rtp2)) => rtp1 == rtp2, (Self::Connector(c1), Self::Connector(c2)) => c1 == c2, (Self::BusinessLabel(bl1), Self::BusinessLabel(bl2)) => bl1 == bl2, (Self::SetupFutureUsage(sfu1), Self::SetupFutureUsage(sfu2)) => sfu1 == sfu2, (Self::UpiType(ut1), Self::UpiType(ut2)) => ut1 == ut2, (Self::VoucherType(vt1), Self::VoucherType(vt2)) => vt1 == vt2, (Self::CardRedirectType(crt1), Self::CardRedirectType(crt2)) => crt1 == crt2, (Self::IssuerName(n1), Self::IssuerName(n2)) => n1 == n2, (Self::IssuerCountry(c1), Self::IssuerCountry(c2)) => c1 == c2, (Self::CustomerDevicePlatform(p1), Self::CustomerDevicePlatform(p2)) => p1 == p2, (Self::CustomerDeviceType(t1), Self::CustomerDeviceType(t2)) => t1 == t2, (Self::CustomerDeviceDisplaySize(s1), Self::CustomerDeviceDisplaySize(s2)) => s1 == s2, (Self::AcquirerCountry(c1), Self::AcquirerCountry(c2)) => c1 == c2, (Self::AcquirerFraudRate(r1), Self::AcquirerFraudRate(r2)) => r1 == r2, _ => false, } } } #[cfg(feature = "payouts")] #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::EnumIter, strum::VariantNames, strum::EnumString, strum::EnumMessage, strum::EnumProperty, )] pub enum PayoutDirKeyKind { #[strum( serialize = "country", serialize = "business_country", detailed_message = "Country of the business unit", props(Category = "Merchant") )] #[serde(rename = "business_country", alias = "country")] BusinessCountry, #[strum( serialize = "billing_country", detailed_message = "Country of the billing address of the customer", props(Category = "Customer") )] #[serde(rename = "billing_country")] BillingCountry, #[strum( serialize = "business_label", detailed_message = "Identifier for business unit", props(Category = "Merchant") )] #[serde(rename = "business_label")] BusinessLabel, #[strum( serialize = "amount", detailed_message = "Value of the transaction", props(Category = "Order details") )] #[serde(rename = "amount")] PayoutAmount, #[strum( serialize = "currency", detailed_message = "Currency used for the payout", props(Category = "Order details") )] #[serde(rename = "currency")] PayoutCurrency, #[strum( serialize = "payment_method", detailed_message = "Different modes of payout - eg. cards, wallets, banks", props(Category = "Payout Methods") )] #[serde(rename = "payment_method")] PayoutType, #[strum( serialize = "wallet", detailed_message = "Supported types of Wallets for payouts", props(Category = "Payout Methods Type") )] #[serde(rename = "wallet")] WalletType, #[strum( serialize = "bank_transfer", detailed_message = "Supported types of Bank transfer types for payouts", props(Category = "Payout Methods Type") )] #[serde(rename = "bank_transfer")] BankTransferType, } #[cfg(feature = "payouts")] #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::VariantNames, )] pub enum PayoutDirValue { #[serde(rename = "business_country", alias = "country")] BusinessCountry(enums::Country), #[serde(rename = "billing_country")] BillingCountry(enums::Country), #[serde(rename = "business_label")] BusinessLabel(types::StrValue), #[serde(rename = "amount")] PayoutAmount(types::NumValue), #[serde(rename = "currency")] PayoutCurrency(enums::PaymentCurrency), #[serde(rename = "payment_method")] PayoutType(common_enums::PayoutType), #[serde(rename = "wallet")] WalletType(enums::PayoutWalletType), #[serde(rename = "bank_transfer")] BankTransferType(enums::PayoutBankTransferType), } #[derive(Debug, Clone)] pub enum DirComparisonLogic { NegativeConjunction, PositiveDisjunction, } #[derive(Debug, Clone)] pub struct DirComparison { pub values: Vec<DirValue>, pub logic: DirComparisonLogic, pub metadata: types::Metadata, } pub type DirIfCondition = Vec<DirComparison>; #[derive(Debug, Clone)] pub struct DirIfStatement { pub condition: DirIfCondition, pub nested: Option<Vec<DirIfStatement>>, } #[derive(Debug, Clone)] pub struct DirRule<O> { pub name: String, pub connector_selection: O, pub statements: Vec<DirIfStatement>, } #[derive(Debug, Clone)] pub struct DirProgram<O> { pub default_selection: O, pub rules: Vec<DirRule<O>>, pub metadata: types::Metadata, } #[cfg(test)] mod test { #![allow(clippy::expect_used)] use rustc_hash::FxHashMap; use strum::IntoEnumIterator; use super::*; #[test] fn test_consistent_dir_key_naming() { let mut key_names: FxHashMap<DirKeyKind, String> = FxHashMap::default(); for key in DirKeyKind::iter() { if matches!(key, DirKeyKind::Connector) { continue; } let json_str = if let DirKeyKind::MetaData = key { r#""metadata""#.to_string() } else { serde_json::to_string(&key).expect("JSON Serialization") }; let display_str = key.to_string(); assert_eq!( json_str.get(1..json_str.len() - 1).expect("Value metadata"), display_str ); key_names.insert(key, display_str); } let values = vec![ dirval!(PaymentMethod = Card), dirval!(CardBin s= "123456"), dirval!(CardType = Credit), dirval!(CardNetwork = Visa), dirval!(PayLaterType = Klarna), dirval!(WalletType = Paypal), dirval!(BankRedirectType = Sofort), dirval!(BankDebitType = Bacs), dirval!(CryptoType = CryptoCurrency), dirval!("" = "metadata"), dirval!(PaymentAmount = 100), dirval!(PaymentCurrency = USD), dirval!(CardRedirectType = Benefit), dirval!(AuthenticationType = ThreeDs), dirval!(CaptureMethod = Manual), dirval!(BillingCountry = UnitedStatesOfAmerica), dirval!(BusinessCountry = France), ]; for val in values { let json_val = serde_json::to_value(&val).expect("JSON Value Serialization"); let json_key = json_val .as_object() .expect("Serialized Object") .get("key") .expect("Object Key"); let value_str = json_key.as_str().expect("Value string"); let dir_key = val.get_key(); let key_name = key_names.get(&dir_key.kind).expect("Key name"); assert_eq!(key_name, value_str); } } #[cfg(feature = "ast_parser")] #[test] fn test_allowed_dir_keys() { use crate::types::DummyOutput; let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { payment_method = card } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let out = ast::lowering::lower_program::<DummyOutput>(program); assert!(out.is_ok()) } #[cfg(feature = "ast_parser")] #[test] fn test_not_allowed_dir_keys() { use crate::types::DummyOutput; let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { bank_debit = ach } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let out = ast::lowering::lower_program::<DummyOutput>(program); assert!(out.is_err()) } }
{ "crate": "euclid", "file": "crates/euclid/src/frontend/dir.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 5, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_euclid_1193789523621220134
clm
file
// Repository: hyperswitch // Crate: euclid // File: crates/euclid/src/frontend/ast.rs // Contains: 9 structs, 4 enums pub mod lowering; #[cfg(feature = "ast_parser")] pub mod parser; use common_enums::RoutableConnectors; use common_utils::types::MinorUnit; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::types::{DataType, Metadata}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct ConnectorChoice { pub connector: RoutableConnectors, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] pub struct MetadataValue { pub key: String, pub value: String, } /// Represents a value in the DSL #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum ValueType { /// Represents a number literal Number(MinorUnit), /// Represents an enum variant EnumVariant(String), /// Represents a Metadata variant MetadataVariant(MetadataValue), /// Represents a arbitrary String value StrValue(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<MinorUnit>), /// 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>), } impl ValueType { pub fn get_type(&self) -> DataType { match self { Self::Number(_) => DataType::Number, Self::StrValue(_) => DataType::StrValue, Self::MetadataVariant(_) => DataType::MetadataValue, Self::EnumVariant(_) => DataType::EnumVariant, Self::NumberComparisonArray(_) => DataType::Number, Self::NumberArray(_) => DataType::Number, Self::EnumVariantArray(_) => DataType::EnumVariant, } } } /// Represents a number comparison for "NumberComparisonArrayValue" #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct NumberComparison { pub comparison_type: ComparisonType, pub number: MinorUnit, } /// Conditional comparison type #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ComparisonType { Equal, NotEqual, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, } /// Represents a single comparison condition. #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct Comparison { /// The left hand side which will always be a domain input identifier like "payment.method.cardtype" pub lhs: String, /// The comparison operator pub comparison: ComparisonType, /// The value to compare against pub value: ValueType, /// Additional metadata that the Static Analyzer and Backend does not touch. /// This can be used to store useful information for the frontend and is required for communication /// between the static analyzer and the frontend. #[schema(value_type=HashMap<String, serde_json::Value>)] pub metadata: Metadata, } /// Represents all the conditions of an IF statement /// eg: /// /// ```text /// payment.method = card & payment.method.cardtype = debit & payment.method.network = diners /// ``` pub type IfCondition = Vec<Comparison>; /// Represents an IF statement with conditions and optional nested IF statements /// /// ```text /// payment.method = card { /// payment.method.cardtype = (credit, debit) { /// payment.method.network = (amex, rupay, diners) /// } /// } /// ``` #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct IfStatement { #[schema(value_type=Vec<Comparison>)] pub condition: IfCondition, pub nested: Option<Vec<IfStatement>>, } /// Represents a rule /// /// ```text /// rule_name: [stripe, adyen, checkout] /// { /// payment.method = card { /// payment.method.cardtype = (credit, debit) { /// payment.method.network = (amex, rupay, diners) /// } /// /// payment.method.cardtype = credit /// } /// } /// ``` #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] #[aliases(RuleConnectorSelection = Rule<ConnectorSelection>)] pub struct Rule<O> { pub name: String, #[serde(alias = "routingOutput")] pub connector_selection: O, pub statements: Vec<IfStatement>, } /// The program, having a default connector selection and /// a bunch of rules. Also can hold arbitrary metadata. #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] #[aliases(ProgramConnectorSelection = Program<ConnectorSelection>)] pub struct Program<O> { pub default_selection: O, #[schema(value_type=RuleConnectorSelection)] pub rules: Vec<Rule<O>>, #[schema(value_type=HashMap<String, serde_json::Value>)] pub metadata: Metadata, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct RoutableConnectorChoice { #[serde(skip)] pub choice_kind: RoutableChoiceKind, pub connector: RoutableConnectors, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub enum RoutableChoiceKind { OnlyConnector, #[default] FullStruct, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ConnectorVolumeSplit { pub connector: RoutableConnectorChoice, pub split: u8, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum ConnectorSelection { Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), }
{ "crate": "euclid", "file": "crates/euclid/src/frontend/ast.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 4, "num_structs": 9, "num_tables": null, "score": null, "total_crates": null }
file_euclid_8783638733498813857
clm
file
// Repository: hyperswitch // Crate: euclid // File: crates/euclid/src/backend/vir_interpreter.rs // Contains: 1 structs, 0 enums pub mod types; use std::fmt::Debug; use serde::{Deserialize, Serialize}; use crate::{ backend::{self, inputs, EuclidBackend}, frontend::{ ast, dir::{self, EuclidDirFilter}, vir, }, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct VirInterpreterBackend<O> { program: vir::ValuedProgram<O>, } impl<O> VirInterpreterBackend<O> where O: Clone, { #[inline] fn eval_comparison(comp: &vir::ValuedComparison, ctx: &types::Context) -> bool { match &comp.logic { vir::ValuedComparisonLogic::PositiveDisjunction => { comp.values.iter().any(|v| ctx.check_presence(v)) } vir::ValuedComparisonLogic::NegativeConjunction => { comp.values.iter().all(|v| !ctx.check_presence(v)) } } } #[inline] fn eval_condition(cond: &vir::ValuedIfCondition, ctx: &types::Context) -> bool { cond.iter().all(|comp| Self::eval_comparison(comp, ctx)) } fn eval_statement(stmt: &vir::ValuedIfStatement, ctx: &types::Context) -> bool { if Self::eval_condition(&stmt.condition, ctx) { { stmt.nested.as_ref().is_none_or(|nested_stmts| { nested_stmts.iter().any(|s| Self::eval_statement(s, ctx)) }) } } else { false } } fn eval_rule(rule: &vir::ValuedRule<O>, ctx: &types::Context) -> bool { rule.statements .iter() .any(|stmt| Self::eval_statement(stmt, ctx)) } fn eval_program( program: &vir::ValuedProgram<O>, ctx: &types::Context, ) -> backend::BackendOutput<O> { program .rules .iter() .find(|rule| Self::eval_rule(rule, ctx)) .map_or_else( || backend::BackendOutput { connector_selection: program.default_selection.clone(), rule_name: None, }, |rule| backend::BackendOutput { connector_selection: rule.connector_selection.clone(), rule_name: Some(rule.name.clone()), }, ) } } impl<O> EuclidBackend<O> for VirInterpreterBackend<O> where O: Clone + EuclidDirFilter, { type Error = types::VirInterpreterError; fn with_program(program: ast::Program<O>) -> Result<Self, Self::Error> { let dir_program = ast::lowering::lower_program(program) .map_err(types::VirInterpreterError::LoweringError)?; let vir_program = dir::lowering::lower_program(dir_program) .map_err(types::VirInterpreterError::LoweringError)?; Ok(Self { program: vir_program, }) } fn execute( &self, input: inputs::BackendInput, ) -> Result<backend::BackendOutput<O>, Self::Error> { let ctx = types::Context::from_input(input); Ok(Self::eval_program(&self.program, &ctx)) } } #[cfg(all(test, feature = "ast_parser"))] mod test { #![allow(clippy::expect_used)] use common_utils::types::MinorUnit; use rustc_hash::FxHashMap; use super::*; use crate::{enums, types::DummyOutput}; #[test] fn test_execution() { let program_str = r#" default: [ "stripe", "adyen"] rule_1: ["stripe"] { pay_later = klarna } rule_2: ["adyen"] { pay_later = affirm } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), card_bin: None, currency: enums::Currency::USD, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_2"); } #[test] fn test_payment_type() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { payment_type = setup_mandate } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: Some("123456".to_string()), authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: Some(enums::PaymentType::SetupMandate), }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_ppt_flow() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { payment_type = ppt_mandate } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: Some("123456".to_string()), authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: Some(enums::PaymentType::PptMandate), }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_mandate_type() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { mandate_type = single_use } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: Some("123456".to_string()), authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: Some(enums::MandateType::SingleUse), payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_mandate_acceptance_type() { let program_str = r#" default: ["stripe","adyen"] rule_1: ["stripe"] { mandate_acceptance_type = online } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: Some("123456".to_string()), authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: Some(enums::MandateAcceptanceType::Online), mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_card_bin() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { card_bin="123456" } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: Some("123456".to_string()), authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_payment_amount() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { amount = 32 } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: None, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_payment_method() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { payment_method = pay_later } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: None, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_future_usage() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { setup_future_usage = off_session } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: None, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: Some(enums::SetupFutureUsage::OffSession), }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_metadata_execution() { let program_str = r#" default: ["stripe"," adyen"] rule_1: ["stripe"] { "metadata_key" = "arbitrary meta" } "#; let mut meta_map = FxHashMap::default(); meta_map.insert("metadata_key".to_string(), "arbitrary meta".to_string()); let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: Some(meta_map), payment: inputs::PaymentInput { amount: MinorUnit::new(32), card_bin: None, currency: enums::Currency::USD, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_less_than_operator() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { amount>=123 } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp_greater = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(150), card_bin: None, currency: enums::Currency::USD, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let mut inp_equal = inp_greater.clone(); inp_equal.payment.amount = MinorUnit::new(123); let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result_greater = backend.execute(inp_greater).expect("Execution"); let result_equal = backend.execute(inp_equal).expect("Execution"); assert_eq!( result_equal.rule_name.expect("Rule Name").as_str(), "rule_1" ); assert_eq!( result_greater.rule_name.expect("Rule Name").as_str(), "rule_1" ); } #[test] fn test_greater_than_operator() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { amount<=123 } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp_lower = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(120), card_bin: None, currency: enums::Currency::USD, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let mut inp_equal = inp_lower.clone(); inp_equal.payment.amount = MinorUnit::new(123); let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result_equal = backend.execute(inp_equal).expect("Execution"); let result_lower = backend.execute(inp_lower).expect("Execution"); assert_eq!( result_equal.rule_name.expect("Rule Name").as_str(), "rule_1" ); assert_eq!( result_lower.rule_name.expect("Rule Name").as_str(), "rule_1" ); } }
{ "crate": "euclid", "file": "crates/euclid/src/backend/vir_interpreter.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_euclid_8948749691233662517
clm
file
// Repository: hyperswitch // Crate: euclid // File: crates/euclid/src/backend/inputs.rs // Contains: 7 structs, 0 enums use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use crate::{ enums, frontend::dir::enums::{CustomerDeviceDisplaySize, CustomerDevicePlatform, CustomerDeviceType}, }; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MandateData { pub mandate_acceptance_type: Option<enums::MandateAcceptanceType>, pub mandate_type: Option<enums::MandateType>, pub payment_type: Option<enums::PaymentType>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentMethodInput { pub payment_method: Option<enums::PaymentMethod>, pub payment_method_type: Option<enums::PaymentMethodType>, pub card_network: Option<enums::CardNetwork>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentInput { pub amount: common_utils::types::MinorUnit, pub currency: enums::Currency, pub authentication_type: Option<enums::AuthenticationType>, pub card_bin: Option<String>, pub capture_method: Option<enums::CaptureMethod>, pub business_country: Option<enums::Country>, pub billing_country: Option<enums::Country>, pub business_label: Option<String>, pub setup_future_usage: Option<enums::SetupFutureUsage>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AcquirerDataInput { pub country: Option<enums::Country>, pub fraud_rate: Option<f64>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CustomerDeviceDataInput { pub platform: Option<CustomerDevicePlatform>, pub device_type: Option<CustomerDeviceType>, pub display_size: Option<CustomerDeviceDisplaySize>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct IssuerDataInput { pub name: Option<String>, pub country: Option<enums::Country>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BackendInput { pub metadata: Option<FxHashMap<String, String>>, pub payment: PaymentInput, pub payment_method: PaymentMethodInput, pub acquirer_data: Option<AcquirerDataInput>, pub customer_device_data: Option<CustomerDeviceDataInput>, pub issuer_data: Option<IssuerDataInput>, pub mandate: MandateData, }
{ "crate": "euclid", "file": "crates/euclid/src/backend/inputs.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 7, "num_tables": null, "score": null, "total_crates": null }
file_euclid_8132309657013385036
clm
file
// Repository: hyperswitch // Crate: euclid // File: crates/euclid/src/backend/interpreter/types.rs // Contains: 1 structs, 1 enums use std::{collections::HashMap, fmt, ops::Deref, string::ToString}; use serde::Serialize; use crate::{backend::inputs, frontend::ast::ValueType, types::EuclidKey}; #[derive(Debug, Clone, Serialize, thiserror::Error)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum InterpreterErrorType { #[error("Invalid key received '{0}'")] InvalidKey(String), #[error("Invalid Comparison")] InvalidComparison, } #[derive(Debug, Clone, Serialize, thiserror::Error)] pub struct InterpreterError { pub error_type: InterpreterErrorType, pub metadata: HashMap<String, serde_json::Value>, } impl fmt::Display for InterpreterError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { InterpreterErrorType::fmt(&self.error_type, f) } } pub struct Context(HashMap<String, Option<ValueType>>); impl Deref for Context { type Target = HashMap<String, Option<ValueType>>; fn deref(&self) -> &Self::Target { &self.0 } } impl From<inputs::BackendInput> for Context { fn from(input: inputs::BackendInput) -> Self { let ctx = HashMap::<String, Option<ValueType>>::from_iter([ ( EuclidKey::PaymentMethod.to_string(), input .payment_method .payment_method .map(|pm| ValueType::EnumVariant(pm.to_string())), ), ( EuclidKey::PaymentMethodType.to_string(), input .payment_method .payment_method_type .map(|pt| ValueType::EnumVariant(pt.to_string())), ), ( EuclidKey::AuthenticationType.to_string(), input .payment .authentication_type .map(|at| ValueType::EnumVariant(at.to_string())), ), ( EuclidKey::CaptureMethod.to_string(), input .payment .capture_method .map(|cm| ValueType::EnumVariant(cm.to_string())), ), ( EuclidKey::PaymentAmount.to_string(), Some(ValueType::Number(input.payment.amount)), ), ( EuclidKey::PaymentCurrency.to_string(), Some(ValueType::EnumVariant(input.payment.currency.to_string())), ), ]); Self(ctx) } }
{ "crate": "euclid", "file": "crates/euclid/src/backend/interpreter/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_euclid_-1045407788725675256
clm
file
// Repository: hyperswitch // Crate: euclid // File: crates/euclid/src/dssa/state_machine.rs // Contains: 6 structs, 1 enums use super::types::EuclidAnalysable; use crate::{dssa::types, frontend::dir, types::Metadata}; #[derive(Debug, Clone, serde::Serialize, thiserror::Error)] #[serde(tag = "type", content = "info", rename_all = "snake_case")] pub enum StateMachineError { #[error("Index out of bounds: {0}")] IndexOutOfBounds(&'static str), } #[derive(Debug)] struct ComparisonStateMachine<'a> { values: &'a [dir::DirValue], logic: &'a dir::DirComparisonLogic, metadata: &'a Metadata, count: usize, ctx_idx: usize, } impl<'a> ComparisonStateMachine<'a> { #[inline] fn is_finished(&self) -> bool { self.count + 1 >= self.values.len() || matches!(self.logic, dir::DirComparisonLogic::NegativeConjunction) } #[inline] fn advance(&mut self) { if let dir::DirComparisonLogic::PositiveDisjunction = self.logic { self.count = (self.count + 1) % self.values.len(); } } #[inline] fn reset(&mut self) { self.count = 0; } #[inline] fn put(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> { if let dir::DirComparisonLogic::PositiveDisjunction = self.logic { *context .get_mut(self.ctx_idx) .ok_or(StateMachineError::IndexOutOfBounds( "in ComparisonStateMachine while indexing into context", ))? = types::ContextValue::assertion( self.values .get(self.count) .ok_or(StateMachineError::IndexOutOfBounds( "in ComparisonStateMachine while indexing into values", ))?, self.metadata, ); } Ok(()) } #[inline] fn push(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> { match self.logic { dir::DirComparisonLogic::PositiveDisjunction => { context.push(types::ContextValue::assertion( self.values .get(self.count) .ok_or(StateMachineError::IndexOutOfBounds( "in ComparisonStateMachine while pushing", ))?, self.metadata, )); } dir::DirComparisonLogic::NegativeConjunction => { context.push(types::ContextValue::negation(self.values, self.metadata)); } } Ok(()) } } #[derive(Debug)] struct ConditionStateMachine<'a> { state_machines: Vec<ComparisonStateMachine<'a>>, start_ctx_idx: usize, } impl<'a> ConditionStateMachine<'a> { fn new(condition: &'a [dir::DirComparison], start_idx: usize) -> Self { let mut machines = Vec::<ComparisonStateMachine<'a>>::with_capacity(condition.len()); let mut machine_idx = start_idx; for cond in condition { let machine = ComparisonStateMachine { values: &cond.values, logic: &cond.logic, metadata: &cond.metadata, count: 0, ctx_idx: machine_idx, }; machines.push(machine); machine_idx += 1; } Self { state_machines: machines, start_ctx_idx: start_idx, } } fn init(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> { for machine in &self.state_machines { machine.push(context)?; } Ok(()) } #[inline] fn destroy(&self, context: &mut types::ConjunctiveContext<'a>) { context.truncate(self.start_ctx_idx); } #[inline] fn is_finished(&self) -> bool { !self .state_machines .iter() .any(|machine| !machine.is_finished()) } #[inline] fn get_next_ctx_idx(&self) -> usize { self.start_ctx_idx + self.state_machines.len() } fn advance( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { for machine in self.state_machines.iter_mut().rev() { if machine.is_finished() { machine.reset(); machine.put(context)?; } else { machine.advance(); machine.put(context)?; break; } } Ok(()) } } #[derive(Debug)] struct IfStmtStateMachine<'a> { condition_machine: ConditionStateMachine<'a>, nested: Vec<&'a dir::DirIfStatement>, nested_idx: usize, } impl<'a> IfStmtStateMachine<'a> { fn new(stmt: &'a dir::DirIfStatement, ctx_start_idx: usize) -> Self { let condition_machine = ConditionStateMachine::new(&stmt.condition, ctx_start_idx); let nested: Vec<&'a dir::DirIfStatement> = match &stmt.nested { None => Vec::new(), Some(nested_stmts) => nested_stmts.iter().collect(), }; Self { condition_machine, nested, nested_idx: 0, } } fn init( &self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<Option<Self>, StateMachineError> { self.condition_machine.init(context)?; Ok(self .nested .first() .map(|nested| Self::new(nested, self.condition_machine.get_next_ctx_idx()))) } #[inline] fn is_finished(&self) -> bool { self.nested_idx + 1 >= self.nested.len() } #[inline] fn is_condition_machine_finished(&self) -> bool { self.condition_machine.is_finished() } #[inline] fn destroy(&self, context: &mut types::ConjunctiveContext<'a>) { self.condition_machine.destroy(context); } #[inline] fn advance_condition_machine( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { self.condition_machine.advance(context)?; Ok(()) } fn advance(&mut self) -> Result<Option<Self>, StateMachineError> { if self.nested.is_empty() { Ok(None) } else { self.nested_idx = (self.nested_idx + 1) % self.nested.len(); Ok(Some(Self::new( self.nested .get(self.nested_idx) .ok_or(StateMachineError::IndexOutOfBounds( "in IfStmtStateMachine while advancing", ))?, self.condition_machine.get_next_ctx_idx(), ))) } } } #[derive(Debug)] struct RuleStateMachine<'a> { connector_selection_data: &'a [(dir::DirValue, Metadata)], connectors_added: bool, if_stmt_machines: Vec<IfStmtStateMachine<'a>>, running_stack: Vec<IfStmtStateMachine<'a>>, } impl<'a> RuleStateMachine<'a> { fn new<O>( rule: &'a dir::DirRule<O>, connector_selection_data: &'a [(dir::DirValue, Metadata)], ) -> Self { let mut if_stmt_machines: Vec<IfStmtStateMachine<'a>> = Vec::with_capacity(rule.statements.len()); for stmt in rule.statements.iter().rev() { if_stmt_machines.push(IfStmtStateMachine::new( stmt, connector_selection_data.len(), )); } Self { connector_selection_data, connectors_added: false, if_stmt_machines, running_stack: Vec::new(), } } fn is_finished(&self) -> bool { self.if_stmt_machines.is_empty() && self.running_stack.is_empty() } fn init_next( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { if self.if_stmt_machines.is_empty() || !self.running_stack.is_empty() { return Ok(()); } if !self.connectors_added { for (dir_val, metadata) in self.connector_selection_data { context.push(types::ContextValue::assertion(dir_val, metadata)); } self.connectors_added = true; } context.truncate(self.connector_selection_data.len()); if let Some(mut next_running) = self.if_stmt_machines.pop() { while let Some(nested_running) = next_running.init(context)? { self.running_stack.push(next_running); next_running = nested_running; } self.running_stack.push(next_running); } Ok(()) } fn advance( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { let mut condition_machines_finished = true; for stmt_machine in self.running_stack.iter_mut().rev() { if !stmt_machine.is_condition_machine_finished() { condition_machines_finished = false; stmt_machine.advance_condition_machine(context)?; break; } else { stmt_machine.advance_condition_machine(context)?; } } if !condition_machines_finished { return Ok(()); } let mut maybe_next_running: Option<IfStmtStateMachine<'a>> = None; while let Some(last) = self.running_stack.last_mut() { if !last.is_finished() { maybe_next_running = last.advance()?; break; } else { last.destroy(context); self.running_stack.pop(); } } if let Some(mut next_running) = maybe_next_running { while let Some(nested_running) = next_running.init(context)? { self.running_stack.push(next_running); next_running = nested_running; } self.running_stack.push(next_running); } else { self.init_next(context)?; } Ok(()) } } #[derive(Debug)] pub struct RuleContextManager<'a> { context: types::ConjunctiveContext<'a>, machine: RuleStateMachine<'a>, init: bool, } impl<'a> RuleContextManager<'a> { pub fn new<O>( rule: &'a dir::DirRule<O>, connector_selection_data: &'a [(dir::DirValue, Metadata)], ) -> Self { Self { context: Vec::new(), machine: RuleStateMachine::new(rule, connector_selection_data), init: false, } } pub fn advance(&mut self) -> Result<Option<&types::ConjunctiveContext<'a>>, StateMachineError> { if !self.init { self.init = true; self.machine.init_next(&mut self.context)?; Ok(Some(&self.context)) } else if self.machine.is_finished() { Ok(None) } else { self.machine.advance(&mut self.context)?; if self.machine.is_finished() { Ok(None) } else { Ok(Some(&self.context)) } } } pub fn advance_mut( &mut self, ) -> Result<Option<&mut types::ConjunctiveContext<'a>>, StateMachineError> { if !self.init { self.init = true; self.machine.init_next(&mut self.context)?; Ok(Some(&mut self.context)) } else if self.machine.is_finished() { Ok(None) } else { self.machine.advance(&mut self.context)?; if self.machine.is_finished() { Ok(None) } else { Ok(Some(&mut self.context)) } } } } #[derive(Debug)] pub struct ProgramStateMachine<'a> { rule_machines: Vec<RuleStateMachine<'a>>, current_rule_machine: Option<RuleStateMachine<'a>>, is_init: bool, } impl<'a> ProgramStateMachine<'a> { pub fn new<O>( program: &'a dir::DirProgram<O>, connector_selection_data: &'a [Vec<(dir::DirValue, Metadata)>], ) -> Self { let mut rule_machines: Vec<RuleStateMachine<'a>> = program .rules .iter() .zip(connector_selection_data.iter()) .rev() .map(|(rule, connector_selection_data)| { RuleStateMachine::new(rule, connector_selection_data) }) .collect(); Self { current_rule_machine: rule_machines.pop(), rule_machines, is_init: false, } } pub fn is_finished(&self) -> bool { self.current_rule_machine .as_ref() .is_none_or(|rsm| rsm.is_finished()) && self.rule_machines.is_empty() } pub fn init( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { if !self.is_init { if let Some(rsm) = self.current_rule_machine.as_mut() { rsm.init_next(context)?; } self.is_init = true; } Ok(()) } pub fn advance( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { if self .current_rule_machine .as_ref() .is_none_or(|rsm| rsm.is_finished()) { self.current_rule_machine = self.rule_machines.pop(); context.clear(); if let Some(rsm) = self.current_rule_machine.as_mut() { rsm.init_next(context)?; } } else if let Some(rsm) = self.current_rule_machine.as_mut() { rsm.advance(context)?; } Ok(()) } } pub struct AnalysisContextManager<'a> { context: types::ConjunctiveContext<'a>, machine: ProgramStateMachine<'a>, init: bool, } impl<'a> AnalysisContextManager<'a> { pub fn new<O>( program: &'a dir::DirProgram<O>, connector_selection_data: &'a [Vec<(dir::DirValue, Metadata)>], ) -> Self { let machine = ProgramStateMachine::new(program, connector_selection_data); let context: types::ConjunctiveContext<'a> = Vec::new(); Self { context, machine, init: false, } } pub fn advance(&mut self) -> Result<Option<&types::ConjunctiveContext<'a>>, StateMachineError> { if !self.init { self.init = true; self.machine.init(&mut self.context)?; Ok(Some(&self.context)) } else if self.machine.is_finished() { Ok(None) } else { self.machine.advance(&mut self.context)?; if self.machine.is_finished() { Ok(None) } else { Ok(Some(&self.context)) } } } } pub fn make_connector_selection_data<O: EuclidAnalysable>( program: &dir::DirProgram<O>, ) -> Vec<Vec<(dir::DirValue, Metadata)>> { program .rules .iter() .map(|rule| { rule.connector_selection .get_dir_value_for_analysis(rule.name.clone()) }) .collect() } #[cfg(all(test, feature = "ast_parser"))] mod tests { #![allow(clippy::expect_used)] use super::*; use crate::{dirval, frontend::ast, types::DummyOutput}; #[test] fn test_correct_contexts() { let program_str = r#" default: ["stripe", "adyen"] stripe_first: ["stripe", "adyen"] { payment_method = wallet { payment_method = (card, bank_redirect) { currency = USD currency = GBP } payment_method = pay_later { capture_method = automatic capture_method = manual } } payment_method = card { payment_method = (card, bank_redirect) & capture_method = (automatic, manual) { currency = (USD, GBP) } } } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let lowered = ast::lowering::lower_program(program).expect("Lowering"); let selection_data = make_connector_selection_data(&lowered); let mut state_machine = ProgramStateMachine::new(&lowered, &selection_data); let mut ctx: types::ConjunctiveContext<'_> = Vec::new(); state_machine.init(&mut ctx).expect("State machine init"); let expected_contexts: Vec<Vec<dir::DirValue>> = vec![ vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = Card), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = BankRedirect), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = Card), dirval!(PaymentCurrency = GBP), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = BankRedirect), dirval!(PaymentCurrency = GBP), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = PayLater), dirval!(CaptureMethod = Automatic), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = PayLater), dirval!(CaptureMethod = Manual), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Card), dirval!(CaptureMethod = Automatic), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Card), dirval!(CaptureMethod = Automatic), dirval!(PaymentCurrency = GBP), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Card), dirval!(CaptureMethod = Manual), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Card), dirval!(CaptureMethod = Manual), dirval!(PaymentCurrency = GBP), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = BankRedirect), dirval!(CaptureMethod = Automatic), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = BankRedirect), dirval!(CaptureMethod = Automatic), dirval!(PaymentCurrency = GBP), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = BankRedirect), dirval!(CaptureMethod = Manual), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = BankRedirect), dirval!(CaptureMethod = Manual), dirval!(PaymentCurrency = GBP), ], ]; let mut expected_idx = 0usize; while !state_machine.is_finished() { let values = ctx .iter() .flat_map(|c| match c.value { types::CtxValueKind::Assertion(val) => vec![val], types::CtxValueKind::Negation(vals) => vals.iter().collect(), }) .collect::<Vec<&dir::DirValue>>(); assert_eq!( values, expected_contexts .get(expected_idx) .expect("Error deriving contexts") .iter() .collect::<Vec<&dir::DirValue>>() ); expected_idx += 1; state_machine .advance(&mut ctx) .expect("State Machine advance"); } assert_eq!(expected_idx, 14); let mut ctx_manager = AnalysisContextManager::new(&lowered, &selection_data); expected_idx = 0; while let Some(ctx) = ctx_manager.advance().expect("Context Manager Context") { let values = ctx .iter() .flat_map(|c| match c.value { types::CtxValueKind::Assertion(val) => vec![val], types::CtxValueKind::Negation(vals) => vals.iter().collect(), }) .collect::<Vec<&dir::DirValue>>(); assert_eq!( values, expected_contexts .get(expected_idx) .expect("Error deriving contexts") .iter() .collect::<Vec<&dir::DirValue>>() ); expected_idx += 1; } assert_eq!(expected_idx, 14); } }
{ "crate": "euclid", "file": "crates/euclid/src/dssa/state_machine.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 6, "num_tables": null, "score": null, "total_crates": null }
file_euclid_-724174007207289724
clm
file
// Repository: hyperswitch // Crate: euclid // File: crates/euclid/src/dssa/types.rs // Contains: 3 structs, 4 enums use std::{collections::HashMap, fmt}; use serde::Serialize; use crate::{ dssa::{self, graph}, frontend::{ast, dir}, types::{DataType, EuclidValue, Metadata}, }; pub trait EuclidAnalysable: Sized { fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(dir::DirValue, Metadata)>; } #[derive(Debug, Clone)] pub enum CtxValueKind<'a> { Assertion(&'a dir::DirValue), Negation(&'a [dir::DirValue]), } impl CtxValueKind<'_> { pub fn get_assertion(&self) -> Option<&dir::DirValue> { if let Self::Assertion(val) = self { Some(val) } else { None } } pub fn get_negation(&self) -> Option<&[dir::DirValue]> { if let Self::Negation(vals) = self { Some(vals) } else { None } } pub fn get_key(&self) -> Option<dir::DirKey> { match self { Self::Assertion(val) => Some(val.get_key()), Self::Negation(vals) => vals.first().map(|v| (*v).get_key()), } } } #[derive(Debug, Clone)] pub struct ContextValue<'a> { pub value: CtxValueKind<'a>, pub metadata: &'a Metadata, } impl<'a> ContextValue<'a> { #[inline] pub fn assertion(value: &'a dir::DirValue, metadata: &'a Metadata) -> Self { Self { value: CtxValueKind::Assertion(value), metadata, } } #[inline] pub fn negation(values: &'a [dir::DirValue], metadata: &'a Metadata) -> Self { Self { value: CtxValueKind::Negation(values), metadata, } } } pub type ConjunctiveContext<'a> = Vec<ContextValue<'a>>; #[derive(Clone, Serialize)] pub enum AnalyzeResult { AllOk, } #[derive(Debug, Clone, Serialize, thiserror::Error)] pub struct AnalysisError { #[serde(flatten)] pub error_type: AnalysisErrorType, pub metadata: Metadata, } impl fmt::Display for AnalysisError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.error_type.fmt(f) } } #[derive(Debug, Clone, Serialize)] pub struct ValueData { pub value: dir::DirValue, pub metadata: Metadata, } #[derive(Debug, Clone, Serialize, thiserror::Error)] #[serde(tag = "type", content = "info", rename_all = "snake_case")] pub enum AnalysisErrorType { #[error("Invalid program key given: '{0}'")] InvalidKey(String), #[error("Invalid variant '{got}' received for key '{key}'")] InvalidVariant { key: String, expected: Vec<String>, got: String, }, #[error( "Invalid data type for value '{}' (expected {expected}, got {got})", key )] InvalidType { key: String, expected: DataType, got: DataType, }, #[error("Invalid comparison '{operator:?}' for value type {value_type}")] InvalidComparison { operator: ast::ComparisonType, value_type: DataType, }, #[error("Invalid value received for length as '{value}: {:?}'", message)] InvalidValue { key: dir::DirKeyKind, value: String, message: Option<String>, }, #[error("Conflicting assertions received for key '{}'", .key.kind)] ConflictingAssertions { key: dir::DirKey, values: Vec<ValueData>, }, #[error("Key '{}' exhaustively negated", .key.kind)] ExhaustiveNegation { key: dir::DirKey, metadata: Vec<Metadata>, }, #[error("The condition '{value}' was asserted and negated in the same condition")] NegatedAssertion { value: dir::DirValue, assertion_metadata: Metadata, negation_metadata: Metadata, }, #[error("Graph analysis error: {0:#?}")] GraphAnalysis( graph::AnalysisError<dir::DirValue>, hyperswitch_constraint_graph::Memoization<dir::DirValue>, ), #[error("State machine error")] StateMachine(dssa::state_machine::StateMachineError), #[error("Unsupported program key '{0}'")] UnsupportedProgramKey(dir::DirKeyKind), #[error("Ran into an unimplemented feature")] NotImplemented, #[error("The payment method type is not supported under the payment method")] NotSupported, } #[derive(Debug, Clone)] pub enum ValueType { EnumVariants(Vec<EuclidValue>), Number, } impl EuclidAnalysable for common_enums::AuthenticationType { fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(dir::DirValue, Metadata)> { let auth = self.to_string(); let dir_value = match self { Self::ThreeDs => dir::DirValue::AuthenticationType(Self::ThreeDs), Self::NoThreeDs => dir::DirValue::AuthenticationType(Self::NoThreeDs), }; vec![( dir_value, HashMap::from_iter([( "AUTHENTICATION_TYPE".to_string(), serde_json::json!({ "rule_name": rule_name, "Authentication_type": auth, }), )]), )] } }
{ "crate": "euclid", "file": "crates/euclid/src/dssa/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 4, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_euclid_-4063355879084004753
clm
file
// Repository: hyperswitch // Crate: euclid // File: crates/euclid/src/dssa/graph.rs // Contains: 1 structs, 1 enums use std::{fmt::Debug, sync::Weak}; use hyperswitch_constraint_graph as cgraph; use rustc_hash::{FxHashMap, FxHashSet}; use crate::{ dssa::types, frontend::dir, types::{DataType, Metadata}, }; pub mod euclid_graph_prelude { pub use hyperswitch_constraint_graph as cgraph; pub use rustc_hash::{FxHashMap, FxHashSet}; pub use strum::EnumIter; pub use crate::{ dssa::graph::*, frontend::dir::{enums::*, DirKey, DirKeyKind, DirValue}, types::*, }; } impl cgraph::KeyNode for dir::DirKey {} impl cgraph::NodeViz for dir::DirKey { fn viz(&self) -> String { self.kind.to_string() } } impl cgraph::ValueNode for dir::DirValue { type Key = dir::DirKey; fn get_key(&self) -> Self::Key { Self::get_key(self) } } impl cgraph::NodeViz for dir::DirValue { fn viz(&self) -> String { match self { Self::PaymentMethod(pm) => pm.to_string(), Self::CardBin(bin) => bin.value.clone(), Self::CardType(ct) => ct.to_string(), Self::CardNetwork(cn) => cn.to_string(), Self::PayLaterType(plt) => plt.to_string(), Self::WalletType(wt) => wt.to_string(), Self::UpiType(ut) => ut.to_string(), Self::BankTransferType(btt) => btt.to_string(), Self::BankRedirectType(brt) => brt.to_string(), Self::BankDebitType(bdt) => bdt.to_string(), Self::CryptoType(ct) => ct.to_string(), Self::RewardType(rt) => rt.to_string(), Self::PaymentAmount(amt) => amt.number.to_string(), Self::PaymentCurrency(curr) => curr.to_string(), Self::AuthenticationType(at) => at.to_string(), Self::CaptureMethod(cm) => cm.to_string(), Self::BusinessCountry(bc) => bc.to_string(), Self::BillingCountry(bc) => bc.to_string(), Self::Connector(conn) => conn.connector.to_string(), Self::MetaData(mv) => format!("[{} = {}]", mv.key, mv.value), Self::MandateAcceptanceType(mat) => mat.to_string(), Self::MandateType(mt) => mt.to_string(), Self::PaymentType(pt) => pt.to_string(), Self::VoucherType(vt) => vt.to_string(), Self::GiftCardType(gct) => gct.to_string(), Self::BusinessLabel(bl) => bl.value.to_string(), Self::SetupFutureUsage(sfu) => sfu.to_string(), Self::CardRedirectType(crt) => crt.to_string(), Self::RealTimePaymentType(rtpt) => rtpt.to_string(), Self::OpenBankingType(ob) => ob.to_string(), Self::MobilePaymentType(mpt) => mpt.to_string(), Self::IssuerName(issuer_name) => issuer_name.value.clone(), Self::IssuerCountry(issuer_country) => issuer_country.to_string(), Self::CustomerDevicePlatform(customer_device_platform) => { customer_device_platform.to_string() } Self::CustomerDeviceType(customer_device_type) => customer_device_type.to_string(), Self::CustomerDeviceDisplaySize(customer_device_display_size) => { customer_device_display_size.to_string() } Self::AcquirerCountry(acquirer_country) => acquirer_country.to_string(), Self::AcquirerFraudRate(acquirer_fraud_rate) => acquirer_fraud_rate.number.to_string(), } } } #[derive(Debug, Clone, serde::Serialize)] #[serde(tag = "type", content = "details", rename_all = "snake_case")] pub enum AnalysisError<V: cgraph::ValueNode> { Graph(cgraph::GraphError<V>), AssertionTrace { trace: Weak<cgraph::AnalysisTrace<V>>, metadata: Metadata, }, NegationTrace { trace: Weak<cgraph::AnalysisTrace<V>>, metadata: Vec<Metadata>, }, } impl<V: cgraph::ValueNode> AnalysisError<V> { fn assertion_from_graph_error(metadata: &Metadata, graph_error: cgraph::GraphError<V>) -> Self { match graph_error { cgraph::GraphError::AnalysisError(trace) => Self::AssertionTrace { trace, metadata: metadata.clone(), }, other => Self::Graph(other), } } fn negation_from_graph_error( metadata: Vec<&Metadata>, graph_error: cgraph::GraphError<V>, ) -> Self { match graph_error { cgraph::GraphError::AnalysisError(trace) => Self::NegationTrace { trace, metadata: metadata.iter().map(|m| (*m).clone()).collect(), }, other => Self::Graph(other), } } } #[derive(Debug)] pub struct AnalysisContext { keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>>, } impl AnalysisContext { pub fn from_dir_values(vals: impl IntoIterator<Item = dir::DirValue>) -> Self { let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> = FxHashMap::default(); for dir_val in vals { let key = dir_val.get_key(); let set = keywise_values.entry(key).or_default(); set.insert(dir_val); } Self { keywise_values } } pub fn insert(&mut self, value: dir::DirValue) { self.keywise_values .entry(value.get_key()) .or_default() .insert(value); } pub fn remove(&mut self, value: dir::DirValue) { let set = self.keywise_values.entry(value.get_key()).or_default(); set.remove(&value); if set.is_empty() { self.keywise_values.remove(&value.get_key()); } } } impl cgraph::CheckingContext for AnalysisContext { type Value = dir::DirValue; fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self where L: Into<Self::Value>, { let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> = FxHashMap::default(); for dir_val in vals.into_iter().map(L::into) { let key = dir_val.get_key(); let set = keywise_values.entry(key).or_default(); set.insert(dir_val); } Self { keywise_values } } fn check_presence( &self, value: &cgraph::NodeValue<dir::DirValue>, strength: cgraph::Strength, ) -> bool { match value { cgraph::NodeValue::Key(k) => { self.keywise_values.contains_key(k) || matches!(strength, cgraph::Strength::Weak) } cgraph::NodeValue::Value(val) => { let key = val.get_key(); let value_set = if let Some(set) = self.keywise_values.get(&key) { set } else { return matches!(strength, cgraph::Strength::Weak); }; match key.kind.get_type() { DataType::EnumVariant | DataType::StrValue | DataType::MetadataValue => { value_set.contains(val) } DataType::Number => val.get_num_value().is_some_and(|num_val| { value_set.iter().any(|ctx_val| { ctx_val .get_num_value() .is_some_and(|ctx_num_val| num_val.fits(&ctx_num_val)) }) }), } } } } fn get_values_by_key( &self, key: &<Self::Value as cgraph::ValueNode>::Key, ) -> Option<Vec<Self::Value>> { self.keywise_values .get(key) .map(|set| set.iter().cloned().collect()) } } pub trait CgraphExt { fn key_analysis( &self, key: dir::DirKey, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>>; fn value_analysis( &self, val: dir::DirValue, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>>; fn check_value_validity( &self, val: dir::DirValue, analysis_ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<bool, cgraph::GraphError<dir::DirValue>>; fn key_value_analysis( &self, val: dir::DirValue, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>>; fn assertion_analysis( &self, positive_ctx: &[(&dir::DirValue, &Metadata)], analysis_ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>>; fn negation_analysis( &self, negative_ctx: &[(&[dir::DirValue], &Metadata)], analysis_ctx: &mut AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>>; fn perform_context_analysis( &self, ctx: &types::ConjunctiveContext<'_>, memo: &mut cgraph::Memoization<dir::DirValue>, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>>; } impl CgraphExt for cgraph::ConstraintGraph<dir::DirValue> { fn key_analysis( &self, key: dir::DirKey, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>> { self.value_map .get(&cgraph::NodeValue::Key(key)) .map_or(Ok(()), |node_id| { self.check_node( ctx, *node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, memo, cycle_map, domains, ) }) } fn value_analysis( &self, val: dir::DirValue, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>> { self.value_map .get(&cgraph::NodeValue::Value(val)) .map_or(Ok(()), |node_id| { self.check_node( ctx, *node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, memo, cycle_map, domains, ) }) } fn check_value_validity( &self, val: dir::DirValue, analysis_ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<bool, cgraph::GraphError<dir::DirValue>> { let maybe_node_id = self.value_map.get(&cgraph::NodeValue::Value(val)); let node_id = if let Some(nid) = maybe_node_id { nid } else { return Ok(false); }; let result = self.check_node( analysis_ctx, *node_id, cgraph::Relation::Positive, cgraph::Strength::Weak, memo, cycle_map, domains, ); match result { Ok(_) => Ok(true), Err(e) => { e.get_analysis_trace()?; Ok(false) } } } fn key_value_analysis( &self, val: dir::DirValue, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>> { self.key_analysis(val.get_key(), ctx, memo, cycle_map, domains) .and_then(|_| self.value_analysis(val, ctx, memo, cycle_map, domains)) } fn assertion_analysis( &self, positive_ctx: &[(&dir::DirValue, &Metadata)], analysis_ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>> { positive_ctx.iter().try_for_each(|(value, metadata)| { self.key_value_analysis((*value).clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| AnalysisError::assertion_from_graph_error(metadata, e)) }) } fn negation_analysis( &self, negative_ctx: &[(&[dir::DirValue], &Metadata)], analysis_ctx: &mut AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>> { let mut keywise_metadata: FxHashMap<dir::DirKey, Vec<&Metadata>> = FxHashMap::default(); let mut keywise_negation: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> = FxHashMap::default(); for (values, metadata) in negative_ctx { let mut metadata_added = false; for dir_value in *values { if !metadata_added { keywise_metadata .entry(dir_value.get_key()) .or_default() .push(metadata); metadata_added = true; } keywise_negation .entry(dir_value.get_key()) .or_default() .insert(dir_value); } } for (key, negation_set) in keywise_negation { let all_metadata = keywise_metadata.remove(&key).unwrap_or_default(); let first_metadata = all_metadata.first().copied().cloned().unwrap_or_default(); self.key_analysis(key.clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| AnalysisError::assertion_from_graph_error(&first_metadata, e))?; let mut value_set = if let Some(set) = key.kind.get_value_set() { set } else { continue; }; value_set.retain(|v| !negation_set.contains(v)); for value in value_set { analysis_ctx.insert(value.clone()); self.value_analysis(value.clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| { AnalysisError::negation_from_graph_error(all_metadata.clone(), e) })?; analysis_ctx.remove(value); } } Ok(()) } fn perform_context_analysis( &self, ctx: &types::ConjunctiveContext<'_>, memo: &mut cgraph::Memoization<dir::DirValue>, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>> { let mut analysis_ctx = AnalysisContext::from_dir_values( ctx.iter() .filter_map(|ctx_val| ctx_val.value.get_assertion().cloned()), ); let positive_ctx = ctx .iter() .filter_map(|ctx_val| { ctx_val .value .get_assertion() .map(|val| (val, ctx_val.metadata)) }) .collect::<Vec<_>>(); self.assertion_analysis( &positive_ctx, &analysis_ctx, memo, &mut cgraph::CycleCheck::new(), domains, )?; let negative_ctx = ctx .iter() .filter_map(|ctx_val| { ctx_val .value .get_negation() .map(|vals| (vals, ctx_val.metadata)) }) .collect::<Vec<_>>(); self.negation_analysis( &negative_ctx, &mut analysis_ctx, memo, &mut cgraph::CycleCheck::new(), domains, )?; Ok(()) } } #[cfg(test)] mod test { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::ops::Deref; use euclid_macros::knowledge; use hyperswitch_constraint_graph::CycleCheck; use super::*; use crate::{dirval, frontend::dir::enums}; #[test] fn test_strong_positive_relation_success() { let graph = knowledge! { PaymentMethod(Card) ->> CaptureMethod(Automatic); PaymentMethod(not Wallet) & PaymentMethod(not PayLater) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Card), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_strong_positive_relation_failure() { let graph = knowledge! { PaymentMethod(Card) ->> CaptureMethod(Automatic); PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([dirval!(CaptureMethod = Automatic)]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_strong_negative_relation_success() { let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Card), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_strong_negative_relation_failure() { let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Wallet), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_normal_one_of_failure() { let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(Wallet) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = PayLater), ]), memo, &mut CycleCheck::new(), None, ); assert!(matches!( *Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected Arc"), cgraph::AnalysisTrace::Value { predecessors: Some(cgraph::error::ValueTracePredecessor::OneOf(_)), .. } )); } #[test] fn test_all_aggregator_success() { let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(PaymentMethod = Card), dirval!(CaptureMethod = Automatic), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_all_aggregator_failure() { let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = PayLater), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_all_aggregator_mandatory_failure() { let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; let mut memo = cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = PayLater), ]), &mut memo, &mut CycleCheck::new(), None, ); assert!(matches!( *Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected Arc"), cgraph::AnalysisTrace::Value { predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(_)), .. } )); } #[test] fn test_in_aggregator_success() { let graph = knowledge! { PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Wallet), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_in_aggregator_failure() { let graph = knowledge! { PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = PayLater), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_not_in_aggregator_success() { let graph = knowledge! { PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = PayLater), dirval!(PaymentMethod = BankRedirect), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_not_in_aggregator_failure() { let graph = knowledge! { PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = PayLater), dirval!(PaymentMethod = BankRedirect), dirval!(PaymentMethod = Card), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_in_aggregator_failure_trace() { let graph = knowledge! { PaymentMethod(in [Card, Wallet]) ->> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = PayLater), ]), memo, &mut CycleCheck::new(), None, ); if let cgraph::AnalysisTrace::Value { predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(agg_error)), .. } = Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected arc") .deref() { assert!(matches!( *Weak::upgrade(agg_error.deref()).expect("Expected Arc"), cgraph::AnalysisTrace::InAggregation { found: Some(dir::DirValue::PaymentMethod(enums::PaymentMethod::PayLater)), .. } )); } else { panic!("Failed unwrapping OnlyInAggregation trace from AnalysisTrace"); } } #[test] fn test_memoization_in_kgraph() { let mut builder = cgraph::ConstraintGraphBuilder::new(); let _node_1 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), None, None::<()>, ); let _node_2 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::BillingCountry(enums::BillingCountry::India)), None, None::<()>, ); let _node_3 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::BusinessCountry( enums::BusinessCountry::UnitedStatesOfAmerica, )), None, None::<()>, ); let mut memo = cgraph::Memoization::new(); let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( _node_1, _node_2, cgraph::Strength::Strong, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_2 = builder .make_edge( _node_2, _node_3, cgraph::Strength::Strong, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to an edge"); let graph = builder.build(); let _result = graph.key_value_analysis( dirval!(BusinessCountry = UnitedStatesOfAmerica), &AnalysisContext::from_dir_values([ dirval!(PaymentMethod = Wallet), dirval!(BillingCountry = India), dirval!(BusinessCountry = UnitedStatesOfAmerica), ]), &mut memo, &mut cycle_map, None, ); let _answer = memo .get(&( _node_3, cgraph::Relation::Positive, cgraph::Strength::Strong, )) .expect("Memoization not workng"); matches!(_answer, Ok(())); } #[test] fn test_cycle_resolution_in_graph() { let mut builder = cgraph::ConstraintGraphBuilder::new(); let _node_1 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), None, None::<()>, ); let _node_2 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), None, None::<()>, ); let mut memo = cgraph::Memoization::new(); let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( _node_1, _node_2, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_2 = builder .make_edge( _node_2, _node_1, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to an edge"); let graph = builder.build(); let _result = graph.key_value_analysis( dirval!(PaymentMethod = Wallet), &AnalysisContext::from_dir_values([ dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = Card), ]), &mut memo, &mut cycle_map, None, ); assert!(_result.is_ok()); } #[test] fn test_cycle_resolution_in_graph1() { let mut builder = cgraph::ConstraintGraphBuilder::new(); let _node_1 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( enums::CaptureMethod::Automatic, )), None, None::<()>, ); let _node_2 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), None, None::<()>, ); let _node_3 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), None, None::<()>, ); let mut memo = cgraph::Memoization::new(); let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( _node_1, _node_2, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_2 = builder .make_edge( _node_1, _node_3, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_3 = builder .make_edge( _node_2, _node_1, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_4 = builder .make_edge( _node_3, _node_1, cgraph::Strength::Strong, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let graph = builder.build(); let _result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Wallet), dirval!(CaptureMethod = Automatic), ]), &mut memo, &mut cycle_map, None, ); assert!(_result.is_ok()); } #[test] fn test_cycle_resolution_in_graph2() { let mut builder = cgraph::ConstraintGraphBuilder::new(); let _node_0 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::BillingCountry( enums::BillingCountry::Afghanistan, )), None, None::<()>, ); let _node_1 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( enums::CaptureMethod::Automatic, )), None, None::<()>, ); let _node_2 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), None, None::<()>, ); let _node_3 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), None, None::<()>, ); let _node_4 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentCurrency(enums::PaymentCurrency::USD)), None, None::<()>, ); let mut memo = cgraph::Memoization::new(); let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( _node_0, _node_1, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_2 = builder .make_edge( _node_1, _node_2, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_3 = builder .make_edge( _node_1, _node_3, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_4 = builder .make_edge( _node_3, _node_4, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_5 = builder .make_edge( _node_2, _node_4, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_6 = builder .make_edge( _node_4, _node_1, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_7 = builder .make_edge( _node_4, _node_0, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let graph = builder.build(); let _result = graph.key_value_analysis( dirval!(BillingCountry = Afghanistan), &AnalysisContext::from_dir_values([ dirval!(PaymentCurrency = USD), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Wallet), dirval!(CaptureMethod = Automatic), dirval!(BillingCountry = Afghanistan), ]), &mut memo, &mut cycle_map, None, ); assert!(_result.is_ok()); } }
{ "crate": "euclid", "file": "crates/euclid/src/dssa/graph.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-4259920683056067215
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/tokenization.rs // Contains: 4 structs, 0 enums use common_enums; use common_utils::id_type; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::{schema, ToSchema}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct GenericTokenizationResponse { /// Unique identifier returned by the tokenization service #[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalTokenId, /// Created time of the tokenization id #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] pub created_at: PrimitiveDateTime, /// Status of the tokenization id created #[schema(value_type = String,example = "enabled")] pub flag: common_enums::TokenizationFlag, } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct GenericTokenizationRequest { /// Customer ID for which the tokenization is requested #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] pub customer_id: id_type::GlobalCustomerId, /// Request for tokenization which contains the data to be tokenized #[schema(value_type = Object,example = json!({ "city": "NY", "unit": "245" }))] pub token_request: masking::Secret<serde_json::Value>, } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct DeleteTokenDataRequest { /// Customer ID for which the tokenization is requested #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] pub customer_id: id_type::GlobalCustomerId, /// Session ID associated with the tokenization request #[schema(value_type = String, example = "12345_pms_01926c58bc6e77c09e809964e72af8c8")] pub session_id: id_type::GlobalPaymentMethodSessionId, } #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct DeleteTokenDataResponse { /// Unique identifier returned by the tokenization service #[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalTokenId, }
{ "crate": "api_models", "file": "crates/api_models/src/tokenization.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_api_models_4976092304965805004
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/locker_migration.rs // Contains: 1 structs, 0 enums #[derive(Debug, Clone, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct MigrateCardResponse { pub status_message: String, pub status_code: String, pub customers_moved: usize, pub cards_moved: usize, }
{ "crate": "api_models", "file": "crates/api_models/src/locker_migration.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-9002604506749396698
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/payment_methods.rs // Contains: 107 structs, 14 enums use std::collections::{HashMap, HashSet}; #[cfg(feature = "v2")] use std::str::FromStr; use cards::CardNumber; #[cfg(feature = "v1")] use common_utils::crypto::OptionalEncryptableName; use common_utils::{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH, errors, ext_traits::OptionExt, id_type, link_utils, pii, types::{MinorUnit, Percentage, Surcharge}, }; use masking::PeekInterface; use serde::de; use utoipa::{schema, ToSchema}; #[cfg(feature = "v1")] use crate::payments::BankCodeResponse; #[cfg(feature = "payouts")] use crate::payouts; use crate::{admin, enums as api_enums, open_router, payments}; #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodCreate { /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>,example = "credit")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user #[schema(example = "Citibank")] pub payment_method_issuer: Option<String>, /// A standard code representing the issuer of payment method #[schema(value_type = Option<PaymentMethodIssuerCode>,example = "jp_applepay")] pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, /// Card Details #[schema(example = json!({ "card_number": "4111111145551142", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "John Doe"}))] pub card: Option<CardDetail>, /// 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>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The card network #[schema(example = "Visa")] pub card_network: Option<String>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] pub bank_transfer: Option<payouts::Bank>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Wallet>)] pub wallet: Option<payouts::Wallet>, /// For Client based calls, SDK will use the client_secret /// in order to call /payment_methods /// Client secret will be generated whenever a new /// payment method is created pub client_secret: Option<String>, /// Payment method data to be passed in case of client /// based flow pub payment_method_data: Option<PaymentMethodCreateData>, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, #[serde(skip_deserializing)] /// The connector mandate details of the payment method, this is added only for cards migration /// api and is skipped during deserialization of the payment method create request as this /// it should not be passed in the request pub connector_mandate_details: Option<PaymentsMandateReference>, #[serde(skip_deserializing)] /// The transaction id of a CIT (customer initiated transaction) associated with the payment method, /// this is added only for cards migration api and is skipped during deserialization of the /// payment method create request as it should not be passed in the request pub network_transaction_id: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodCreate { /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "google_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// 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>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// Payment method data to be passed pub payment_method_data: PaymentMethodCreateData, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodIntentCreate { /// 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>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodIntentConfirm { /// The unique identifier of the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Payment method data to be passed pub payment_method_data: PaymentMethodCreateData, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "credit")] pub payment_method_subtype: api_enums::PaymentMethodType, } #[cfg(feature = "v2")] impl PaymentMethodIntentConfirm { pub fn validate_payment_method_data_against_payment_method( payment_method_type: api_enums::PaymentMethod, payment_method_data: PaymentMethodCreateData, ) -> bool { match payment_method_type { api_enums::PaymentMethod::Card => { matches!( payment_method_data, PaymentMethodCreateData::Card(_) | PaymentMethodCreateData::ProxyCard(_) ) } _ => false, } } } /// This struct is used internally only #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentMethodIntentConfirmInternal { pub id: id_type::GlobalPaymentMethodId, pub request: PaymentMethodIntentConfirm, } #[cfg(feature = "v2")] impl From<PaymentMethodIntentConfirmInternal> for PaymentMethodIntentConfirm { fn from(item: PaymentMethodIntentConfirmInternal) -> Self { item.request } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] /// This struct is only used by and internal api to migrate payment method pub struct PaymentMethodMigrate { /// Merchant id pub merchant_id: id_type::MerchantId, /// The type of payment method use for the payment. pub payment_method: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user pub payment_method_issuer: Option<String>, /// A standard code representing the issuer of payment method pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, /// Card Details pub card: Option<MigrateCardDetail>, /// Network token details pub network_token: Option<MigrateNetworkTokenDetail>, /// 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. pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the customer. pub customer_id: Option<id_type::CustomerId>, /// The card network pub card_network: Option<String>, /// Payment method details from locker #[cfg(feature = "payouts")] pub bank_transfer: Option<payouts::Bank>, /// Payment method details from locker #[cfg(feature = "payouts")] pub wallet: Option<payouts::Wallet>, /// Payment method data to be passed in case of client /// based flow pub payment_method_data: Option<PaymentMethodCreateData>, /// The billing details of the payment method pub billing: Option<payments::Address>, /// The connector mandate details of the payment method #[serde(deserialize_with = "deserialize_connector_mandate_details")] pub connector_mandate_details: Option<CommonMandateReference>, // The CIT (customer initiated transaction) transaction id associated with the payment method pub network_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodMigrateResponse { //payment method response when payment method entry is created pub payment_method_response: PaymentMethodResponse, //card data migration status pub card_migrated: Option<bool>, //network token data migration status pub network_token_migrated: Option<bool>, //connector mandate details migration status pub connector_mandate_details_migrated: Option<bool>, //network transaction id migration status pub network_transaction_id_migrated: Option<bool>, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodRecordUpdateResponse { pub payment_method_id: String, pub status: common_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub connector_mandate_details: Option<pii::SecretSerdeValue>, pub updated_payment_method_data: Option<bool>, pub connector_customer: Option<pii::SecretSerdeValue>, } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsMandateReference( pub HashMap<id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>, ); #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PayoutsMandateReference( pub HashMap<id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>, ); #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PayoutsMandateReferenceRecord { pub transfer_method_id: Option<String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PaymentsMandateReferenceRecord { pub connector_mandate_id: String, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::Currency>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct CommonMandateReference { pub payments: Option<PaymentsMandateReference>, pub payouts: Option<PayoutsMandateReference>, } impl From<CommonMandateReference> for PaymentsMandateReference { fn from(common_mandate: CommonMandateReference) -> Self { common_mandate.payments.unwrap_or_default() } } impl From<PaymentsMandateReference> for CommonMandateReference { fn from(payments_reference: PaymentsMandateReference) -> Self { Self { payments: Some(payments_reference), payouts: None, } } } fn deserialize_connector_mandate_details<'de, D>( deserializer: D, ) -> Result<Option<CommonMandateReference>, D::Error> where D: serde::Deserializer<'de>, { let value: Option<serde_json::Value> = <Option<serde_json::Value> as de::Deserialize>::deserialize(deserializer)?; let payments_data = value .clone() .map(|mut mandate_details| { mandate_details .as_object_mut() .map(|obj| obj.remove("payouts")); serde_json::from_value::<PaymentsMandateReference>(mandate_details) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize PaymentsMandateReference `{err_msg}`", )) })?; let payouts_data = value .clone() .map(|mandate_details| { serde_json::from_value::<Option<CommonMandateReference>>(mandate_details).map( |optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) }, ) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize CommonMandateReference `{err_msg}`", )) })? .flatten(); Ok(Some(CommonMandateReference { payments: payments_data, payouts: payouts_data, })) } #[cfg(feature = "v1")] impl PaymentMethodCreate { pub fn get_payment_method_create_from_payment_method_migrate( card_number: CardNumber, payment_method_migrate: &PaymentMethodMigrate, ) -> Self { let card_details = payment_method_migrate .card .as_ref() .map(|payment_method_migrate_card| CardDetail { card_number, card_exp_month: payment_method_migrate_card.card_exp_month.clone(), card_exp_year: payment_method_migrate_card.card_exp_year.clone(), card_holder_name: payment_method_migrate_card.card_holder_name.clone(), nick_name: payment_method_migrate_card.nick_name.clone(), card_issuing_country: payment_method_migrate_card.card_issuing_country.clone(), card_network: payment_method_migrate_card.card_network.clone(), card_issuer: payment_method_migrate_card.card_issuer.clone(), card_type: payment_method_migrate_card.card_type.clone(), }); Self { customer_id: payment_method_migrate.customer_id.clone(), payment_method: payment_method_migrate.payment_method, payment_method_type: payment_method_migrate.payment_method_type, payment_method_issuer: payment_method_migrate.payment_method_issuer.clone(), payment_method_issuer_code: payment_method_migrate.payment_method_issuer_code, metadata: payment_method_migrate.metadata.clone(), payment_method_data: payment_method_migrate.payment_method_data.clone(), connector_mandate_details: payment_method_migrate .connector_mandate_details .clone() .map(|common_mandate_reference| { PaymentsMandateReference::from(common_mandate_reference) }), client_secret: None, billing: payment_method_migrate.billing.clone(), card: card_details, card_network: payment_method_migrate.card_network.clone(), #[cfg(feature = "payouts")] bank_transfer: payment_method_migrate.bank_transfer.clone(), #[cfg(feature = "payouts")] wallet: payment_method_migrate.wallet.clone(), network_transaction_id: payment_method_migrate.network_transaction_id.clone(), } } } #[cfg(feature = "v2")] impl PaymentMethodCreate { pub fn validate_payment_method_data_against_payment_method( payment_method_type: api_enums::PaymentMethod, payment_method_data: PaymentMethodCreateData, ) -> bool { match payment_method_type { api_enums::PaymentMethod::Card => { matches!( payment_method_data, PaymentMethodCreateData::Card(_) | PaymentMethodCreateData::ProxyCard(_) ) } _ => false, } } pub fn get_tokenize_connector_id( &self, ) -> Result<id_type::MerchantConnectorAccountId, error_stack::Report<errors::ValidationError>> { self.psp_tokenization .clone() .get_required_value("psp_tokenization") .map(|psp| psp.connector_id) } } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodUpdate { /// Card Details #[schema(example = json!({ "card_number": "4111111145551142", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "John Doe"}))] pub card: Option<CardDetailUpdate>, /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodUpdate { /// Payment method details to be updated for the payment_method pub payment_method_data: Option<PaymentMethodUpdateData>, /// The connector token details to be updated for the payment_method pub connector_token_details: Option<ConnectorTokenDetails>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodUpdateData { Card(CardDetailUpdate), } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodCreateData { Card(CardDetail), ProxyCard(ProxyCardDetails), } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodCreateData { Card(CardDetail), } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } #[derive( Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, strum::EnumString, strum::Display, Eq, PartialEq, )] #[serde(rename_all = "snake_case")] pub enum CardType { Credit, Debit, } // We cannot use the card struct that we have for payments for the following reason // The card struct used for payments has card_cvc as mandatory // but when vaulting the card, we do not need cvc to be collected from the user // This is because, the vaulted payment method can be used for future transactions in the presence of the customer // when the customer is on_session again, the cvc can be collected from the customer #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country #[schema(value_type = CountryAlpha2)] pub card_issuing_country: Option<api_enums::CountryAlpha2>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<CardType>, /// The CVC number for the card /// This is optional in case the card needs to be vaulted #[schema(value_type = String, example = "242")] pub card_cvc: Option<masking::Secret<String>>, } // This struct is for collecting Proxy Card Data // All card related data present in this struct are tokenzied // No strict type is present to accept tokenized data #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ProxyCardDetails { /// Tokenized Card Number #[schema(value_type = String,example = "tok_sjfowhoejsldj")] pub card_number: masking::Secret<String>, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// First Six Digit of Card Number pub bin_number: Option<String>, ///Last Four Digit of Card Number pub last_four: Option<String>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<common_enums::CardNetwork>, /// Card Type pub card_type: Option<String>, /// Issuing Country of the Card pub card_issuing_country: Option<String>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// The CVC number for the card /// This is optional in case the card needs to be vaulted #[schema(value_type = String, example = "242")] pub card_cvc: Option<masking::Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MigrateCardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: masking::Secret<String>, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MigrateNetworkTokenData { /// Network Token Number #[schema(value_type = String,example = "4111111145551142")] pub network_token_number: CardNumber, /// Network Token Expiry Month #[schema(value_type = String,example = "10")] pub network_token_exp_month: masking::Secret<String>, /// Network Token Expiry Year #[schema(value_type = String,example = "25")] pub network_token_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MigrateNetworkTokenDetail { /// Network token details pub network_token_data: MigrateNetworkTokenData, /// Network token requestor reference id pub network_token_requestor_ref_id: String, } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetailUpdate { /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: Option<masking::Secret<String>>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: Option<masking::Secret<String>>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, } #[cfg(feature = "v1")] impl CardDetailUpdate { pub fn apply(&self, card_data_from_locker: Card) -> CardDetail { CardDetail { card_number: card_data_from_locker.card_number, card_exp_month: self .card_exp_month .clone() .unwrap_or(card_data_from_locker.card_exp_month), card_exp_year: self .card_exp_year .clone() .unwrap_or(card_data_from_locker.card_exp_year), card_holder_name: self .card_holder_name .clone() .or(card_data_from_locker.name_on_card), nick_name: self .nick_name .clone() .or(card_data_from_locker.nick_name.map(masking::Secret::new)), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, } } } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetailUpdate { /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, } #[cfg(feature = "v2")] impl CardDetailUpdate { pub fn apply(&self, card_data_from_locker: Card) -> CardDetail { CardDetail { card_number: card_data_from_locker.card_number, card_exp_month: card_data_from_locker.card_exp_month, card_exp_year: card_data_from_locker.card_exp_year, card_holder_name: self .card_holder_name .clone() .or(card_data_from_locker.name_on_card), nick_name: self .nick_name .clone() .or(card_data_from_locker.nick_name.map(masking::Secret::new)), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, card_cvc: None, } } } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodResponseData { Card(CardDetailFromLocker), } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodResponse { /// Unique identifier for a merchant #[schema(example = "merchant_1671528864", value_type = String)] pub merchant_id: id_type::MerchantId, /// The unique identifier of the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The unique identifier of the Payment method #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] pub payment_method_id: String, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>, example = "credit")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Card details from card locker #[schema(example = json!({"last4": "1142","exp_month": "03","exp_year": "2030"}))] pub card: Option<CardDetailFromLocker>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional. #[schema(example = true)] pub installment_payment_enabled: Option<bool>, /// Type of payment experience enabled with the connector #[schema(value_type = Option<Vec<PaymentExperience>>, example = json!(["redirect_to_url"]))] pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, /// 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>, example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = Option<PrimitiveDateTime>, example = "2023-01-18T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] #[serde(skip_serializing_if = "Option::is_none")] pub bank_transfer: Option<payouts::Bank>, #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_used_at: Option<time::PrimitiveDateTime>, /// For Client based calls pub client_secret: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema, Clone)] pub struct ConnectorTokenDetails { /// The unique identifier of the connector account through which the token was generated #[schema(value_type = String, example = "mca_")] pub connector_id: id_type::MerchantConnectorAccountId, #[schema(value_type = TokenizationType)] pub token_type: common_enums::TokenizationType, /// The status of connector token if it is active or inactive #[schema(value_type = ConnectorTokenStatus)] pub status: common_enums::ConnectorTokenStatus, /// The reference id of the connector token /// This is the reference that was passed to connector when creating the token pub connector_token_request_reference_id: Option<String>, pub original_payment_authorized_amount: Option<MinorUnit>, /// The currency of the original payment authorized amount #[schema(value_type = Currency)] pub original_payment_authorized_currency: Option<common_enums::Currency>, /// Metadata associated with the connector token pub metadata: Option<pii::SecretSerdeValue>, /// The value of the connector token. This token can be used to make merchant initiated payments ( MIT ), directly with the connector. pub token: masking::Secret<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema, Clone)] pub struct PaymentMethodResponse { /// The unique identifier of the Payment method #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, /// Unique identifier for a merchant #[schema(value_type = String, example = "merchant_1671528864")] pub merchant_id: id_type::MerchantId, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>, example = "credit")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = Option<PrimitiveDateTime>, example = "2023-01-18T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_used_at: Option<time::PrimitiveDateTime>, /// The payment method details related to the payment method pub payment_method_data: Option<PaymentMethodResponseData>, /// The connector token details if available pub connector_tokens: Option<Vec<ConnectorTokenDetails>>, pub network_token: Option<NetworkTokenResponse>, } #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub enum PaymentMethodsData { Card(CardDetailsPaymentMethod), BankDetails(PaymentMethodDataBankCreds), WalletDetails(PaymentMethodDataWalletInfo), } #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub struct ExternalVaultTokenData { /// Tokenized reference for Card Number pub tokenized_card_number: masking::Secret<String>, } #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub struct CardDetailsPaymentMethod { pub last4_digits: Option<String>, pub issuer_country: Option<String>, pub expiry_month: Option<masking::Secret<String>>, pub expiry_year: Option<masking::Secret<String>>, pub nick_name: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, pub co_badged_card_data: Option<CoBadgedCardDataToBeSaved>, } impl From<&CoBadgedCardData> for CoBadgedCardDataToBeSaved { fn from(co_badged_card_data: &CoBadgedCardData) -> Self { Self { co_badged_card_networks: co_badged_card_data .co_badged_card_networks_info .get_card_networks(), issuer_country_code: co_badged_card_data.issuer_country_code, is_regulated: co_badged_card_data.is_regulated, regulated_name: co_badged_card_data.regulated_name.clone(), } } } #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub struct CoBadgedCardData { pub co_badged_card_networks_info: open_router::CoBadgedCardNetworks, pub issuer_country_code: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, } #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub struct CoBadgedCardDataToBeSaved { pub co_badged_card_networks: Vec<common_enums::CardNetwork>, pub issuer_country_code: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct NetworkTokenDetailsPaymentMethod { pub last4_digits: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub issuer_country: Option<common_enums::CountryAlpha2>, #[schema(value_type = Option<String>)] pub network_token_expiry_month: Option<masking::Secret<String>>, #[schema(value_type = Option<String>)] pub network_token_expiry_year: Option<masking::Secret<String>>, #[schema(value_type = Option<String>)] pub nick_name: Option<masking::Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, pub card_isin: Option<String>, pub card_issuer: Option<String>, #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodDataBankCreds { pub mask: String, pub hash: String, pub account_type: Option<String>, pub account_name: Option<String>, pub payment_method_type: api_enums::PaymentMethodType, pub connector_details: Vec<BankAccountConnectorDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct PaymentMethodDataWalletInfo { /// 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>, } impl From<payments::additional_info::WalletAdditionalDataForCard> for PaymentMethodDataWalletInfo { fn from(item: payments::additional_info::WalletAdditionalDataForCard) -> Self { Self { last4: item.last4, card_network: item.card_network, card_type: item.card_type, } } } impl From<PaymentMethodDataWalletInfo> for payments::additional_info::WalletAdditionalDataForCard { fn from(item: PaymentMethodDataWalletInfo) -> Self { Self { last4: item.last4, card_network: item.card_network, card_type: item.card_type, } } } impl From<payments::ApplepayPaymentMethod> for PaymentMethodDataWalletInfo { fn from(item: payments::ApplepayPaymentMethod) -> Self { Self { last4: item .display_name .chars() .rev() .take(4) .collect::<Vec<_>>() .into_iter() .rev() .collect(), card_network: item.network, card_type: Some(item.pm_type), } } } impl TryFrom<PaymentMethodDataWalletInfo> for payments::ApplepayPaymentMethod { type Error = error_stack::Report<errors::ValidationError>; fn try_from(item: PaymentMethodDataWalletInfo) -> Result<Self, Self::Error> { Ok(Self { display_name: item.last4, network: item.card_network, pm_type: item.card_type.get_required_value("card_type")?, }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct BankAccountTokenData { pub payment_method_type: api_enums::PaymentMethodType, pub payment_method: api_enums::PaymentMethod, pub connector_details: BankAccountConnectorDetails, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct BankAccountConnectorDetails { pub connector: String, pub account_id: masking::Secret<String>, pub mca_id: id_type::MerchantConnectorAccountId, pub access_token: BankAccountAccessCreds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub enum BankAccountAccessCreds { AccessToken(masking::Secret<String>), } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct Card { pub card_number: CardNumber, pub name_on_card: Option<masking::Secret<String>>, pub card_exp_month: masking::Secret<String>, pub card_exp_year: masking::Secret<String>, pub card_brand: Option<String>, pub card_isin: Option<String>, pub nick_name: Option<String>, } #[cfg(feature = "v1")] impl From<(Card, Option<common_enums::CardNetwork>)> for CardDetail { fn from((card, card_network): (Card, Option<common_enums::CardNetwork>)) -> Self { Self { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.name_on_card.clone(), nick_name: card.nick_name.map(masking::Secret::new), card_issuing_country: None, card_network, card_issuer: None, card_type: None, } } } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct CardDetailFromLocker { pub scheme: Option<String>, pub issuer_country: Option<String>, pub last4_digits: Option<String>, #[serde(skip)] #[schema(value_type=Option<String>)] pub card_number: Option<CardNumber>, #[schema(value_type=Option<String>)] pub expiry_month: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub expiry_year: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_token: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_fingerprint: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub nick_name: Option<masking::Secret<String>>, #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_type: Option<String>, pub saved_to_locker: bool, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct CardDetailFromLocker { #[schema(value_type = Option<CountryAlpha2>)] pub issuer_country: Option<api_enums::CountryAlpha2>, pub last4_digits: Option<String>, #[serde(skip)] #[schema(value_type=Option<String>)] pub card_number: Option<CardNumber>, #[schema(value_type=Option<String>)] pub expiry_month: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub expiry_year: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_fingerprint: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub nick_name: Option<masking::Secret<String>>, #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_type: Option<String>, pub saved_to_locker: bool, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct NetworkTokenResponse { pub payment_method_data: NetworkTokenDetailsPaymentMethod, } fn saved_in_locker_default() -> bool { true } #[cfg(feature = "v1")] impl From<CardDetailFromLocker> for payments::AdditionalCardInfo { fn from(item: CardDetailFromLocker) -> Self { Self { card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, card_issuing_country: item.issuer_country, bank_code: None, last4: item.last4_digits, card_isin: item.card_isin, card_extended_bin: item .card_number .map(|card_number| card_number.get_extended_card_bin()), card_exp_month: item.expiry_month, card_exp_year: item.expiry_year, card_holder_name: item.card_holder_name, payment_checks: None, authentication_data: None, is_regulated: None, signature_network: None, } } } #[cfg(feature = "v2")] impl From<CardDetailFromLocker> for payments::AdditionalCardInfo { fn from(item: CardDetailFromLocker) -> Self { Self { card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, card_issuing_country: item.issuer_country.map(|country| country.to_string()), bank_code: None, last4: item.last4_digits, card_isin: item.card_isin, card_extended_bin: item .card_number .map(|card_number| card_number.get_extended_card_bin()), card_exp_month: item.expiry_month, card_exp_year: item.expiry_year, card_holder_name: item.card_holder_name, payment_checks: None, authentication_data: None, is_regulated: None, signature_network: None, } } } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForSession { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypes>, /// The list of saved payment methods of the customer pub customer_payment_methods: Vec<CustomerPaymentMethodResponseItem>, } #[cfg(feature = "v1")] impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { fn from(item: CardDetailsPaymentMethod) -> Self { Self { scheme: None, issuer_country: item.issuer_country, last4_digits: item.last4_digits, card_number: None, expiry_month: item.expiry_month, expiry_year: item.expiry_year, card_token: None, card_holder_name: item.card_holder_name, card_fingerprint: None, nick_name: item.nick_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, } } } #[cfg(feature = "v2")] impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { fn from(item: CardDetailsPaymentMethod) -> Self { Self { issuer_country: item .issuer_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten(), last4_digits: item.last4_digits, card_number: None, expiry_month: item.expiry_month, expiry_year: item.expiry_year, card_holder_name: item.card_holder_name, card_fingerprint: None, nick_name: item.nick_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, } } } #[cfg(feature = "v2")] impl From<CardDetail> for CardDetailFromLocker { fn from(item: CardDetail) -> Self { Self { issuer_country: item.card_issuing_country, last4_digits: Some(item.card_number.get_last4()), card_number: Some(item.card_number), expiry_month: Some(item.card_exp_month), expiry_year: Some(item.card_exp_year), card_holder_name: item.card_holder_name, nick_name: item.nick_name, card_isin: None, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, card_fingerprint: None, } } } #[cfg(feature = "v1")] impl From<CardDetail> for CardDetailFromLocker { fn from(item: CardDetail) -> Self { // scheme should be updated in case of co-badged cards let card_scheme = item .card_network .clone() .map(|card_network| card_network.to_string()); Self { issuer_country: item.card_issuing_country, last4_digits: Some(item.card_number.get_last4()), card_number: Some(item.card_number), expiry_month: Some(item.card_exp_month), expiry_year: Some(item.card_exp_year), card_holder_name: item.card_holder_name, nick_name: item.nick_name, card_isin: None, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, card_fingerprint: None, scheme: card_scheme, card_token: None, } } } #[cfg(feature = "v2")] impl From<CardDetail> for CardDetailsPaymentMethod { fn from(item: CardDetail) -> Self { Self { issuer_country: item.card_issuing_country.map(|c| c.to_string()), last4_digits: Some(item.card_number.get_last4()), expiry_month: Some(item.card_exp_month), expiry_year: Some(item.card_exp_year), card_holder_name: item.card_holder_name, nick_name: item.nick_name, card_isin: None, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, co_badged_card_data: None, } } } #[cfg(feature = "v1")] impl From<(CardDetailFromLocker, Option<&CoBadgedCardData>)> for CardDetailsPaymentMethod { fn from( (item, co_badged_card_data): (CardDetailFromLocker, Option<&CoBadgedCardData>), ) -> Self { Self { issuer_country: item.issuer_country, last4_digits: item.last4_digits, expiry_month: item.expiry_month, expiry_year: item.expiry_year, nick_name: item.nick_name, card_holder_name: item.card_holder_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, co_badged_card_data: co_badged_card_data.map(CoBadgedCardDataToBeSaved::from), } } } #[cfg(feature = "v2")] impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { fn from(item: CardDetailFromLocker) -> Self { Self { issuer_country: item.issuer_country.map(|country| country.to_string()), last4_digits: item.last4_digits, expiry_month: item.expiry_month, expiry_year: item.expiry_year, nick_name: item.nick_name, card_holder_name: item.card_holder_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, co_badged_card_data: None, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct PaymentExperienceTypes { /// The payment experience enabled #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience_type: api_enums::PaymentExperience, /// The list of eligible connectors for a given payment experience #[schema(example = json!(["stripe", "adyen"]))] pub eligible_connectors: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct CardNetworkTypes { /// The card network enabled #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: api_enums::CardNetwork, /// surcharge details for this card network pub surcharge_details: Option<SurchargeDetailsResponse>, /// The list of eligible connectors for a given card network #[schema(example = json!(["stripe", "adyen"]))] pub eligible_connectors: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankDebitTypes { pub eligible_connectors: Vec<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypes { /// The payment method type enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The list of payment experiences enabled, if applicable for a payment method type pub payment_experience: Option<Vec<PaymentExperienceTypes>>, /// The list of card networks enabled, if applicable for a payment method type pub card_networks: Option<Vec<CardNetworkTypes>>, #[schema(deprecated)] /// The list of banks enabled, if applicable for a payment method type . To be deprecated soon. pub bank_names: Option<Vec<BankCodeResponse>>, /// The Bank debit payment method information, if applicable for a payment method type. pub bank_debits: Option<BankDebitTypes>, /// The Bank transfer payment method information, if applicable for a payment method type. pub bank_transfers: Option<BankTransferTypes>, /// Required fields for the payment_method_type. pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, /// surcharge details for this payment method type if exists pub surcharge_details: Option<SurchargeDetailsResponse>, /// auth service connector label for this payment method type, if exists pub pm_auth_connector: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] #[serde(untagged)] // Untagged used for serialization only pub enum PaymentMethodSubtypeSpecificData { #[schema(title = "card")] Card { card_networks: Vec<CardNetworkTypes>, }, #[schema(title = "bank")] Bank { #[schema(value_type = BankNames)] bank_names: Vec<common_enums::BankNames>, }, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypes { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] pub extra_information: Option<PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. pub required_fields: Vec<RequiredFieldInfo>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SurchargeDetailsResponse { /// surcharge value pub surcharge: SurchargeResponse, /// tax on surcharge value pub tax_on_surcharge: Option<SurchargePercentage>, /// surcharge amount for this payment pub display_surcharge_amount: f64, /// tax on surcharge amount for this payment pub display_tax_on_surcharge_amount: f64, /// sum of display_surcharge_amount and display_tax_on_surcharge_amount pub display_total_surcharge_amount: f64, } #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum SurchargeResponse { /// Fixed Surcharge value Fixed(MinorUnit), /// Surcharge percentage Rate(SurchargePercentage), } impl From<Surcharge> for SurchargeResponse { fn from(value: Surcharge) -> Self { match value { Surcharge::Fixed(amount) => Self::Fixed(amount), Surcharge::Rate(percentage) => Self::Rate(percentage.into()), } } } #[derive(Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct SurchargePercentage { percentage: f32, } impl From<Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>> for SurchargePercentage { fn from(value: Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>) -> Self { Self { percentage: value.get_percentage(), } } } /// Required fields info used while listing the payment_method_data #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq, ToSchema)] pub struct RequiredFieldInfo { /// Required field for a payment_method through a payment_method_type pub required_field: String, /// Display name of the required field in the front-end pub display_name: String, /// Possible field type of required field #[schema(value_type = FieldType)] pub field_type: api_enums::FieldType, #[schema(value_type = Option<String>)] pub value: Option<masking::Secret<String>>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct ResponsePaymentMethodsEnabled { /// The payment method enabled #[schema(value_type = PaymentMethod)] pub payment_method: api_enums::PaymentMethod, /// The list of payment method types enabled for a connector account pub payment_method_types: Vec<ResponsePaymentMethodTypes>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankTransferTypes { /// The list of eligible connectors for a given payment experience #[schema(example = json!(["stripe", "adyen"]))] pub eligible_connectors: Vec<String>, } #[derive(Clone, Debug)] pub struct ResponsePaymentMethodIntermediate { pub payment_method_type: api_enums::PaymentMethodType, pub payment_experience: Option<api_enums::PaymentExperience>, pub card_networks: Option<Vec<api_enums::CardNetwork>>, pub payment_method: api_enums::PaymentMethod, pub connector: String, pub merchant_connector_id: String, } impl ResponsePaymentMethodIntermediate { pub fn new( pm_type: RequestPaymentMethodTypes, connector: String, merchant_connector_id: String, pm: api_enums::PaymentMethod, ) -> Self { Self { payment_method_type: pm_type.payment_method_type, payment_experience: pm_type.payment_experience, card_networks: pm_type.card_networks, payment_method: pm, connector, merchant_connector_id, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, Hash)] pub struct RequestPaymentMethodTypes { #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, #[schema(value_type = Option<PaymentExperience>)] pub payment_experience: Option<api_enums::PaymentExperience>, #[schema(value_type = Option<Vec<CardNetwork>>)] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// List of currencies accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "specific_accepted", "list": ["USD", "INR"] } ), value_type = Option<AcceptedCurrencies>)] pub accepted_currencies: Option<admin::AcceptedCurrencies>, /// List of Countries accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "specific_accepted", "list": ["UK", "AU"] } ), value_type = Option<AcceptedCountries>)] pub accepted_countries: Option<admin::AcceptedCountries>, /// Minimum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) #[schema(example = 1)] pub minimum_amount: Option<MinorUnit>, /// Maximum amount supported by the processor. To be represented in the lowest denomination of /// the target currency (For example, for USD it should be in cents) #[schema(example = 1313)] pub maximum_amount: Option<MinorUnit>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = false)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional. #[schema(example = true)] pub installment_payment_enabled: Option<bool>, } impl RequestPaymentMethodTypes { /// Get payment_method_type #[cfg(feature = "v1")] pub fn get_payment_method_type(&self) -> Option<api_enums::PaymentMethodType> { Some(self.payment_method_type) } } #[cfg(feature = "v1")] //List Payment Method #[derive(Debug, Clone, serde::Serialize, Default, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodListRequest { /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, /// The two-letter ISO currency code #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))] pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>, /// The three-letter ISO currency code #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))] pub accepted_currencies: Option<Vec<api_enums::Currency>>, /// Filter by amount #[schema(example = 60)] pub amount: Option<MinorUnit>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional. #[schema(example = true)] pub installment_payment_enabled: Option<bool>, /// Indicates whether the payment method is eligible for card netwotks #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// Indicates the limit of last used payment methods #[schema(example = 1)] pub limit: Option<i64>, } #[cfg(feature = "v1")] impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = PaymentMethodListRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "installment_payment_enabled" => { set_or_reject_duplicate( &mut output.installment_payment_enabled, "installment_payment_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } } #[cfg(feature = "v2")] //List Payment Method #[derive(Debug, Clone, serde::Serialize, Default, ToSchema)] #[serde(deny_unknown_fields)] pub struct ListMethodsForPaymentMethodsRequest { /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, /// The two-letter ISO currency code #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))] pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>, /// Filter by amount #[schema(example = 60)] pub amount: Option<MinorUnit>, /// The three-letter ISO currency code #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))] pub accepted_currencies: Option<Vec<api_enums::Currency>>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for card netwotks #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// Indicates the limit of last used payment methods #[schema(example = 1)] pub limit: Option<i64>, } #[cfg(feature = "v2")] impl<'de> serde::Deserialize<'de> for ListMethodsForPaymentMethodsRequest { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = ListMethodsForPaymentMethodsRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = ListMethodsForPaymentMethodsRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } } // Try to set the provided value to the data otherwise throw an error fn set_or_reject_duplicate<T, E: de::Error>( data: &mut Option<T>, name: &'static str, value: T, ) -> Result<(), E> { match data { Some(_inner) => Err(de::Error::duplicate_field(name)), None => { *data = Some(value); Ok(()) } } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponse { /// Redirect URL of the merchant #[schema(example = "https://www.google.com")] pub redirect_url: Option<String>, /// currency of the Payment to be done #[schema(example = "USD", value_type = Currency)] pub currency: Option<api_enums::Currency>, /// Information about the payment method pub payment_methods: Vec<ResponsePaymentMethodsEnabled>, /// Value indicating if the current payment is a mandate payment #[schema(value_type = MandateType)] pub mandate_payment: Option<payments::MandateType>, #[schema(value_type = Option<String>)] pub merchant_name: OptionalEncryptableName, /// flag to indicate if surcharge and tax breakup screen should be shown or not #[schema(value_type = bool)] pub show_surcharge_breakup_screen: bool, #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, /// flag to indicate whether to perform external 3ds authentication #[schema(example = true)] pub request_external_three_ds_authentication: bool, /// flag that indicates whether to collect shipping details from wallets or from the customer pub collect_shipping_details_from_wallets: Option<bool>, /// flag that indicates whether to collect billing details from wallets or from the customer pub collect_billing_details_from_wallets: Option<bool>, /// flag that indicates whether to calculate tax on the order amount pub is_tax_calculation_enabled: bool, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodsListResponse { /// List of payment methods for customer pub customer_payment_methods: Vec<CustomerPaymentMethod>, /// Returns whether a customer id is not tied to a payment intent (only when the request is made against a client secret) pub is_guest_customer: Option<bool>, } // OLAP PML Response #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodsListResponse { /// List of payment methods for customer pub customer_payment_methods: Vec<PaymentMethodResponseItem>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct GetTokenDataRequest { /// Indicates the type of token to be fetched pub token_type: api_enums::TokenDataType, } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for GetTokenDataRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct TokenDataResponse { /// The unique identifier of the payment method. #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: id_type::GlobalPaymentMethodId, /// token type of the payment method #[schema(value_type = TokenDataType)] pub token_type: api_enums::TokenDataType, /// token details of the payment method pub token_details: TokenDetailsResponse, } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for TokenDataResponse {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum TokenDetailsResponse { NetworkTokenDetails(NetworkTokenDetailsResponse), } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct NetworkTokenDetailsResponse { /// Network token generated against the Card Number #[schema(value_type = String)] pub network_token: cards::NetworkToken, /// Expiry month of the network token #[schema(value_type = String)] pub network_token_exp_month: masking::Secret<String>, /// Expiry year of the network token #[schema(value_type = String)] pub network_token_exp_year: masking::Secret<String>, /// Cryptogram generated by the Network #[schema(value_type = Option<String>)] pub cryptogram: Option<masking::Secret<String>>, /// Issuer of the card pub card_issuer: Option<String>, /// Card network of the token #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<common_enums::CardNetwork>, /// Card type of the token pub card_type: Option<CardType>, /// Issuing country of the card #[schema(value_type = Option<CountryAlpha2>)] pub card_issuing_country: Option<common_enums::CountryAlpha2>, /// Bank code of the card pub bank_code: Option<String>, /// Name of the card holder #[schema(value_type = Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, /// Nick name of the card holder #[schema(value_type = Option<String>)] pub nick_name: Option<masking::Secret<String>>, /// ECI indicator of the card pub eci: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct TotalPaymentMethodCountResponse { /// total count of payment methods under the merchant pub total_count: i64, } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for TotalPaymentMethodCountResponse {} #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodDeleteResponse { /// The unique identifier of the Payment method #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] pub payment_method_id: String, /// Whether payment method was deleted or not #[schema(example = true)] pub deleted: bool, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodDeleteResponse { /// The unique identifier of the Payment method #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerDefaultPaymentMethodResponse { /// The unique identifier of the Payment method #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] pub default_payment_method_id: Option<String>, /// The unique identifier of the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>,example = "credit")] pub payment_method_type: Option<api_enums::PaymentMethodType>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentMethodResponseItem { /// The unique identifier of the payment method. #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "credit")] pub payment_method_subtype: api_enums::PaymentMethodType, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// PaymentMethod Data from locker pub payment_method_data: Option<PaymentMethodListData>, /// Masked bank details from PM auth services #[schema(example = json!({"mask": "0000"}))] pub bank: Option<MaskedBankDetails>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: time::PrimitiveDateTime, /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601")] pub last_used_at: time::PrimitiveDateTime, /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub is_default: bool, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, ///The network token details for the payment method pub network_tokenization: Option<NetworkTokenResponse>, /// Whether psp_tokenization is enabled for the payment_method, this will be true when at least /// one multi-use token with status `Active` is available for the payment method pub psp_tokenization_enabled: bool, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodResponseItem { /// The unique identifier of the payment method. #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, /// Temporary Token for payment method in vault which gets refreshed for every payment #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")] pub payment_token: String, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "credit")] pub payment_method_subtype: api_enums::PaymentMethodType, /// Indicates whether the payment method is eligible for recurring payments #[schema(example = true)] pub recurring_enabled: bool, /// PaymentMethod Data from locker pub payment_method_data: Option<PaymentMethodListData>, /// Masked bank details from PM auth services #[schema(example = json!({"mask": "0000"}))] pub bank: Option<MaskedBankDetails>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: time::PrimitiveDateTime, /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub last_used_at: time::PrimitiveDateTime, /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub is_default: bool, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodListData { Card(CardDetailFromLocker), #[cfg(feature = "payouts")] #[schema(value_type = Bank)] Bank(payouts::Bank), } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethod { /// Token for payment method in temporary card locker which gets refreshed often #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")] pub payment_token: String, /// The unique identifier of the customer. #[schema(example = "pm_iouuy468iyuowqs")] pub payment_method_id: String, /// The unique identifier of the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>,example = "credit_card")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user #[schema(example = "Citibank")] pub payment_method_issuer: Option<String>, /// A standard code representing the issuer of payment method #[schema(value_type = Option<PaymentMethodIssuerCode>,example = "jp_applepay")] pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional. #[schema(example = true)] pub installment_payment_enabled: Option<bool>, /// Type of payment experience enabled with the connector #[schema(value_type = Option<Vec<PaymentExperience>>,example = json!(["redirect_to_url"]))] pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, /// Card details from card locker #[schema(example = json!({"last4": "1142","exp_month": "03","exp_year": "2030"}))] pub card: Option<CardDetailFromLocker>, /// 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>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = Option<PrimitiveDateTime>,example = "2023-01-18T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] #[serde(skip_serializing_if = "Option::is_none")] pub bank_transfer: Option<payouts::Bank>, /// Masked bank details from PM auth services #[schema(example = json!({"mask": "0000"}))] pub bank: Option<MaskedBankDetails>, /// Surcharge details for this saved card pub surcharge_details: Option<SurchargeDetailsResponse>, /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = Option<PrimitiveDateTime>,example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_used_at: Option<time::PrimitiveDateTime>, /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub default_payment_method_set: bool, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkRequest { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: Option<String>, /// The unique identifier of the customer. #[schema(value_type = String, example = "cus_92dnwed8s32bV9D8Snbiasd8v")] pub customer_id: id_type::CustomerId, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Redirect to this URL post completion #[schema(value_type = Option<String>, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1/status")] pub return_url: Option<String>, /// List of payment methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkResponse { /// The unique identifier for the collect link. #[schema(value_type = String, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: String, /// The unique identifier of the customer. #[schema(value_type = String, example = "cus_92dnwed8s32bV9D8Snbiasd8v")] pub customer_id: id_type::CustomerId, /// Time when this link will be expired in ISO8601 format #[schema(value_type = PrimitiveDateTime, example = "2025-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: time::PrimitiveDateTime, /// URL to the form's link generated for collecting payment method details. #[schema(value_type = String, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1")] pub link: masking::Secret<url::Url>, /// Redirect to this URL post completion #[schema(value_type = Option<String>, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1/status")] pub return_url: Option<String>, /// Collect link config used #[serde(flatten)] #[schema(value_type = GenericLinkUiConfig)] pub ui_config: link_utils::GenericLinkUiConfig, /// List of payment methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkRenderRequest { /// Unique identifier for a merchant. #[schema(example = "merchant_1671528864", value_type = String)] pub merchant_id: id_type::MerchantId, /// The unique identifier for the collect link. #[schema(value_type = String, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: String, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodCollectLinkDetails { pub publishable_key: masking::Secret<String>, pub client_secret: masking::Secret<String>, pub pm_collect_link_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: time::PrimitiveDateTime, pub return_url: Option<String>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodCollectLinkStatusDetails { pub pm_collect_link_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: time::PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: link_utils::PaymentMethodCollectStatus, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MaskedBankDetails { pub mask: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodId { pub payment_method_id: String, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DefaultPaymentMethod { #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, pub payment_method_id: String, } //------------------------------------------------TokenizeService------------------------------------------------ #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizePayloadEncrypted { pub payload: String, pub key_id: String, pub version: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizePayloadRequest { pub value1: String, pub value2: String, pub lookup_key: String, pub service_name: String, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct GetTokenizePayloadRequest { pub lookup_key: String, pub service_name: String, pub get_value2: bool, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct DeleteTokenizeByTokenRequest { pub lookup_key: String, pub service_name: String, } #[derive(Debug, serde::Serialize)] // Blocked: Yet to be implemented by `basilisk` pub struct DeleteTokenizeByDateRequest { pub buffer_minutes: i32, pub service_name: String, pub max_rows: i32, } #[derive(Debug, serde::Deserialize)] pub struct GetTokenizePayloadResponse { pub lookup_key: String, pub get_value2: Option<bool>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCardValue1 { pub card_number: String, pub exp_year: String, pub exp_month: String, pub name_on_card: Option<String>, pub nickname: Option<String>, pub card_last_four: Option<String>, pub card_token: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ListCountriesCurrenciesRequest { pub connector: api_enums::Connector, pub payment_method_type: api_enums::PaymentMethodType, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ListCountriesCurrenciesResponse { pub currencies: HashSet<api_enums::Currency>, pub countries: HashSet<CountryCodeWithName>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq)] pub struct CountryCodeWithName { pub code: api_enums::CountryAlpha2, pub name: api_enums::Country, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCardValue2 { pub card_security_code: Option<String>, pub card_fingerprint: Option<String>, pub external_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub payment_method_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletValue1 { pub data: payments::WalletData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankTransferValue1 { pub data: payments::BankTransferData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankTransferValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectValue1 { pub data: payments::BankRedirectData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PaymentMethodRecord { pub customer_id: id_type::CustomerId, pub name: Option<masking::Secret<String>>, pub email: Option<pii::Email>, pub phone: Option<masking::Secret<String>>, pub phone_country_code: Option<String>, pub merchant_id: Option<id_type::MerchantId>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_type: Option<api_enums::PaymentMethodType>, pub nick_name: Option<masking::Secret<String>>, pub payment_instrument_id: Option<masking::Secret<String>>, pub connector_customer_id: Option<String>, pub card_number_masked: masking::Secret<String>, pub card_expiry_month: masking::Secret<String>, pub card_expiry_year: masking::Secret<String>, pub card_scheme: Option<String>, pub original_transaction_id: Option<String>, pub billing_address_zip: Option<masking::Secret<String>>, pub billing_address_state: Option<masking::Secret<String>>, pub billing_address_first_name: Option<masking::Secret<String>>, pub billing_address_last_name: Option<masking::Secret<String>>, pub billing_address_city: Option<String>, pub billing_address_country: Option<api_enums::CountryAlpha2>, pub billing_address_line1: Option<masking::Secret<String>>, pub billing_address_line2: Option<masking::Secret<String>>, pub billing_address_line3: Option<masking::Secret<String>>, pub raw_card_number: Option<masking::Secret<String>>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub merchant_connector_ids: Option<String>, pub original_transaction_amount: Option<i64>, pub original_transaction_currency: Option<common_enums::Currency>, pub line_number: Option<i64>, pub network_token_number: Option<CardNumber>, pub network_token_expiry_month: Option<masking::Secret<String>>, pub network_token_expiry_year: Option<masking::Secret<String>>, pub network_token_requestor_ref_id: Option<String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct UpdatePaymentMethodRecord { pub payment_method_id: String, pub status: Option<common_enums::PaymentMethodStatus>, pub network_transaction_id: Option<String>, pub line_number: Option<i64>, pub payment_instrument_id: Option<masking::Secret<String>>, pub connector_customer_id: Option<String>, pub merchant_connector_ids: Option<String>, pub card_expiry_month: Option<masking::Secret<String>>, pub card_expiry_year: Option<masking::Secret<String>>, } #[derive(Debug, serde::Serialize)] pub struct PaymentMethodUpdateResponse { pub payment_method_id: String, pub status: Option<common_enums::PaymentMethodStatus>, pub network_transaction_id: Option<String>, pub connector_mandate_details: Option<pii::SecretSerdeValue>, pub update_status: UpdateStatus, #[serde(skip_serializing_if = "Option::is_none")] pub update_error: Option<String>, pub updated_payment_method_data: Option<bool>, pub connector_customer: Option<pii::SecretSerdeValue>, pub line_number: Option<i64>, } #[derive(Debug, Default, serde::Serialize)] pub struct PaymentMethodMigrationResponse { pub line_number: Option<i64>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method: Option<api_enums::PaymentMethod>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method_type: Option<api_enums::PaymentMethodType>, pub customer_id: Option<id_type::CustomerId>, pub migration_status: MigrationStatus, #[serde(skip_serializing_if = "Option::is_none")] pub migration_error: Option<String>, pub card_number_masked: Option<masking::Secret<String>>, pub card_migrated: Option<bool>, pub network_token_migrated: Option<bool>, pub connector_mandate_details_migrated: Option<bool>, pub network_transaction_id_migrated: Option<bool>, } #[derive(Debug, Default, serde::Serialize)] pub enum MigrationStatus { Success, #[default] Failed, } #[derive(Debug, Default, serde::Serialize)] pub enum UpdateStatus { Success, #[default] Failed, } impl PaymentMethodRecord { fn create_address(&self) -> Option<payments::AddressDetails> { if self.billing_address_first_name.is_some() && self.billing_address_line1.is_some() && self.billing_address_zip.is_some() && self.billing_address_city.is_some() && self.billing_address_country.is_some() { Some(payments::AddressDetails { city: self.billing_address_city.clone(), country: self.billing_address_country, line1: self.billing_address_line1.clone(), line2: self.billing_address_line2.clone(), state: self.billing_address_state.clone(), line3: self.billing_address_line3.clone(), zip: self.billing_address_zip.clone(), first_name: self.billing_address_first_name.clone(), last_name: self.billing_address_last_name.clone(), origin_zip: None, }) } else { None } } fn create_phone(&self) -> Option<payments::PhoneDetails> { if self.phone.is_some() || self.phone_country_code.is_some() { Some(payments::PhoneDetails { number: self.phone.clone(), country_code: self.phone_country_code.clone(), }) } else { None } } fn create_billing(&self) -> Option<payments::Address> { let address = self.create_address(); let phone = self.create_phone(); if address.is_some() || phone.is_some() || self.email.is_some() { Some(payments::Address { address, phone, email: self.email.clone(), }) } else { None } } } #[cfg(feature = "v1")] type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, ); #[cfg(feature = "v1")] type PaymentMethodUpdateResponseType = ( Result<PaymentMethodRecordUpdateResponse, String>, UpdatePaymentMethodRecord, ); #[cfg(feature = "v1")] impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponse { fn from((response, record): PaymentMethodMigrationResponseType) -> Self { match response { Ok(res) => Self { payment_method_id: Some(res.payment_method_response.payment_method_id), payment_method: res.payment_method_response.payment_method, payment_method_type: res.payment_method_response.payment_method_type, customer_id: res.payment_method_response.customer_id, migration_status: MigrationStatus::Success, migration_error: None, card_number_masked: Some(record.card_number_masked), line_number: record.line_number, card_migrated: res.card_migrated, network_token_migrated: res.network_token_migrated, connector_mandate_details_migrated: res.connector_mandate_details_migrated, network_transaction_id_migrated: res.network_transaction_id_migrated, }, Err(e) => Self { customer_id: Some(record.customer_id), migration_status: MigrationStatus::Failed, migration_error: Some(e), card_number_masked: Some(record.card_number_masked), line_number: record.line_number, ..Self::default() }, } } } #[cfg(feature = "v1")] impl From<PaymentMethodUpdateResponseType> for PaymentMethodUpdateResponse { fn from((response, record): PaymentMethodUpdateResponseType) -> Self { match response { Ok(res) => Self { payment_method_id: res.payment_method_id, status: Some(res.status), network_transaction_id: res.network_transaction_id, connector_mandate_details: res.connector_mandate_details, updated_payment_method_data: res.updated_payment_method_data, connector_customer: res.connector_customer, update_status: UpdateStatus::Success, update_error: None, line_number: record.line_number, }, Err(e) => Self { payment_method_id: record.payment_method_id, status: record.status, network_transaction_id: record.network_transaction_id, connector_mandate_details: None, updated_payment_method_data: None, connector_customer: None, update_status: UpdateStatus::Failed, update_error: Some(e), line_number: record.line_number, }, } } } impl TryFrom<( &PaymentMethodRecord, id_type::MerchantId, Option<&Vec<id_type::MerchantConnectorAccountId>>, )> for PaymentMethodMigrate { type Error = error_stack::Report<errors::ValidationError>; fn try_from( item: ( &PaymentMethodRecord, id_type::MerchantId, Option<&Vec<id_type::MerchantConnectorAccountId>>, ), ) -> Result<Self, Self::Error> { let (record, merchant_id, mca_ids) = item; let billing = record.create_billing(); let connector_mandate_details = if let Some(payment_instrument_id) = &record.payment_instrument_id { let ids = mca_ids.get_required_value("mca_ids")?; let mandate_map: HashMap<_, _> = ids .iter() .map(|mca_id| { ( mca_id.clone(), PaymentsMandateReferenceRecord { connector_mandate_id: payment_instrument_id.peek().to_string(), payment_method_type: record.payment_method_type, original_payment_authorized_amount: record.original_transaction_amount, original_payment_authorized_currency: record .original_transaction_currency, }, ) }) .collect(); Some(PaymentsMandateReference(mandate_map)) } else { None }; Ok(Self { merchant_id, customer_id: Some(record.customer_id.clone()), card: Some(MigrateCardDetail { card_number: record .raw_card_number .clone() .unwrap_or_else(|| record.card_number_masked.clone()), card_exp_month: record.card_expiry_month.clone(), card_exp_year: record.card_expiry_year.clone(), card_holder_name: record.name.clone(), card_network: None, card_type: None, card_issuer: None, card_issuing_country: None, nick_name: record.nick_name.clone(), }), network_token: Some(MigrateNetworkTokenDetail { network_token_data: MigrateNetworkTokenData { network_token_number: record.network_token_number.clone().unwrap_or_default(), network_token_exp_month: record .network_token_expiry_month .clone() .unwrap_or_default(), network_token_exp_year: record .network_token_expiry_year .clone() .unwrap_or_default(), card_holder_name: record.name.clone(), nick_name: record.nick_name.clone(), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, }, network_token_requestor_ref_id: record .network_token_requestor_ref_id .clone() .unwrap_or_default(), }), payment_method: record.payment_method, payment_method_type: record.payment_method_type, payment_method_issuer: None, billing, connector_mandate_details: connector_mandate_details.map( |payments_mandate_reference| { CommonMandateReference::from(payments_mandate_reference) }, ), metadata: None, payment_method_issuer_code: None, card_network: None, #[cfg(feature = "payouts")] bank_transfer: None, #[cfg(feature = "payouts")] wallet: None, payment_method_data: None, network_transaction_id: record.original_transaction_id.clone(), }) } } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardNetworkTokenizeRequest { /// Merchant ID associated with the tokenization request #[schema(example = "merchant_1671528864", value_type = String)] pub merchant_id: id_type::MerchantId, /// Details of the card or payment method to be tokenized #[serde(flatten)] pub data: TokenizeDataRequest, /// Customer details #[schema(value_type = CustomerDetails)] pub customer: payments::CustomerDetails, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// 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>, example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The name of the bank/ provider issuing the payment method to the end user pub payment_method_issuer: Option<String>, } impl common_utils::events::ApiEventMetric for CardNetworkTokenizeRequest {} #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum TokenizeDataRequest { Card(TokenizeCardRequest), ExistingPaymentMethod(TokenizePaymentMethodRequest), } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct TokenizeCardRequest { /// Card Number #[schema(value_type = String, example = "4111111145551142")] pub raw_card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String, example = "10")] pub card_expiry_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String, example = "25")] pub card_expiry_year: masking::Secret<String>, /// The CVC number for the card #[schema(value_type = Option<String>, example = "242")] pub card_cvc: Option<masking::Secret<String>>, /// Card Holder Name #[schema(value_type = Option<String>, example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>, example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<CardType>, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TokenizePaymentMethodRequest { /// Payment method's ID #[serde(skip_deserializing)] pub payment_method_id: String, /// The CVC number for the card #[schema(value_type = Option<String>, example = "242")] pub card_cvc: Option<masking::Secret<String>>, } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardNetworkTokenizeResponse { /// Response for payment method entry in DB pub payment_method_response: Option<PaymentMethodResponse>, /// Customer details #[schema(value_type = CustomerDetails)] pub customer: Option<payments::CustomerDetails>, /// Card network tokenization status pub card_tokenized: bool, /// Error code #[serde(skip_serializing_if = "Option::is_none")] pub error_code: Option<String>, /// Error message #[serde(skip_serializing_if = "Option::is_none")] pub error_message: Option<String>, /// Details that were sent for tokenization #[serde(skip_serializing_if = "Option::is_none")] pub tokenization_data: Option<TokenizeDataRequest>, } impl common_utils::events::ApiEventMetric for CardNetworkTokenizeResponse {} impl From<&Card> for MigrateCardDetail { fn from(card: &Card) -> Self { Self { card_number: masking::Secret::new(card.card_number.get_card_no()), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.name_on_card.clone(), nick_name: card .nick_name .as_ref() .map(|name| masking::Secret::new(name.clone())), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionRequest { /// The customer id for which the payment methods session is to be created #[schema(value_type = String, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::GlobalCustomerId, /// The billing address details of the customer. This will also be used for any new payment methods added during the session #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The return url to which the customer should be redirected to after adding the payment method #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, /// The time (seconds ) when the session will expire /// If not provided, the session will expire in 15 minutes #[schema(example = 900, default = 900)] pub expires_in: Option<u32>, /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data #[schema(value_type = Option<serde_json::Value>)] pub tokenization_data: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodsSessionUpdateRequest { /// The billing address details of the customer. This will also be used for any new payment methods added during the session #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data #[schema(value_type = Option<serde_json::Value>)] pub tokenization_data: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionUpdateSavedPaymentMethod { /// The payment method id of the payment method to be updated #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: id_type::GlobalPaymentMethodId, /// The update request for the payment method update #[serde(flatten)] pub payment_method_update_request: PaymentMethodUpdate, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionDeleteSavedPaymentMethod { /// The payment method id of the payment method to be updated #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: id_type::GlobalPaymentMethodId, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionConfirmRequest { /// The payment method type #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype #[schema(value_type = PaymentMethodType, example = "google_pay")] pub payment_method_subtype: common_enums::PaymentMethodType, /// The payment instrument data to be used for the payment #[schema(value_type = PaymentMethodDataRequest)] pub payment_method_data: payments::PaymentMethodDataRequest, /// The return url to which the customer should be redirected to after adding the payment method #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionResponse { #[schema(value_type = String, example = "12345_pms_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodSessionId, /// The customer id for which the payment methods session is to be created #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] pub customer_id: id_type::GlobalCustomerId, /// The billing address details of the customer. This will also be used for any new payment methods added during the session #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data #[schema(value_type = Option<serde_json::Value>)] pub tokenization_data: Option<pii::SecretSerdeValue>, /// The iso timestamp when the session will expire /// Trying to retrieve the session or any operations on the session after this time will result in an error #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_at: time::PrimitiveDateTime, /// Client Secret #[schema(value_type = String)] pub client_secret: masking::Secret<String>, /// The return url to which the user should be redirected to #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The next action details for the payment method session #[schema(value_type = Option<NextActionData>)] pub next_action: Option<payments::NextActionData>, /// The customer authentication details for the payment method /// This refers to either the payment / external authentication details pub authentication_details: Option<AuthenticationDetails>, /// The payment method that was created using this payment method session #[schema(value_type = Option<Vec<String>>)] pub associated_payment_methods: Option<Vec<String>>, /// The token-id created if there is tokenization_data present #[schema(value_type = Option<String>, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] pub associated_token_id: Option<id_type::GlobalTokenId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema, Clone)] pub struct AuthenticationDetails { /// The status of authentication for the payment method #[schema(value_type = IntentStatus)] pub status: common_enums::IntentStatus, /// Error details of the authentication #[schema(value_type = Option<ErrorDetails>)] pub error: Option<payments::ErrorDetails>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct NetworkTokenStatusCheckSuccessResponse { /// The status of the network token #[schema(value_type = TokenStatus)] pub status: api_enums::TokenStatus, /// The expiry month of the network token if active #[schema(value_type = String)] pub token_expiry_month: masking::Secret<String>, /// The expiry year of the network token if active #[schema(value_type = String)] pub token_expiry_year: masking::Secret<String>, /// The last four digits of the card pub card_last_four: String, /// The last four digits of the network token pub token_last_four: String, /// The expiry date of the card in MM/YY format pub card_expiry: String, /// The payment method ID that was checked #[schema(value_type = String, example = "12345_pm_019959146f92737389eb6927ce1eb7dc")] pub payment_method_id: id_type::GlobalPaymentMethodId, /// The customer ID associated with the payment method #[schema(value_type = String, example = "12345_cus_0195dc62bb8e7312a44484536da76aef")] pub customer_id: id_type::GlobalCustomerId, } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for NetworkTokenStatusCheckResponse {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct NetworkTokenStatusCheckFailureResponse { /// Error message describing what went wrong pub error_message: String, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NetworkTokenStatusCheckResponse { /// Successful network token status check response SuccessResponse(NetworkTokenStatusCheckSuccessResponse), /// Error response for network token status check FailureResponse(NetworkTokenStatusCheckFailureResponse), }
{ "crate": "api_models", "file": "crates/api_models/src/payment_methods.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 14, "num_structs": 107, "num_tables": null, "score": null, "total_crates": null }
file_api_models_2530748742795129748
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/verifications.rs // Contains: 5 structs, 0 enums use common_utils::id_type; /// The request body for verification of merchant (everything except domain_names are prefilled) #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayMerchantVerificationConfigs { pub domain_names: Vec<String>, pub encrypt_to: String, pub partner_internal_merchant_identifier: String, pub partner_merchant_name: String, } /// The derivation point for domain names from request body #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayMerchantVerificationRequest { pub domain_names: Vec<String>, pub merchant_connector_account_id: id_type::MerchantConnectorAccountId, } /// Response to be sent for the verify/applepay api #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayMerchantResponse { pub status_message: String, } /// QueryParams to be send by the merchant for fetching the verified domains #[derive(Debug, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayGetVerifiedDomainsParam { pub merchant_id: id_type::MerchantId, pub merchant_connector_account_id: id_type::MerchantConnectorAccountId, } /// Response to be sent for derivation of the already verified domains #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayVerifiedDomainsResponse { pub verified_domains: Vec<String>, }
{ "crate": "api_models", "file": "crates/api_models/src/verifications.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-5105269492305356165
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/proxy.rs // Contains: 3 structs, 1 enums use std::collections::HashMap; use common_utils::request::Method; use reqwest::header::HeaderMap; use serde::{Deserialize, Serialize}; use serde_json::Value; use utoipa::ToSchema; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Headers(pub HashMap<String, String>); impl Headers { pub fn as_map(&self) -> &HashMap<String, String> { &self.0 } pub fn from_header_map(headers: Option<&HeaderMap>) -> Self { headers .map(|h| { let map = h .iter() .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())) .collect(); Self(map) }) .unwrap_or_else(|| Self(HashMap::new())) } } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct ProxyRequest { /// The request body that needs to be forwarded pub request_body: Value, /// The destination URL where the request needs to be forwarded #[schema(value_type = String, example = "https://api.example.com/endpoint")] pub destination_url: url::Url, /// The headers that need to be forwarded #[schema(value_type = Object, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub headers: Headers, /// The method that needs to be used for the request #[schema(value_type = Method, example = "Post")] pub method: Method, /// The vault token that is used to fetch sensitive data from the vault pub token: String, /// The type of token that is used to fetch sensitive data from the vault #[schema(value_type = TokenType, example = "payment_method_id")] pub token_type: TokenType, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum TokenType { TokenizationId, PaymentMethodId, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct ProxyResponse { /// The response received from the destination pub response: Value, /// The status code of the response pub status_code: u16, /// The headers of the response #[schema(value_type = Object, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub response_headers: Headers, } impl common_utils::events::ApiEventMetric for ProxyRequest {} impl common_utils::events::ApiEventMetric for ProxyResponse {}
{ "crate": "api_models", "file": "crates/api_models/src/proxy.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-4865616609014060893
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/open_router.rs // Contains: 23 structs, 5 enums use std::{collections::HashMap, fmt::Debug}; use common_utils::{errors, id_type, types::MinorUnit}; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, }, }; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::{ enums::{Currency, PaymentMethod}, payment_methods, }; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct OpenRouterDecideGatewayRequest { pub payment_info: PaymentInfo, #[schema(value_type = String)] pub merchant_id: id_type::ProfileId, pub eligible_gateway_list: Option<Vec<String>>, pub ranking_algorithm: Option<RankingAlgorithm>, pub elimination_enabled: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct DecideGatewayResponse { pub decided_gateway: Option<String>, pub gateway_priority_map: Option<serde_json::Value>, pub filter_wise_gateways: Option<serde_json::Value>, pub priority_logic_tag: Option<String>, pub routing_approach: Option<String>, pub gateway_before_evaluation: Option<String>, pub priority_logic_output: Option<PriorityLogicOutput>, pub reset_approach: Option<String>, pub routing_dimension: Option<String>, pub routing_dimension_level: Option<String>, pub is_scheduled_outage: Option<bool>, pub is_dynamic_mga_enabled: Option<bool>, pub gateway_mga_id_map: Option<serde_json::Value>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct PriorityLogicOutput { pub is_enforcement: Option<bool>, pub gws: Option<Vec<String>>, pub priority_logic_tag: Option<String>, pub gateway_reference_ids: Option<HashMap<String, String>>, pub primary_logic: Option<PriorityLogicData>, pub fallback_logic: Option<PriorityLogicData>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PriorityLogicData { pub name: Option<String>, pub status: Option<String>, pub failure_reason: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RankingAlgorithm { SrBasedRouting, PlBasedRouting, NtwBasedRouting, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct PaymentInfo { #[schema(value_type = String)] pub payment_id: id_type::PaymentId, pub amount: MinorUnit, pub currency: Currency, // customerId: Option<ETCu::CustomerId>, // preferredGateway: Option<ETG::Gateway>, pub payment_type: String, pub metadata: Option<String>, // internalMetadata: Option<String>, // isEmi: Option<bool>, // emiBank: Option<String>, // emiTenure: Option<i32>, pub payment_method_type: String, pub payment_method: PaymentMethod, // paymentSource: Option<String>, // authType: Option<ETCa::txn_card_info::AuthType>, // cardIssuerBankName: Option<String>, pub card_isin: Option<String>, // cardType: Option<ETCa::card_type::CardType>, // cardSwitchProvider: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct DecidedGateway { pub gateway_priority_map: Option<HashMap<String, f64>>, pub debit_routing_output: Option<DebitRoutingOutput>, pub routing_approach: String, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct DebitRoutingOutput { pub co_badged_card_networks_info: CoBadgedCardNetworks, pub issuer_country: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, pub card_type: common_enums::CardType, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct CoBadgedCardNetworksInfo { pub network: common_enums::CardNetwork, pub saving_percentage: f64, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct CoBadgedCardNetworks(pub Vec<CoBadgedCardNetworksInfo>); impl CoBadgedCardNetworks { pub fn get_card_networks(&self) -> Vec<common_enums::CardNetwork> { self.0.iter().map(|info| info.network.clone()).collect() } pub fn get_signature_network(&self) -> Option<common_enums::CardNetwork> { self.0 .iter() .find(|info| info.network.is_signature_network()) .map(|info| info.network.clone()) } } impl From<&DebitRoutingOutput> for payment_methods::CoBadgedCardData { fn from(output: &DebitRoutingOutput) -> Self { Self { co_badged_card_networks_info: output.co_badged_card_networks_info.clone(), issuer_country_code: output.issuer_country, is_regulated: output.is_regulated, regulated_name: output.regulated_name.clone(), } } } impl TryFrom<(payment_methods::CoBadgedCardData, String)> for DebitRoutingRequestData { type Error = error_stack::Report<errors::ParsingError>; fn try_from( (output, card_type): (payment_methods::CoBadgedCardData, String), ) -> Result<Self, Self::Error> { let parsed_card_type = card_type.parse::<common_enums::CardType>().map_err(|_| { error_stack::Report::new(errors::ParsingError::EnumParseFailure("CardType")) })?; Ok(Self { co_badged_card_networks_info: output.co_badged_card_networks_info.get_card_networks(), issuer_country: output.issuer_country_code, is_regulated: output.is_regulated, regulated_name: output.regulated_name, card_type: parsed_card_type, }) } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CoBadgedCardRequest { pub merchant_category_code: common_enums::DecisionEngineMerchantCategoryCode, pub acquirer_country: common_enums::CountryAlpha2, pub co_badged_card_data: Option<DebitRoutingRequestData>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DebitRoutingRequestData { pub co_badged_card_networks_info: Vec<common_enums::CardNetwork>, pub issuer_country: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, pub card_type: common_enums::CardType, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ErrorResponse { pub status: String, pub error_code: String, pub error_message: String, pub priority_logic_tag: Option<String>, pub filter_wise_gateways: Option<serde_json::Value>, pub error_info: UnifiedError, pub is_dynamic_mga_enabled: bool, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct UnifiedError { pub code: String, pub user_message: String, pub developer_message: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)] #[serde(rename_all = "camelCase")] pub struct UpdateScorePayload { #[schema(value_type = String)] pub merchant_id: id_type::ProfileId, pub gateway: String, pub status: TxnStatus, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] pub struct UpdateScoreResponse { pub message: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TxnStatus { Started, AuthenticationFailed, JuspayDeclined, PendingVbv, VBVSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CODInitiated, Voided, VoidedPostCharge, VoidInitiated, Nop, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, ToBeCharged, Pending, Failure, Declined, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct DecisionEngineConfigSetupRequest { pub merchant_id: String, pub config: DecisionEngineConfigVariant, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GetDecisionEngineConfigRequest { pub merchant_id: String, pub algorithm: DecisionEngineDynamicAlgorithmType, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub enum DecisionEngineDynamicAlgorithmType { SuccessRate, Elimination, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(tag = "type", content = "data")] #[serde(rename_all = "camelCase")] pub enum DecisionEngineConfigVariant { SuccessRate(DecisionEngineSuccessRateData), Elimination(DecisionEngineEliminationData), } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineSuccessRateData { pub default_latency_threshold: Option<f64>, pub default_bucket_size: Option<i32>, pub default_hedging_percent: Option<f64>, pub default_lower_reset_factor: Option<f64>, pub default_upper_reset_factor: Option<f64>, pub default_gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>, pub sub_level_input_config: Option<Vec<DecisionEngineSRSubLevelInputConfig>>, } impl DecisionEngineSuccessRateData { pub fn update(&mut self, new_config: Self) { if let Some(threshold) = new_config.default_latency_threshold { self.default_latency_threshold = Some(threshold); } if let Some(bucket_size) = new_config.default_bucket_size { self.default_bucket_size = Some(bucket_size); } if let Some(hedging_percent) = new_config.default_hedging_percent { self.default_hedging_percent = Some(hedging_percent); } if let Some(lower_reset_factor) = new_config.default_lower_reset_factor { self.default_lower_reset_factor = Some(lower_reset_factor); } if let Some(upper_reset_factor) = new_config.default_upper_reset_factor { self.default_upper_reset_factor = Some(upper_reset_factor); } if let Some(gateway_extra_score) = new_config.default_gateway_extra_score { self.default_gateway_extra_score .as_mut() .map(|score| score.extend(gateway_extra_score)); } if let Some(sub_level_input_config) = new_config.sub_level_input_config { self.sub_level_input_config.as_mut().map(|config| { config.extend(sub_level_input_config); }); } } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineSRSubLevelInputConfig { pub payment_method_type: Option<String>, pub payment_method: Option<String>, pub latency_threshold: Option<f64>, pub bucket_size: Option<i32>, pub hedging_percent: Option<f64>, pub lower_reset_factor: Option<f64>, pub upper_reset_factor: Option<f64>, pub gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>, } impl DecisionEngineSRSubLevelInputConfig { pub fn update(&mut self, new_config: Self) { if let Some(payment_method_type) = new_config.payment_method_type { self.payment_method_type = Some(payment_method_type); } if let Some(payment_method) = new_config.payment_method { self.payment_method = Some(payment_method); } if let Some(latency_threshold) = new_config.latency_threshold { self.latency_threshold = Some(latency_threshold); } if let Some(bucket_size) = new_config.bucket_size { self.bucket_size = Some(bucket_size); } if let Some(hedging_percent) = new_config.hedging_percent { self.hedging_percent = Some(hedging_percent); } if let Some(lower_reset_factor) = new_config.lower_reset_factor { self.lower_reset_factor = Some(lower_reset_factor); } if let Some(upper_reset_factor) = new_config.upper_reset_factor { self.upper_reset_factor = Some(upper_reset_factor); } if let Some(gateway_extra_score) = new_config.gateway_extra_score { self.gateway_extra_score .as_mut() .map(|score| score.extend(gateway_extra_score)); } } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineGatewayWiseExtraScore { pub gateway_name: String, pub gateway_sigma_factor: f64, } impl DecisionEngineGatewayWiseExtraScore { pub fn update(&mut self, new_config: Self) { self.gateway_name = new_config.gateway_name; self.gateway_sigma_factor = new_config.gateway_sigma_factor; } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineEliminationData { pub threshold: f64, } impl DecisionEngineEliminationData { pub fn update(&mut self, new_config: Self) { self.threshold = new_config.threshold; } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct MerchantAccount { pub merchant_id: String, pub gateway_success_rate_based_decider_input: Option<String>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct FetchRoutingConfig { pub merchant_id: String, pub algorithm: AlgorithmType, } #[derive(Debug, Serialize, Deserialize, Clone, Copy)] #[serde(rename_all = "camelCase")] pub enum AlgorithmType { SuccessRate, Elimination, DebitRouting, }
{ "crate": "api_models", "file": "crates/api_models/src/open_router.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 5, "num_structs": 23, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-7122072980695273820
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/refunds.rs // Contains: 19 structs, 3 enums use std::collections::HashMap; pub use common_utils::types::MinorUnit; use common_utils::{pii, types::TimeRange}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use super::payments::AmountFilter; #[cfg(feature = "v1")] use crate::admin; use crate::{admin::MerchantConnectorInfo, enums}; #[cfg(feature = "v1")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundRequest { /// The payment id against which refund is to be initiated #[schema( max_length = 30, min_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: common_utils::id_type::PaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. If this is not passed by the merchant, this field shall be auto generated and provided in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: Option<String>, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the full payment amount #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] pub amount: Option<MinorUnit>, /// Reason for the refund. Often useful for displaying to users and your customer support executive. In case the payment went through Stripe, this field needs to be passed with one of these enums: `duplicate`, `fraudulent`, or `requested_by_customer` #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// To indicate whether to refund needs to be instant or scheduled. Default value is instant #[schema(default = "Instant", example = "Instant")] pub refund_type: Option<RefundType>, /// 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>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>)] pub split_refunds: Option<common_types::refunds::SplitRefund>, } #[cfg(feature = "v2")] #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundsCreateRequest { /// The payment id against which refund is initiated #[schema( max_length = 30, min_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: common_utils::id_type::GlobalPaymentId, /// Unique Identifier for the Refund given by the Merchant. #[schema( max_length = 64, min_length = 1, example = "ref_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub merchant_reference_id: common_utils::id_type::RefundReferenceId, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the amount_captured of the payment #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] pub amount: Option<MinorUnit>, /// Reason for the refund. Often useful for displaying to users and your customer support executive. #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// To indicate whether to refund needs to be instant or scheduled. Default value is instant #[schema(default = "Instant", example = "Instant")] pub refund_type: Option<RefundType>, /// 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>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v1")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrieveBody { pub force_sync: Option<bool>, } #[cfg(feature = "v2")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrieveBody { pub force_sync: Option<bool>, } #[cfg(feature = "v2")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrievePayload { /// `force_sync` with the connector to get refund details pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v1")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RefundsRetrieveRequest { /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: String, /// `force_sync` with the connector to get refund details /// (defaults to false) pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RefundsRetrieveRequest { /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: common_utils::id_type::GlobalRefundId, /// `force_sync` with the connector to get refund details /// (defaults to false) pub force_sync: Option<bool>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundUpdateRequest { #[serde(skip)] pub refund_id: String, /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// 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>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundMetadataUpdateRequest { /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// 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>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundManualUpdateRequest { #[serde(skip)] pub refund_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The status for refund pub status: Option<RefundStatus>, /// The code for the error pub error_code: Option<String>, /// The error message pub error_message: Option<String>, } #[cfg(feature = "v1")] /// To indicate whether to refund needs to be instant or scheduled #[derive( Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, )] #[serde(rename_all = "snake_case")] pub enum RefundType { Scheduled, #[default] Instant, } #[cfg(feature = "v2")] /// To indicate whether the refund needs to be instant or scheduled #[derive( Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, )] #[serde(rename_all = "snake_case")] pub enum RefundType { Scheduled, #[default] Instant, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { /// Unique Identifier for the refund pub refund_id: String, /// The payment id against which refund is initiated #[schema(value_type = String)] pub payment_id: common_utils::id_type::PaymentId, /// The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc #[schema(value_type = i64 , minimum = 100, example = 6540)] pub amount: MinorUnit, /// The three-letter ISO currency code pub currency: String, /// The status for refund pub status: RefundStatus, /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive pub reason: Option<String>, /// 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>)] pub metadata: Option<pii::SecretSerdeValue>, /// The error message pub error_message: Option<String>, /// The code for the error pub error_code: Option<String>, /// Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// The timestamp at which refund is created #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, /// The timestamp at which refund is updated #[serde(with = "common_utils::custom_serde::iso8601::option")] pub updated_at: Option<PrimitiveDateTime>, /// The connector used for the refund and the corresponding payment #[schema(example = "stripe")] pub connector: String, /// The id of business profile for this refund #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The merchant_connector_id of the processor through which this payment went through #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>,)] pub split_refunds: Option<common_types::refunds::SplitRefund>, /// Error code received from the issuer in case of failed refunds pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed refunds pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] impl RefundResponse { pub fn get_refund_id_as_string(&self) -> String { self.refund_id.clone() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { /// Global Refund Id for the refund #[schema(value_type = String)] pub id: common_utils::id_type::GlobalRefundId, /// The payment id against which refund is initiated #[schema(value_type = String)] pub payment_id: common_utils::id_type::GlobalPaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4", value_type = Option<String>, )] pub merchant_reference_id: Option<common_utils::id_type::RefundReferenceId>, /// The refund amount #[schema(value_type = i64 , minimum = 100, example = 6540)] pub amount: MinorUnit, /// The three-letter ISO currency code #[schema(value_type = Currency)] pub currency: common_enums::Currency, /// The status for refund pub status: RefundStatus, /// An arbitrary string attached to the object pub reason: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, /// The error details for the refund pub error_details: Option<RefundErrorDetails>, /// The timestamp at which refund is created #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The timestamp at which refund is updated #[serde(with = "common_utils::custom_serde::iso8601")] pub updated_at: PrimitiveDateTime, /// The connector used for the refund and the corresponding payment #[schema(example = "stripe", value_type = Connector)] pub connector: enums::Connector, /// The id of business profile for this refund #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, /// The merchant_connector_id of the processor through which this payment went through #[schema(value_type = String)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// The reference id of the connector for the refund pub connector_refund_reference_id: Option<String>, } #[cfg(feature = "v2")] impl RefundResponse { pub fn get_refund_id_as_string(&self) -> String { self.id.get_string_repr().to_owned() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundErrorDetails { pub code: String, pub message: String, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundListRequest { /// The identifier for the payment #[schema(value_type = Option<String>)] pub payment_id: Option<common_utils::id_type::PaymentId>, /// The identifier for the refund pub refund_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// Limit on the number of objects to return pub limit: Option<i64>, /// The starting point within a list of objects pub offset: Option<i64>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc) #[serde(flatten)] pub time_range: Option<TimeRange>, /// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range) pub amount_filter: Option<AmountFilter>, /// The list of connectors to filter refunds list pub connector: Option<Vec<String>>, /// The list of merchant connector ids to filter the refunds list for selected label #[schema(value_type = Option<Vec<String>>)] pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, /// The list of currencies to filter refunds list #[schema(value_type = Option<Vec<Currency>>)] pub currency: Option<Vec<enums::Currency>>, /// The list of refund statuses to filter refunds list #[schema(value_type = Option<Vec<RefundStatus>>)] pub refund_status: Option<Vec<enums::RefundStatus>>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundListRequest { /// The identifier for the payment #[schema(value_type = Option<String>)] pub payment_id: Option<common_utils::id_type::GlobalPaymentId>, /// The identifier for the refund #[schema(value_type = String)] pub refund_id: Option<common_utils::id_type::GlobalRefundId>, /// Limit on the number of objects to return pub limit: Option<i64>, /// The starting point within a list of objects pub offset: Option<i64>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc) #[serde(flatten)] pub time_range: Option<TimeRange>, /// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range) pub amount_filter: Option<AmountFilter>, /// The list of connectors to filter refunds list pub connector: Option<Vec<String>>, /// The list of merchant connector ids to filter the refunds list for selected label #[schema(value_type = Option<Vec<String>>)] pub connector_id_list: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, /// The list of currencies to filter refunds list #[schema(value_type = Option<Vec<Currency>>)] pub currency: Option<Vec<enums::Currency>>, /// The list of refund statuses to filter refunds list #[schema(value_type = Option<Vec<RefundStatus>>)] pub refund_status: Option<Vec<enums::RefundStatus>>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)] pub struct RefundListResponse { /// The number of refunds included in the list pub count: usize, /// The total number of refunds in the list pub total_count: i64, /// The List of refund response object pub data: Vec<RefundResponse>, } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, ToSchema)] pub struct RefundListMetaData { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<enums::Currency>, /// The list of available refund status filters #[schema(value_type = Vec<RefundStatus>)] pub refund_status: Vec<enums::RefundStatus>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RefundListFilters { /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<enums::Currency>, /// The list of available refund status filters #[schema(value_type = Vec<RefundStatus>)] pub refund_status: Vec<enums::RefundStatus>, } #[derive(Clone, Debug, serde::Serialize)] pub struct RefundAggregateResponse { /// The list of refund status with their count pub status_with_count: HashMap<enums::RefundStatus, i64>, } /// The status for refunds #[derive( Debug, Eq, Clone, Copy, PartialEq, Default, Deserialize, Serialize, ToSchema, strum::Display, strum::EnumIter, )] #[serde(rename_all = "snake_case")] pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, } impl From<enums::RefundStatus> for RefundStatus { fn from(status: enums::RefundStatus) -> Self { match status { enums::RefundStatus::Failure | enums::RefundStatus::TransactionFailure => Self::Failed, enums::RefundStatus::ManualReview => Self::Review, enums::RefundStatus::Pending => Self::Pending, enums::RefundStatus::Success => Self::Succeeded, } } } impl From<RefundStatus> for enums::RefundStatus { fn from(status: RefundStatus) -> Self { match status { RefundStatus::Failed => Self::Failure, RefundStatus::Review => Self::ManualReview, RefundStatus::Pending => Self::Pending, RefundStatus::Succeeded => Self::Success, } } }
{ "crate": "api_models", "file": "crates/api_models/src/refunds.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 19, "num_tables": null, "score": null, "total_crates": null }
file_api_models_1872883387646498525
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/organization.rs // Contains: 5 structs, 0 enums use common_enums::OrganizationType; use common_utils::{id_type, pii}; use utoipa::ToSchema; pub struct OrganizationNew { pub org_id: id_type::OrganizationId, pub org_type: OrganizationType, pub org_name: Option<String>, } impl OrganizationNew { pub fn new(org_type: OrganizationType, org_name: Option<String>) -> Self { Self { org_id: id_type::OrganizationId::default(), org_type, org_name, } } } #[derive(Clone, Debug, serde::Serialize)] pub struct OrganizationId { pub organization_id: id_type::OrganizationId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OrganizationCreateRequest { /// Name of the organization pub organization_name: String, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OrganizationUpdateRequest { /// Name of the organization pub organization_name: Option<String>, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, /// Platform merchant id is unique distiguisher for special merchant in the platform org #[schema(value_type = String)] pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct OrganizationResponse { /// The unique identifier for the Organization #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: id_type::OrganizationId, /// Name of the Organization pub organization_name: Option<String>, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: time::PrimitiveDateTime, pub created_at: time::PrimitiveDateTime, /// Organization Type of the organization #[schema(value_type = Option<OrganizationType>, example = "standard")] pub organization_type: Option<OrganizationType>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct OrganizationResponse { /// The unique identifier for the Organization #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub id: id_type::OrganizationId, /// Name of the Organization pub organization_name: Option<String>, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: time::PrimitiveDateTime, pub created_at: time::PrimitiveDateTime, /// Organization Type of the organization #[schema(value_type = Option<OrganizationType>, example = "standard")] pub organization_type: Option<OrganizationType>, }
{ "crate": "api_models", "file": "crates/api_models/src/organization.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_api_models_7259240787410408945
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/payouts.rs // Contains: 29 structs, 6 enums use std::collections::HashMap; use cards::CardNumber; #[cfg(feature = "v2")] use common_utils::types::BrowserInformation; use common_utils::{ consts::default_payouts_list_limit, crypto, id_type, link_utils, payout_method_utils, pii::{self, Email}, transformers::ForeignFrom, types::{UnifiedCode, UnifiedMessage}, }; use masking::Secret; #[cfg(feature = "v1")] use payments::BrowserInformation; use router_derive::FlatStruct; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{enums as api_enums, payment_methods::RequiredFieldInfo, payments}; #[derive(Debug, Serialize, Clone, ToSchema)] pub enum PayoutRequest { PayoutActionRequest(PayoutActionRequest), PayoutCreateRequest(Box<PayoutCreateRequest>), PayoutRetrieveRequest(PayoutRetrieveRequest), } #[derive( Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PayoutCreateRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts that have been done by a single merchant. This field is auto generated and is returned in the API response, **not required to be included in the Payout Create/Update Request.** #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub payout_id: Option<id_type::PayoutId>, /// This is an identifier for the merchant account. This is inferred from the API key provided during the request, **not required to be included in the Payout Create/Update Request.** #[schema(max_length = 255, value_type = Option<String>, example = "merchant_1668273825")] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported. #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = Option<u64>, example = 1000)] #[mandatory_in(PayoutsCreateRequest = u64)] #[remove_in(PayoutsConfirmRequest)] #[serde(default, deserialize_with = "payments::amount::deserialize_option")] pub amount: Option<payments::Amount>, /// The currency of the payout request can be specified here #[schema(value_type = Option<Currency>, example = "USD")] #[mandatory_in(PayoutsCreateRequest = Currency)] #[remove_in(PayoutsConfirmRequest)] pub currency: Option<api_enums::Currency>, /// Specifies routing algorithm for selecting a connector #[schema(value_type = Option<StaticRoutingAlgorithm>, example = json!({ "type": "single", "data": "adyen" }))] pub routing: Option<serde_json::Value>, /// This field allows the merchant to manually select a connector with which the payout can go through. #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// This field is used when merchant wants to confirm the payout, thus useful for the payout _Confirm_ request. Ideally merchants should _Create_ a payout, _Update_ it (if required), then _Confirm_ it. #[schema(value_type = Option<bool>, example = true, default = false)] #[remove_in(PayoutConfirmRequest)] pub confirm: Option<bool>, /// The payout_type of the payout request can be specified here, this is a mandatory field to _Confirm_ the payout, i.e., should be passed in _Create_ request, if not then should be updated in the payout _Update_ request, then only it can be confirmed. #[schema(value_type = Option<PayoutType>, example = "card")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method information required for carrying out a payout #[schema(value_type = Option<PayoutMethodData>)] pub payout_method_data: Option<PayoutMethodData>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = Option<bool>, example = true, default = false)] pub auto_fulfill: Option<bool>, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. _Deprecated: Use customer_id instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetails>)] pub customer: Option<payments::CustomerDetails>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PayoutsCreateRequest)] #[mandatory_in(PayoutConfirmRequest = String)] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "US", value_type = Option<CountryAlpha2>)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to, select from the given list of options #[schema(value_type = Option<PayoutEntityType>, example = "Individual")] pub entity_type: Option<api_enums::PayoutEntityType>, /// Specifies whether or not the payout request is recurring #[schema(value_type = Option<bool>, default = false)] pub recurring: Option<bool>, /// 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>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Provide a reference to a stored payout method, used to process the payout. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432", value_type = Option<String>)] pub payout_token: Option<String>, /// The business profile to use for this payout, especially if there are multiple business profiles associated with the account, otherwise default business profile associated with the merchant account will be used. #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The send method which will be required for processing payouts, check options for better understanding. #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// Whether to get the payout link (if applicable). Merchant need to specify this during the Payout _Create_, this field can not be updated during Payout _Update_. #[schema(default = false, example = true, value_type = Option<bool>)] pub payout_link: Option<bool>, /// Custom payout link config for the particular payout, if payout link is to be generated. #[schema(value_type = Option<PayoutCreatePayoutLinkConfig>)] pub payout_link_config: Option<PayoutCreatePayoutLinkConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: Option<Secret<String>>, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// Identifier for payout method pub payout_method_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<BrowserInformation>, } impl PayoutCreateRequest { pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } } /// Custom payout link config for the particular payout, if payout link is to be generated. #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] pub struct PayoutCreatePayoutLinkConfig { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub payout_link_id: Option<String>, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// List of payout methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, /// Form layout of the payout link #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] pub form_layout: Option<api_enums::UIWidgetFormLayout>, /// `test_mode` allows for opening payout links without any restrictions. This removes /// - domain name validations /// - check for making sure link is accessed within an iframe #[schema(value_type = Option<bool>, example = false)] pub test_mode: Option<bool>, } /// The payout method information required for carrying out a payout #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodData { Card(CardPayout), Bank(Bank), Wallet(Wallet), BankRedirect(BankRedirect), } impl Default for PayoutMethodData { fn default() -> Self { Self::Card(CardPayout::default()) } } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct CardPayout { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String)] pub expiry_month: Secret<String>, /// The card's expiry year #[schema(value_type = String)] pub expiry_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(untagged)] pub enum Bank { Ach(AchBankTransfer), Bacs(BacsBankTransfer), Sepa(SepaBankTransfer), Pix(PixBankTransfer), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct AchBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [9 digits] Routing number - used in USA for identifying a specific bank. #[schema(value_type = String, example = "110000000")] pub bank_routing_number: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct BacsBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [6 digits] Sort Code - used in UK and Ireland for identifying a bank and it's branches. #[schema(value_type = String, example = "98-76-54")] pub bank_sort_code: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] // The SEPA (Single Euro Payments Area) is a pan-European network that allows you to send and receive payments in euros between two cross-border bank accounts in the eurozone. pub struct SepaBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// International Bank Account Number (iban) - used in many countries for identifying a bank along with it's customer. #[schema(value_type = String, example = "DE89370400440532013000")] pub iban: Secret<String>, /// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches #[schema(value_type = String, example = "HSBCGB2LXXX")] pub bic: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct PixBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank branch #[schema(value_type = Option<String>, example = "3707")] pub bank_branch: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// Unique key for pix customer #[schema(value_type = String, example = "000123456")] pub pix_key: Secret<String>, /// Individual taxpayer identification number #[schema(value_type = Option<String>, example = "000123456")] pub tax_id: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum Wallet { ApplePayDecrypt(ApplePayDecrypt), Paypal(Paypal), Venmo(Venmo), } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirect { Interac(Interac), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Interac { /// Customer email linked with interac account #[schema(value_type = String, example = "john.doe@example.com")] pub email: Email, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Paypal { /// Email linked with paypal account #[schema(value_type = String, example = "john.doe@example.com")] pub email: Option<Email>, /// mobile number linked to paypal account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, /// id of the paypal account #[schema(value_type = String, example = "G83KXTJ5EHCQ2")] pub paypal_id: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Venmo { /// mobile number linked to venmo account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct ApplePayDecrypt { /// The dpan number associated with card number #[schema(value_type = String, example = "4242424242424242")] pub dpan: CardNumber, /// The card's expiry month #[schema(value_type = String)] pub expiry_month: Secret<String>, /// The card's expiry year #[schema(value_type = String)] pub expiry_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } #[derive(Debug, ToSchema, Clone, Serialize, router_derive::PolymorphicSchema)] #[serde(deny_unknown_fields)] pub struct PayoutCreateResponse { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, value_type = String, example = "merchant_1668273825")] pub merchant_id: id_type::MerchantId, /// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported. #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 1000)] pub amount: common_utils::types::MinorUnit, /// Recipient's currency for the payout request #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// The connector used for the payout #[schema(example = "wise")] pub connector: Option<String>, /// The payout method that is to be used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method details for the payout #[schema(value_type = Option<PayoutMethodDataResponse>, example = json!(r#"{ "card": { "last4": "2503", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": null, "payment_checks": null, "authentication_data": null } }"#))] pub payout_method_data: Option<PayoutMethodDataResponse>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = bool, example = true, default = false)] pub auto_fulfill: bool, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetailsResponse>)] pub customer: Option<payments::CustomerDetailsResponse>, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout #[schema(example = "US", value_type = CountryAlpha2)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout #[schema(example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: api_enums::PayoutEntityType, /// Specifies whether or not the payout request is recurring #[schema(value_type = bool, default = false)] pub recurring: bool, /// 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>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Unique identifier of the merchant connector account #[schema(value_type = Option<String>, example = "mca_sAD3OZLATetvjLOYhUSy")] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Current status of the Payout #[schema(value_type = PayoutStatus, example = RequiresConfirmation)] pub status: api_enums::PayoutStatus, /// If there was an error while calling the connector the error message is received here #[schema(value_type = Option<String>, example = "Failed while verifying the card")] pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(value_type = Option<String>, example = "E0001")] pub error_code: Option<String>, /// The business profile that is associated with this payout #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Time when the payout was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Underlying processor's payout resource ID #[schema(value_type = Option<String>, example = "S3FC9G9M2MVFDXT5")] pub connector_transaction_id: Option<String>, /// Payout's send priority (if applicable) #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// List of attempts #[schema(value_type = Option<Vec<PayoutAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PayoutAttemptResponse>>, /// If payout link was requested, this contains the link's ID and the URL to render the payout widget #[schema(value_type = Option<PayoutLinkResponse>)] pub payout_link: Option<PayoutLinkResponse>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: crypto::OptionalEncryptableName, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, /// Identifier for payout method pub payout_method_id: Option<String>, } /// The payout method information for response #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodDataResponse { #[schema(value_type = CardAdditionalData)] Card(Box<payout_method_utils::CardAdditionalData>), #[schema(value_type = BankAdditionalData)] Bank(Box<payout_method_utils::BankAdditionalData>), #[schema(value_type = WalletAdditionalData)] Wallet(Box<payout_method_utils::WalletAdditionalData>), #[schema(value_type = BankRedirectAdditionalData)] BankRedirect(Box<payout_method_utils::BankRedirectAdditionalData>), } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct PayoutAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = PayoutStatus, example = "failed")] pub status: api_enums::PayoutStatus, /// The payout attempt amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6583)] pub amount: common_utils::types::MinorUnit, /// The currency of the amount of the payout attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<api_enums::Currency>, /// The connector used for the payout pub connector: Option<String>, /// Connector's error code in case of failures pub error_code: Option<String>, /// Connector's error message in case of failures pub error_message: Option<String>, /// The payout method that was used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payment_method: Option<api_enums::PayoutType>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "bacs")] pub payout_method_type: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payout provided by the connector pub connector_transaction_id: Option<String>, /// If the payout was cancelled the reason provided here pub cancellation_reason: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, } #[derive(Default, Debug, Clone, Deserialize, ToSchema)] pub struct PayoutRetrieveBody { pub force_sync: Option<bool>, #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive(Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutRetrieveRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, /// `force_sync` with the connector to get payout details /// (defaults to false) #[schema(value_type = Option<bool>, default = false, example = true)] pub force_sync: Option<bool>, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive(Debug, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PayoutCancelRequest, PayoutFulfillRequest)] pub struct PayoutActionRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, } #[derive(Default, Debug, ToSchema, Clone, Deserialize)] pub struct PayoutVendorAccountDetails { pub vendor_details: PayoutVendorDetails, pub individual_details: PayoutIndividualDetails, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutVendorDetails { pub account_type: String, pub business_type: String, pub business_profile_mcc: Option<i32>, pub business_profile_url: Option<String>, pub business_profile_name: Option<Secret<String>>, pub company_address_line1: Option<Secret<String>>, pub company_address_line2: Option<Secret<String>>, pub company_address_postal_code: Option<Secret<String>>, pub company_address_city: Option<Secret<String>>, pub company_address_state: Option<Secret<String>>, pub company_phone: Option<Secret<String>>, pub company_tax_id: Option<Secret<String>>, pub company_owners_provided: Option<bool>, pub capabilities_card_payments: Option<bool>, pub capabilities_transfers: Option<bool>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutIndividualDetails { pub tos_acceptance_date: Option<i64>, pub tos_acceptance_ip: Option<Secret<String>>, pub individual_dob_day: Option<Secret<String>>, pub individual_dob_month: Option<Secret<String>>, pub individual_dob_year: Option<Secret<String>>, pub individual_id_number: Option<Secret<String>>, pub individual_ssn_last_4: Option<Secret<String>>, pub external_account_account_holder_type: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListConstraints { /// The identifier for customer #[schema(value_type = Option<String>, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "payout_fafa124123", value_type = Option<String>,)] pub starting_after: Option<id_type::PayoutId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "payout_fafa124123", value_type = Option<String>,)] pub ending_before: Option<id_type::PayoutId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The time at which payout is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListFilterConstraints { /// The identifier for payout #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: Option<id_type::PayoutId>, /// The merchant order reference ID for payout #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[schema(value_type = Option<String>,example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payouts list #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// The list of currencies to filter payouts list #[schema(value_type = Currency, example = "USD")] pub currency: Option<Vec<api_enums::Currency>>, /// The list of payout status to filter payouts list #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["pending", "failed"]))] pub status: Option<Vec<api_enums::PayoutStatus>>, /// The list of payout methods to filter payouts list #[schema(value_type = Option<Vec<PayoutType>>, example = json!(["bank", "card"]))] pub payout_method: Option<Vec<common_enums::PayoutType>>, /// Type of recipient #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: Option<common_enums::PayoutEntityType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListResponse { /// The number of payouts included in the list pub size: usize, /// The list of payouts response objects pub data: Vec<PayoutCreateResponse>, /// The total number of available payouts for given constraints #[serde(skip_serializing_if = "Option::is_none")] pub total_count: Option<i64>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListFilters { /// The list of available connector filters #[schema(value_type = Vec<PayoutConnectors>)] pub connector: Vec<api_enums::PayoutConnectors>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<common_enums::Currency>, /// The list of available payout status filters #[schema(value_type = Vec<PayoutStatus>)] pub status: Vec<common_enums::PayoutStatus>, /// The list of available payout method filters #[schema(value_type = Vec<PayoutType>)] pub payout_method: Vec<common_enums::PayoutType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutLinkResponse { pub payout_link_id: String, #[schema(value_type = String)] pub link: Secret<url::Url>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PayoutLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payout_id: id_type::PayoutId, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkDetails { pub publishable_key: Secret<String>, pub client_secret: Secret<String>, pub payout_link_id: String, pub payout_id: id_type::PayoutId, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>, pub enabled_payment_methods_with_required_fields: Vec<PayoutEnabledPaymentMethodsInfo>, pub amount: common_utils::types::StringMajorUnit, pub currency: common_enums::Currency, pub locale: String, pub form_layout: Option<common_enums::UIWidgetFormLayout>, pub test_mode: bool, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutEnabledPaymentMethodsInfo { pub payment_method: common_enums::PaymentMethod, pub payment_method_types_info: Vec<PaymentMethodTypeInfo>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodTypeInfo { pub payment_method_type: common_enums::PaymentMethodType, pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, } #[derive(Clone, Debug, serde::Serialize, FlatStruct)] pub struct RequiredFieldsOverrideRequest { pub billing: Option<payments::Address>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkStatusDetails { pub payout_link_id: String, pub payout_id: id_type::PayoutId, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: api_enums::PayoutStatus, pub error_code: Option<UnifiedCode>, pub error_message: Option<UnifiedMessage>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub test_mode: bool, } impl From<Bank> for payout_method_utils::BankAdditionalData { fn from(bank_data: Bank) -> Self { match bank_data { Bank::Ach(AchBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_routing_number, }) => Self::Ach(Box::new( payout_method_utils::AchBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_routing_number: bank_routing_number.into(), }, )), Bank::Bacs(BacsBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_sort_code, }) => Self::Bacs(Box::new( payout_method_utils::BacsBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_sort_code: bank_sort_code.into(), }, )), Bank::Sepa(SepaBankTransfer { bank_name, bank_country_code, bank_city, iban, bic, }) => Self::Sepa(Box::new( payout_method_utils::SepaBankTransferAdditionalData { bank_name, bank_country_code, bank_city, iban: iban.into(), bic: bic.map(From::from), }, )), Bank::Pix(PixBankTransfer { bank_name, bank_branch, bank_account_number, pix_key, tax_id, }) => Self::Pix(Box::new( payout_method_utils::PixBankTransferAdditionalData { bank_name, bank_branch, bank_account_number: bank_account_number.into(), pix_key: pix_key.into(), tax_id: tax_id.map(From::from), }, )), } } } impl From<Wallet> for payout_method_utils::WalletAdditionalData { fn from(wallet_data: Wallet) -> Self { match wallet_data { Wallet::Paypal(Paypal { email, telephone_number, paypal_id, }) => Self::Paypal(Box::new(payout_method_utils::PaypalAdditionalData { email: email.map(ForeignFrom::foreign_from), telephone_number: telephone_number.map(From::from), paypal_id: paypal_id.map(From::from), })), Wallet::Venmo(Venmo { telephone_number }) => { Self::Venmo(Box::new(payout_method_utils::VenmoAdditionalData { telephone_number: telephone_number.map(From::from), })) } Wallet::ApplePayDecrypt(ApplePayDecrypt { expiry_month, expiry_year, card_holder_name, .. }) => Self::ApplePayDecrypt(Box::new( payout_method_utils::ApplePayDecryptAdditionalData { card_exp_month: expiry_month, card_exp_year: expiry_year, card_holder_name, }, )), } } } impl From<BankRedirect> for payout_method_utils::BankRedirectAdditionalData { fn from(bank_redirect: BankRedirect) -> Self { match bank_redirect { BankRedirect::Interac(Interac { email }) => { Self::Interac(Box::new(payout_method_utils::InteracAdditionalData { email: Some(ForeignFrom::foreign_from(email)), })) } } } } impl From<payout_method_utils::AdditionalPayoutMethodData> for PayoutMethodDataResponse { fn from(additional_data: payout_method_utils::AdditionalPayoutMethodData) -> Self { match additional_data { payout_method_utils::AdditionalPayoutMethodData::Card(card_data) => { Self::Card(card_data) } payout_method_utils::AdditionalPayoutMethodData::Bank(bank_data) => { Self::Bank(bank_data) } payout_method_utils::AdditionalPayoutMethodData::Wallet(wallet_data) => { Self::Wallet(wallet_data) } payout_method_utils::AdditionalPayoutMethodData::BankRedirect(bank_redirect) => { Self::BankRedirect(bank_redirect) } } } }
{ "crate": "api_models", "file": "crates/api_models/src/payouts.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 6, "num_structs": 29, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-4264282824852825661
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/cards_info.rs // Contains: 7 structs, 1 enums use std::fmt::Debug; use common_utils::events::ApiEventMetric; use utoipa::ToSchema; use crate::enums; #[derive(serde::Deserialize, ToSchema)] pub struct CardsInfoRequestParams { #[schema(example = "pay_OSERgeV9qAy7tlK7aKpc_secret_TuDUoh11Msxh12sXn3Yp")] pub client_secret: Option<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CardsInfoRequest { pub client_secret: Option<String>, pub card_iin: String, } #[derive(serde::Serialize, Debug, ToSchema)] pub struct CardInfoResponse { #[schema(example = "374431")] pub card_iin: String, #[schema(example = "AMEX")] pub card_issuer: Option<String>, #[schema(example = "AMEX")] pub card_network: Option<String>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "CLASSIC")] pub card_sub_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, } #[derive(serde::Serialize, Debug, ToSchema)] pub struct CardInfoMigrateResponseRecord { pub card_iin: Option<String>, pub card_issuer: Option<String>, pub card_network: Option<String>, pub card_type: Option<String>, pub card_sub_type: Option<String>, pub card_issuing_country: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardInfoCreateRequest { pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub last_updated_provider: Option<String>, } impl ApiEventMetric for CardInfoCreateRequest {} #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardInfoUpdateRequest { pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub last_updated_provider: Option<String>, pub line_number: Option<i64>, } impl ApiEventMetric for CardInfoUpdateRequest {} #[derive(Debug, Default, serde::Serialize)] pub enum CardInfoMigrationStatus { Success, #[default] Failed, } #[derive(Debug, Default, serde::Serialize)] pub struct CardInfoMigrationResponse { pub line_number: Option<i64>, pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<String>, pub card_type: Option<String>, pub card_sub_type: Option<String>, pub card_issuing_country: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub migration_error: Option<String>, pub migration_status: CardInfoMigrationStatus, } impl ApiEventMetric for CardInfoMigrationResponse {} type CardInfoMigrationResponseType = ( Result<CardInfoMigrateResponseRecord, String>, CardInfoUpdateRequest, ); impl From<CardInfoMigrationResponseType> for CardInfoMigrationResponse { fn from((response, record): CardInfoMigrationResponseType) -> Self { match response { Ok(res) => Self { card_iin: record.card_iin, line_number: record.line_number, card_issuer: res.card_issuer, card_network: res.card_network, card_type: res.card_type, card_sub_type: res.card_sub_type, card_issuing_country: res.card_issuing_country, migration_status: CardInfoMigrationStatus::Success, migration_error: None, }, Err(e) => Self { card_iin: record.card_iin, migration_status: CardInfoMigrationStatus::Failed, migration_error: Some(e), line_number: record.line_number, ..Self::default() }, } } }
{ "crate": "api_models", "file": "crates/api_models/src/cards_info.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 7, "num_tables": null, "score": null, "total_crates": null }
file_api_models_9218903494490089038
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/revenue_recovery_data_backfill.rs // Contains: 12 structs, 3 enums use std::{collections::HashMap, fs::File, io::BufReader}; use actix_multipart::form::{tempfile::TempFile, MultipartForm}; use actix_web::{HttpResponse, ResponseError}; use common_enums::{CardNetwork, PaymentMethodType}; use common_utils::{events::ApiEventMetric, pii::PhoneNumberStrategy}; use csv::Reader; use masking::Secret; use serde::{Deserialize, Serialize}; use time::{Date, PrimitiveDateTime}; #[derive(Debug, Deserialize, Serialize)] pub struct RevenueRecoveryBackfillRequest { pub bin_number: Option<Secret<String>>, pub customer_id_resp: String, pub connector_payment_id: Option<String>, pub token: Option<Secret<String>>, pub exp_date: Option<Secret<String>>, pub card_network: Option<CardNetwork>, pub payment_method_sub_type: Option<PaymentMethodType>, pub clean_bank_name: Option<String>, pub country_name: Option<String>, pub daily_retry_history: Option<String>, } #[derive(Debug, Serialize)] pub struct UnlockStatusResponse { pub unlocked: bool, } #[derive(Debug, Serialize)] pub struct RevenueRecoveryDataBackfillResponse { pub processed_records: usize, pub failed_records: usize, } #[derive(Debug, Serialize)] pub struct CsvParsingResult { pub records: Vec<RevenueRecoveryBackfillRequest>, pub failed_records: Vec<CsvParsingError>, } #[derive(Debug, Serialize)] pub struct CsvParsingError { pub row_number: usize, pub error: String, } /// Comprehensive card #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ComprehensiveCardData { pub card_type: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_network: Option<CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub daily_retry_history: Option<HashMap<Date, i32>>, } impl ApiEventMetric for RevenueRecoveryDataBackfillResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for UnlockStatusResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for CsvParsingResult { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for CsvParsingError { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for RedisDataResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for UpdateTokenStatusRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for UpdateTokenStatusResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[derive(Debug, Clone, Serialize)] pub enum BackfillError { InvalidCardType(String), DatabaseError(String), RedisError(String), CsvParsingError(String), FileProcessingError(String), } #[derive(serde::Deserialize)] pub struct BackfillQuery { pub cutoff_time: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub enum RedisKeyType { Status, // for customer:{id}:status Tokens, // for customer:{id}:tokens } #[derive(Debug, Deserialize)] pub struct GetRedisDataQuery { pub key_type: RedisKeyType, } #[derive(Debug, Serialize)] pub struct RedisDataResponse { pub exists: bool, pub ttl_seconds: i64, pub data: Option<serde_json::Value>, } #[derive(Debug, Serialize)] pub enum ScheduledAtUpdate { SetToNull, SetToDateTime(PrimitiveDateTime), } impl<'de> Deserialize<'de> for ScheduledAtUpdate { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let value = serde_json::Value::deserialize(deserializer)?; match value { serde_json::Value::String(s) => { if s.to_lowercase() == "null" { Ok(Self::SetToNull) } else { // Parse as datetime using iso8601 deserializer common_utils::custom_serde::iso8601::deserialize( &mut serde_json::Deserializer::from_str(&format!("\"{}\"", s)), ) .map(Self::SetToDateTime) .map_err(serde::de::Error::custom) } } _ => Err(serde::de::Error::custom( "Expected null variable or datetime iso8601 ", )), } } } #[derive(Debug, Deserialize, Serialize)] pub struct UpdateTokenStatusRequest { pub connector_customer_id: String, pub payment_processor_token: Secret<String, PhoneNumberStrategy>, pub scheduled_at: Option<ScheduledAtUpdate>, pub is_hard_decline: Option<bool>, pub error_code: Option<String>, } #[derive(Debug, Serialize)] pub struct UpdateTokenStatusResponse { pub updated: bool, pub message: String, } impl std::fmt::Display for BackfillError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::InvalidCardType(msg) => write!(f, "Invalid card type: {}", msg), Self::DatabaseError(msg) => write!(f, "Database error: {}", msg), Self::RedisError(msg) => write!(f, "Redis error: {}", msg), Self::CsvParsingError(msg) => write!(f, "CSV parsing error: {}", msg), Self::FileProcessingError(msg) => write!(f, "File processing error: {}", msg), } } } impl std::error::Error for BackfillError {} impl ResponseError for BackfillError { fn error_response(&self) -> HttpResponse { HttpResponse::BadRequest().json(serde_json::json!({ "error": self.to_string() })) } } #[derive(Debug, MultipartForm)] pub struct RevenueRecoveryDataBackfillForm { #[multipart(rename = "file")] pub file: TempFile, } impl RevenueRecoveryDataBackfillForm { pub fn validate_and_get_records_with_errors(&self) -> Result<CsvParsingResult, BackfillError> { // Step 1: Open the file let file = File::open(self.file.file.path()) .map_err(|error| BackfillError::FileProcessingError(error.to_string()))?; let mut csv_reader = Reader::from_reader(BufReader::new(file)); // Step 2: Parse CSV into typed records let mut records = Vec::new(); let mut failed_records = Vec::new(); for (row_index, record_result) in csv_reader .deserialize::<RevenueRecoveryBackfillRequest>() .enumerate() { match record_result { Ok(record) => { records.push(record); } Err(err) => { failed_records.push(CsvParsingError { row_number: row_index + 2, // +2 because enumerate starts at 0 and CSV has header row error: err.to_string(), }); } } } Ok(CsvParsingResult { records, failed_records, }) } }
{ "crate": "api_models", "file": "crates/api_models/src/revenue_recovery_data_backfill.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 12, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-5317033134018843257
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/surcharge_decision_configs.rs // Contains: 5 structs, 1 enums use common_utils::{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH, events, types::{MinorUnit, Percentage}, }; use euclid::frontend::{ ast::Program, dir::{DirKeyKind, EuclidDirFilter}, }; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct SurchargeDetailsOutput { pub surcharge: SurchargeOutput, pub tax_on_surcharge: Option<Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum SurchargeOutput { Fixed { amount: MinorUnit }, Rate(Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>), } #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct SurchargeDecisionConfigs { pub surcharge_details: Option<SurchargeDetailsOutput>, } impl EuclidDirFilter for SurchargeDecisionConfigs { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::PaymentMethod, DirKeyKind::MetaData, DirKeyKind::PaymentAmount, DirKeyKind::PaymentCurrency, DirKeyKind::BillingCountry, DirKeyKind::CardNetwork, DirKeyKind::PayLaterType, DirKeyKind::WalletType, DirKeyKind::BankTransferType, DirKeyKind::BankRedirectType, DirKeyKind::BankDebitType, DirKeyKind::CryptoType, DirKeyKind::RealTimePaymentType, ]; } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SurchargeDecisionManagerRecord { pub name: String, pub merchant_surcharge_configs: MerchantSurchargeConfigs, pub algorithm: Program<SurchargeDecisionConfigs>, pub created_at: i64, pub modified_at: i64, } impl events::ApiEventMetric for SurchargeDecisionManagerRecord { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct SurchargeDecisionConfigReq { pub name: Option<String>, pub merchant_surcharge_configs: MerchantSurchargeConfigs, pub algorithm: Option<Program<SurchargeDecisionConfigs>>, } impl events::ApiEventMetric for SurchargeDecisionConfigReq { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct MerchantSurchargeConfigs { pub show_surcharge_breakup_screen: Option<bool>, } pub type SurchargeDecisionManagerResponse = SurchargeDecisionManagerRecord;
{ "crate": "api_models", "file": "crates/api_models/src/surcharge_decision_configs.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 5, "num_tables": null, "score": null, "total_crates": null }
file_api_models_3501256469266605552
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/payments.rs // Contains: 20 structs, 11 enums #[cfg(feature = "v1")] use std::fmt; use std::{ collections::{HashMap, HashSet}, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::{GooglePayCardFundingSource, ProductType}; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_types::{payments as common_payments_types, primitive_wrappers}; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, new_type::MaskedBankAccount, pii::{self, Email}, types::{AmountConvertor, MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; #[cfg(feature = "v2")] fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error> where D: serde::Deserializer<'de>, T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error, { let opt_str: Option<String> = Option::deserialize(v)?; match opt_str { Some(s) if s.is_empty() => Ok(None), Some(s) => { // Estimate capacity based on comma count let capacity = s.matches(',').count() + 1; let mut result = Vec::with_capacity(capacity); for item in s.split(',') { let trimmed_item = item.trim(); if !trimmed_item.is_empty() { let parsed_item = trimmed_item.parse::<T>().map_err(|e| { <D::Error as serde::de::Error>::custom(format!( "Invalid value '{trimmed_item}': {e}" )) })?; result.push(parsed_item); } } Ok(Some(result)) } None => Ok(None), } } use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; #[cfg(feature = "v1")] use serde::{de, Deserializer}; use serde::{ser::Serializer, Deserialize, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v2")] use crate::mandates; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, enums as api_enums, mandates::RecurringDetails, }; #[cfg(feature = "v1")] use crate::{disputes, ephemeral_key::EphemeralKeyCreateResponse, refunds, ValidateFieldAndGet}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, /// The tax registration identifier of the customer. #[schema(value_type=Option<String>,max_length = 255)] pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentAttemptListRequest { #[schema(value_type = String)] pub payment_intent_id: id_type::GlobalPaymentId, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentAttemptListResponse { pub payment_attempt_list: Vec<PaymentAttemptResponse>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, enable_partial_authorization: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "cs_0195b34da95d75239c6a4bf514458896")] pub client_secret: Option<Secret<String>>, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, /// 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, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = PaymentType)] pub payment_type: api_enums::PaymentType, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardBalanceCheckResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The balance of the gift card pub balance: MinorUnit, /// The currency of the Gift Card #[schema(value_type = Currency)] pub currency: common_enums::Currency, /// Whether the gift card balance is enough for the transaction (Used for split payments case) pub needs_additional_pm_data: bool, /// Transaction amount left after subtracting gift card balance (Used for split payments) pub remaining_amount: MinorUnit, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, router_derive::ValidateSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The primary amount for the payment, provided in the lowest denomination of the specified currency (e.g., 6540 for $65.40 USD). This field is mandatory for creating a payment. #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order, in the lowest denomination of the currency. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three-letter ISO 4217 currency code (e.g., "USD", "EUR") for the payment amount. This field is mandatory for creating a payment. #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The amount to be captured from the user's payment method, in the lowest denomination. If not provided, and `capture_method` is `automatic`, the full payment `amount` will be captured. If `capture_method` is `manual`, this can be specified in the `/capture` call. Must be less than or equal to the authorized amount. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Optional. A merchant-provided unique identifier for the payment, contains 30 characters long (e.g., "pay_mbabizu24mvu3mela5njyhpit4"). If provided, it ensures idempotency for the payment creation request. If omitted, Hyperswitch generates a unique ID for the payment. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// If set to `true`, Hyperswitch attempts to confirm and authorize the payment immediately after creation, provided sufficient payment method details are included. If `false` or omitted (default is `false`), the payment is created with a status such as `requires_payment_method` or `requires_confirmation`, and a separate `POST /payments/{payment_id}/confirm` call is necessary to proceed with authorization. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// An arbitrary string attached to the payment. Often useful for displaying to users or for your own internal record-keeping. #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to redirect the customer to after they complete the payment process or authentication. This is crucial for flows that involve off-site redirection (e.g., 3DS, some bank redirects, wallet payments). #[schema(value_type = Option<String>, example = "https://hyperswitch.io", max_length = 2048)] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 64, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// 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>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Your unique identifier for this payment or order. This ID helps you reconcile payments on your system. If provided, it is passed to the connector if supported. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, /// If enabled, provides whole connector response pub all_keys_required: Option<bool>, /// Indicates whether the `payment_id` was provided by the merchant /// This value is inferred internally based on the request #[serde(skip_deserializing)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub is_payment_id_from_merchant: bool, /// Indicates how the payment was initiated (e.g., ecommerce, mail, or telephone). #[schema(value_type = Option<PaymentChannel>)] pub payment_channel: Option<common_enums::PaymentChannel>, /// Your tax status for this order or transaction. #[schema(value_type = Option<TaxStatus>)] pub tax_status: Option<api_enums::TaxStatus>, /// Total amount of the discount you have applied to the order or transaction. #[schema(value_type = Option<i64>, example = 6540)] pub discount_amount: Option<MinorUnit>, /// Tax amount applied to shipping charges. pub shipping_amount_tax: Option<MinorUnit>, /// Duty or customs fee amount for international transactions. pub duty_amount: Option<MinorUnit>, /// Date the payer placed the order. #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub order_date: Option<PrimitiveDateTime>, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, /// Boolean indicating whether to enable overcapture for this payment #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<bool>, example = true)] pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>, /// Boolean flag indicating whether this payment method is stored and has been previously used for payments #[schema(value_type = Option<bool>, example = true)] pub is_stored_credential: Option<bool>, /// The category of the MIT transaction #[schema(value_type = Option<MitCategory>, example = "recurring")] pub mit_category: Option<api_enums::MitCategory>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encrypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, .. }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } pub fn validate_stored_credential( &self, ) -> common_utils::errors::CustomResult<(), ValidationError> { if self.is_stored_credential == Some(false) && (self.recurring_details.is_some() || self.payment_token.is_some() || self.mandate_id.is_some()) { Err(ValidationError::InvalidValue { message: "is_stored_credential should be true when reusing stored payment method data" .to_string(), } .into()) } else { Ok(()) } } pub fn validate_mit_request(&self) -> common_utils::errors::CustomResult<(), ValidationError> { if self.mit_category.is_some() && (!matches!(self.off_session, Some(true)) || self.recurring_details.is_none()) { return Err(ValidationError::InvalidValue { message: "`mit_category` requires both: (1) `off_session = true`, and (2) `recurring_details`.".to_string(), } .into()); } Ok(()) } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, tax_registration_id: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, tax_registration_id: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, /// Accept-language of the browser pub accept_language: Option<String>, /// Identifier of the source that initiated the request. pub referer: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// A unique identifier for this specific payment attempt. pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The name of the payment connector (e.g., 'stripe', 'adyen') used for this attempt. pub connector: Option<String>, /// A human-readable message from the connector explaining the error, if one occurred during this payment attempt. pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If this payment attempt is associated with a mandate (e.g., for a recurring or subsequent payment), this field will contain the ID of that mandate. pub mandate_id: Option<String>, /// The error code returned by the connector if this payment attempt failed. This code is specific to the connector. pub error_code: Option<String>, /// If a tokenized (saved) payment method was used for this attempt, this field contains the payment token representing that payment method. pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// The connector's own reference or transaction ID for this specific payment attempt. Useful for reconciliation with the connector. #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The payment method information for the payment attempt pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentAttemptRecordResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The amount of the payment attempt #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Error details for the payment attempt, if any. /// This includes fields like error code, network advice code, and network decline code. pub error_details: Option<RecordAttemptErrorDetails>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub payment_intent_feature_metadata: Option<FeatureMetadata>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub payment_attempt_feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// attempt created at timestamp pub created_at: PrimitiveDateTime, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct RecoveryPaymentsResponse { /// Unique identifier for the payment. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub intent_status: api_enums::IntentStatus, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, // stripe specific field used to identify duplicate attempts. #[schema(value_type = Option<String>, example = "ch_123abc456def789ghi012klmn")] pub charge_id: Option<String>, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// A unique identifier for this specific capture operation. pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The name of the payment connector that processed this capture. pub connector: String, /// The ID of the payment attempt that was successfully authorized and subsequently captured by this operation. pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// A human-readable message from the connector explaining why this capture operation failed, if applicable. pub error_message: Option<String>, /// The error code returned by the connector if this capture operation failed. This code is connector-specific. pub error_code: Option<String>, /// A more detailed reason from the connector explaining the capture failure, if available. pub error_reason: Option<String>, /// The connector's own reference or transaction ID for this specific capture operation. Useful for reconciliation. pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq, ToSchema)] pub struct NetworkDetails { pub network_advice_code: Option<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: 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 CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: 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>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: 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 CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: 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>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For Flexiti Redirect as PayLater long term finance Option FlexitiRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, BreadpayRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::FlexitiRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} | Self::BreadpayRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, SepaGuarenteedBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaGuarenteedBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SplitPaymentMethodDataRequest { pub payment_method_data: PaymentMethodData, #[schema(value_type = PaymentMethod)] pub payment_method_type: api_enums::PaymentMethod, #[schema(value_type = PaymentMethodType)] pub payment_method_subtype: api_enums::PaymentMethodType, } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct RecordAttemptPaymentMethodDataRequest { /// Additional details for the payment method (e.g., card expiry date, card network). #[serde(flatten)] pub payment_method_data: AdditionalPaymentData, /// billing details for the payment method. pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct ProxyPaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<ProxyPaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum ProxyPaymentMethodData { #[schema(title = "ProxyCardData")] VaultDataCard(Box<ProxyCardData>), VaultToken(VaultToken), } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ProxyCardData { /// The token which refers to the card number #[schema(value_type = String, example = "token_card_number")] pub card_number: Secret<String>, /// 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 CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: 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 first six digit of the card number #[schema(value_type = String, example = "424242")] pub bin_number: Option<String>, /// The last four digit of the card number #[schema(value_type = String, example = "4242")] pub last_four: Option<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct VaultToken { /// The tokenized CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BluecodeRedirect {} => api_enums::PaymentMethodType::Bluecode, Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPay(_) | Self::AmazonPayRedirect(_) => { api_enums::PaymentMethodType::AmazonPay } Self::Skrill(_) => api_enums::PaymentMethodType::Skrill, Self::Paysera(_) => api_enums::PaymentMethodType::Paysera, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, Self::RevolutPay(_) => api_enums::PaymentMethodType::RevolutPay, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::FlexitiRedirect {} => api_enums::PaymentMethodType::Flexiti, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, Self::BreadpayRedirect {} => api_enums::PaymentMethodType::Breadpay, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, Self::SepaGuarenteedBankDebit { .. } => { api_enums::PaymentMethodType::SepaGuarenteedDebit } } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, Self::InstantBankTransferFinland {} => { api_enums::PaymentMethodType::InstantBankTransferFinland } Self::InstantBankTransferPoland {} => { api_enums::PaymentMethodType::InstantBankTransferPoland } Self::IndonesianBankTransfer { .. } => { api_enums::PaymentMethodType::IndonesianBankTransfer } } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, Self::UpiQr(_) => api_enums::PaymentMethodType::UpiQr, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, Self::BhnCardNetwork(_) => api_enums::PaymentMethodType::BhnCardNetwork, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, BhnCardNetwork(BHNGiftCardDetails), } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct BHNGiftCardDetails { /// The gift card or account number #[schema(value_type = String)] pub account_number: Secret<String>, /// The security PIN for gift cards requiring it #[schema(value_type = String)] pub pin: Option<Secret<String>>, /// The CVV2 code for Open Loop/VPLN products #[schema(value_type = String)] pub cvv2: Option<Secret<String>>, /// The expiration date in MMYYYY format for Open Loop/VPLN products #[schema(value_type = String)] pub expiration_date: Option<String>, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, /// Indicates if the card issuer is regulated under government-imposed interchange fee caps. /// In the United States, this includes debit cards that fall under the Durbin Amendment, /// which imposes capped interchange fees. pub is_regulated: Option<bool>, /// The global signature network under which the card is issued. /// This represents the primary global card brand, even if the transaction uses a local network pub signature_network: Option<api_enums::CardNetwork>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } impl AdditionalPaymentData { pub fn get_additional_card_info(&self) -> Option<AdditionalCardInfo> { match self { Self::Card(additional_card_info) => Some(*additional_card_info.clone()), _ => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), UpiQr(UpiQrData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiQrData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, /// Source bank account number #[schema(value_type = Option<String>, example = "8b******-****-****-****-*******08bc5")] 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)] 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")] expiry_date: Option<PrimitiveDateTime>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, 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)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} | Self::InstantBankTransferFinland {} | Self::IndonesianBankTransfer { .. } | Self::InstantBankTransferPoland {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay HK redirect #[schema(title = "AliPayHkRedirect")] AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Ali Pay QrCode #[schema(title = "AliPayQr")] AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect #[schema(title = "AliPayRedirect")] AliPayRedirect(AliPayRedirection), /// The wallet data for Amazon Pay #[schema(title = "AmazonPay")] AmazonPay(AmazonPayWalletData), /// The wallet data for Amazon Pay redirect #[schema(title = "AmazonPayRedirect")] AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Apple pay #[schema(title = "ApplePay")] ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow #[schema(title = "ApplePayRedirect")] ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow #[schema(title = "ApplePayThirdPartySdk")] ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// The wallet data for Bluecode QR Code Redirect #[schema(title = "BluecodeRedirect")] BluecodeRedirect {}, /// The wallet data for Cashapp Qr #[schema(title = "CashappQr")] CashappQr(Box<CashappQr>), /// Wallet data for DANA redirect flow #[schema(title = "DanaRedirect")] DanaRedirect {}, /// The wallet data for Gcash redirect #[schema(title = "GcashRedirect")] GcashRedirect(GcashRedirection), /// The wallet data for GoPay redirect #[schema(title = "GoPayRedirect")] GoPayRedirect(GoPayRedirection), /// The wallet data for Google pay #[schema(title = "GooglePay")] GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow #[schema(title = "GooglePayRedirect")] GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow #[schema(title = "GooglePayThirdPartySdk")] GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), /// The wallet data for KakaoPay redirect #[schema(title = "KakaoPayRedirect")] KakaoPayRedirect(KakaoPayRedirection), /// Wallet data for MbWay redirect flow #[schema(title = "MbWayRedirect")] MbWayRedirect(Box<MbWayRedirection>), // The wallet data for Mifinity Ewallet #[schema(title = "Mifinity")] Mifinity(MifinityData), /// The wallet data for MobilePay redirect #[schema(title = "MobilePayRedirect")] MobilePayRedirect(Box<MobilePayRedirection>), /// The wallet data for Momo redirect #[schema(title = "MomoRedirect")] MomoRedirect(MomoRedirection), /// This is for paypal redirection #[schema(title = "PaypalRedirect")] PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal #[schema(title = "PaypalSdk")] PaypalSdk(PayPalWalletData), /// The wallet data for Paysera #[schema(title = "Paysera")] Paysera(PayseraData), /// The wallet data for Paze #[schema(title = "Paze")] Paze(PazeWalletData), // The wallet data for RevolutPay #[schema(title = "RevolutPay")] RevolutPay(RevolutPayData), /// The wallet data for Samsung Pay #[schema(title = "SamsungPay")] SamsungPay(Box<SamsungPayWalletData>), /// The wallet data for Skrill #[schema(title = "Skrill")] Skrill(SkrillData), // The wallet data for Swish #[schema(title = "SwishQr")] SwishQr(SwishQrData), /// The wallet data for Touch n Go Redirection #[schema(title = "TouchNGoRedirect")] TouchNGoRedirect(Box<TouchNGoRedirection>), /// Wallet data for Twint Redirection #[schema(title = "TwintRedirect")] TwintRedirect {}, /// Wallet data for Vipps Redirection #[schema(title = "VippsRedirect")] VippsRedirect {}, /// The wallet data for WeChat Pay Display QrCode #[schema(title = "WeChatPayQr")] WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for WeChat Pay Redirection #[schema(title = "WeChatPayRedirect")] WeChatPayRedirect(Box<WeChatPayRedirection>), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPay(_) | Self::AmazonPayRedirect(_) | Self::Skrill(_) | Self::Paysera(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) | Self::RevolutPay(_) | Self::BluecodeRedirect {} => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay #[schema(value_type = GpayTokenizationData)] pub tokenization_data: common_types::payments::GpayTokenizationData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPaySessionTokenData { #[serde(rename = "amazon_pay")] pub data: AmazonPayMerchantCredentials, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPayMerchantCredentials { /// Amazon Pay merchant account identifier pub merchant_id: String, /// Amazon Pay store ID pub store_id: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SkrillData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayseraData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData { #[schema(value_type = Option<String>)] pub token: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData { #[schema(value_type = Option<String>)] pub token: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BluecodeQrRedirect {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, /// Card funding source for the selected payment method pub card_funding_source: Option<GooglePayCardFundingSource>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct RevolutPayData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayWalletData { /// Checkout Session identifier pub checkout_session_id: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay #[schema(value_type = ApplePayPaymentData)] pub payment_data: common_types::payments::ApplePayPaymentData, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number (CPF or CNPJ) #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, /// The shopper's bank account number associated with the boleto #[schema(value_type = Option<String>)] pub bank_number: Option<Secret<String>>, /// The type of identification document used (e.g., CPF or CNPJ) #[schema(value_type = Option<DocumentKind>, example = "Cpf", default = "Cnpj")] pub document_type: Option<common_enums::DocumentKind>, /// The fine percentage charged if payment is overdue #[schema(value_type = Option<String>)] pub fine_percentage: Option<String>, /// The number of days after the due date when the fine is applied #[schema(value_type = Option<String>)] pub fine_quantity_days: Option<String>, /// The interest percentage charged on late payments #[schema(value_type = Option<String>)] pub interest_percentage: Option<String>, /// The number of days after which the boleto is written off (canceled) #[schema(value_type = Option<String>)] pub write_off_quantity_days: Option<String>, /// Custom messages or instructions to display on the boleto #[schema(value_type = Option<Vec<String>>)] pub messages: Option<Vec<String>>, // #[serde(with = "common_utils::custom_serde::date_yyyy_mm_dd::option")] #[schema(value_type = Option<String>, format = "date", example = "2025-08-22")] // The date upon which the boleto is due and is of format: "YYYY-MM-DD" pub due_date: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct CustomRecoveryPaymentMethodData { /// Primary payment method token at payment processor end. #[schema(value_type = String, example = "token_1234")] pub primary_processor_payment_method_token: Secret<String>, /// AdditionalCardInfo for the primary token. pub additional_payment_method_info: AdditionalCardInfo, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] // #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] // #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The city, district, suburb, town, or village of the address. #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO 3166-1 alpha-2 country code (e.g., US, GB). #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the street address or P.O. Box. #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the street address or P.O. Box (e.g., apartment, suite, unit, or building). #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the street address, if applicable. #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, /// The zip/postal code of the origin #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub origin_zip: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), origin_zip: self.origin_zip.or(other.origin_zip.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment being captured. This is taken from the path parameter. #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant. This is usually inferred from the API key. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The amount to capture, in the lowest denomination of the currency. If omitted, the entire `amount_capturable` of the payment will be captured. Must be less than or equal to the current `amount_capturable`. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount. (Currently not fully supported or behavior may vary by connector). pub refund_uncaptured_amount: Option<bool>, /// A dynamic suffix that appears on your customer's credit card statement. This is concatenated with the (shortened) descriptor prefix set on your account to form the complete statement descriptor. The combined length should not exceed connector-specific limits (typically 22 characters). pub statement_descriptor_suffix: Option<String>, /// An optional prefix for the statement descriptor that appears on your customer's credit card statement. This can override the default prefix set on your merchant account. The combined length of prefix and suffix should not exceed connector-specific limits (typically 22 characters). pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. (Deprecated) #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[cfg(feature = "v2")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The reason for the payment cancel pub cancellation_reason: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCancelResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "cancelled")] pub status: common_enums::IntentStatus, /// Cancellation reason for the payment cancellation #[schema(example = "Requested by merchant")] pub cancellation_reason: Option<String>, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, /// The unique identifier for the customer associated with the payment pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<api_enums::Connector>, #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// Error details for the payment pub error: Option<ErrorDetails>, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, RedirectInsidePopup, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, #[cfg(feature = "v1")] RedirectInsidePopup { popup_url: String, redirect_response_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the SDK UPI intent URI for payment processing SdkUpiIntentInformation { #[schema(value_type = String)] sdk_uri: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, poll_config: Option<PollConfig>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum ThreeDsMethodData { AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, /// Three DS Method Key three_ds_method_key: Option<ThreeDsMethodKey>, /// Indicates whethere to wait for Post message after 3DS method data submission consume_post_message_for_three_ds_method_completion: bool, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum ThreeDsMethodKey { #[serde(rename = "threeDSMethodData")] ThreeDsMethodData, #[serde(rename = "JWT")] JWT, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SdkUpiIntentInformation { pub sdk_uri: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher entry date pub entry_date: Option<String>, /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, /// Human-readable numeric version of the barcode. pub digitable_line: Option<Secret<String>>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, pub poll_config: Option<PollConfig>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PollConfig { /// Interval of the poll pub delay_in_secs: u16, /// Frequency of the poll pub frequency: u16, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The amount (in minor units) that can still be captured for this payment. This is relevant when `capture_method` is `manual`. Once fully captured, or if `capture_method` is `automatic` and payment succeeded, this will be 0. #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The total amount (in minor units) that has been captured for this payment. For `fauxpay` sandbox connector, this might reflect the authorized amount if `status` is `succeeded` even if `capture_method` was `manual`. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The name of the payment connector (e.g., 'stripe', 'adyen') that processed or is processing this payment. #[schema(example = "stripe")] pub connector: Option<String>, /// A secret token unique to this payment intent. It is primarily used by client-side applications (e.g., Hyperswitch SDKs) to authenticate actions like confirming the payment or handling next actions. This secret should be handled carefully and not exposed publicly beyond its intended client-side use. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Timestamp indicating when this payment intent was created, in ISO 8601 format. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Three-letter ISO currency code (e.g., USD, EUR) for the payment amount. #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// An arbitrary string providing a description for the payment, often useful for display or internal record-keeping. #[schema(example = "It's my first payment request")] pub description: Option<String>, /// An array of refund objects associated with this payment. Empty or null if no refunds have been processed. #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// If the payment requires further action from the customer (e.g., 3DS authentication, redirect to a bank page), this object will contain the necessary information for the client to proceed. Null if no further action is needed from the customer at this stage. pub next_action: Option<NextActionData>, /// If the payment intent was cancelled, this field provides a textual reason for the cancellation (e.g., "requested_by_customer", "abandoned"). pub cancellation_reason: Option<String>, /// The connector-specific error code from the last failed payment attempt associated with this payment intent. #[schema(example = "E0001")] pub error_code: Option<String>, /// A human-readable error message from the last failed payment attempt associated with this payment intent. #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Describes the type of payment flow experienced by the customer (e.g., 'redirect_to_url', 'invoke_sdk', 'display_qr_code'). #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// The specific payment method subtype used for this payment (e.g., 'credit_card', 'klarna', 'gpay'). This provides more granularity than the 'payment_method' field. #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// A label identifying the specific merchant connector account (MCA) used for this payment. This often combines the connector name, business country, and a custom label (e.g., "stripe_US_primary"). #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The two-letter ISO country code (e.g., US, GB) of the business unit or profile under which this payment was processed. #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The label identifying the specific business unit or profile under which this payment was processed by the merchant. pub business_label: Option<String>, /// An optional sub-label for further categorization of the business unit or profile used for this payment. pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// 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>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Indicates how the payment was initiated (e.g., ecommerce, mail, or telephone). #[schema(value_type = Option<PaymentChannel>)] pub payment_channel: Option<common_enums::PaymentChannel>, /// A unique identifier for the payment method used in this payment. If the payment method was saved or tokenized, this ID can be used to reference it for future transactions or recurring payments. pub payment_method_id: Option<String>, /// The network transaction ID is a unique identifier for the transaction as recognized by the payment network (e.g., Visa, Mastercard), this ID can be used to reference it for future transactions or recurring payments. pub network_transaction_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, /// Contains whole connector response #[schema(value_type = Option<String>)] pub whole_connector_response: Option<Secret<String>>, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, /// Bool indicating if overcapture must be requested for this payment #[schema(value_type = Option<bool>)] pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>, /// Boolean indicating whether overcapture is effectively enabled for this payment #[schema(value_type = Option<bool>)] pub is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>, /// Contains card network response details (e.g., Visa/Mastercard advice codes). #[schema(value_type = Option<NetworkDetails>)] pub network_details: Option<NetworkDetails>, /// Boolean flag indicating whether this payment method is stored and has been previously used for payments #[schema(value_type = Option<bool>, example = true)] pub is_stored_credential: Option<bool>, /// The category of the MIT transaction #[schema(value_type = Option<MitCategory>, example = "recurring")] pub mit_category: Option<api_enums::MitCategory>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment instrument data to be used for the payment in case of split payments pub split_payment_method_data: Option<Vec<SplitPaymentMethodDataRequest>>, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, /// If true, returns stringified connector raw response body pub return_raw_connector_response: Option<bool>, /// The webhook endpoint URL to receive payment status notifications #[schema(value_type = Option<String>, example = "https://merchant.example.com/webhooks/payment")] pub webhook_url: Option<common_utils::types::Url>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Gift Card balance check #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsGiftCardBalanceCheckRequest { pub gift_card_data: GiftCardData, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: mandates::ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct ExternalVaultProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: ProxyPaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, /// If true, returns stringified connector raw response body pub return_raw_connector_response: Option<bool>, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, /// Stringified connector raw response body. Only returned if `return_raw_connector_response` is true pub return_raw_connector_response: Option<bool>, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, /// The webhook endpoint URL to receive payment status notifications #[schema(value_type = Option<String>, example = "https://merchant.example.com/webhooks/payment")] pub webhook_url: Option<common_utils::types::Url>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present, description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption, statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled, payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication, force_3ds_challenge: request.force_3ds_challenge, merchant_connector_details: request.merchant_connector_details.clone(), enable_partial_authorization: request.enable_partial_authorization, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), payment_token: None, merchant_connector_details: request.merchant_connector_details.clone(), return_raw_connector_response: request.return_raw_connector_response, split_payment_method_data: None, webhook_url: request.webhook_url.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request body for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, /// If true, returns stringified connector raw response body pub return_raw_connector_response: Option<bool>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] /// Request for Payment Status pub struct PaymentsStatusRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, /// If true, returns stringified connector raw response body pub return_raw_connector_response: Option<bool>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The detailed error reason that was returned by the connector. pub reason: Option<String>, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// Time when the payment was last modified #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// Stringified connector raw response body. Only returned if `return_raw_connector_response` is true #[schema(value_type = Option<String>)] pub raw_connector_response: Option<Secret<String>>, /// Additional data that might be required by hyperswitch based on the additional features. pub feature_metadata: Option<FeatureMetadata>, /// 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>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] impl PaymentAttemptListResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( &self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.payment_attempt_list.iter().find_map(|attempt| { attempt .connector_payment_id .as_ref() .filter(|txn_id| *txn_id == connector_transaction_id) .map(|_| attempt.clone()) }) } pub fn find_attempt_in_attempts_list_using_charge_id( &self, charge_id: String, ) -> Option<PaymentAttemptResponse> { self.payment_attempt_list.iter().find_map(|attempt| { attempt.feature_metadata.as_ref().and_then(|metadata| { metadata.revenue_recovery.as_ref().and_then(|recovery| { recovery .charge_id .as_ref() .filter(|id| **id == charge_id) .map(|_| attempt.clone()) }) }) }) } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Vec<Connector>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub connector: Option<Vec<api_enums::Connector>>, /// The currency to filter payments list #[param(value_type = Option<Vec<Currency>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub currency: Option<Vec<enums::Currency>>, /// The payment status to filter payments list #[param(value_type = Option<Vec<IntentStatus>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub status: Option<Vec<enums::IntentStatus>>, /// The payment method type to filter payments list #[param(value_type = Option<Vec<PaymentMethod>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub payment_method_type: Option<Vec<enums::PaymentMethod>>, /// The payment method subtype to filter payments list #[param(value_type = Option<Vec<PaymentMethodType>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub payment_method_subtype: Option<Vec<enums::PaymentMethodType>>, /// The authentication type to filter payments list #[param(value_type = Option<Vec<AuthenticationType>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The merchant connector id to filter payments list #[param(value_type = Option<Vec<String>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<Vec<CardNetwork>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// Optional query parameters that might be specific to a connector or flow, passed through during the retrieve operation. Use with caution and refer to specific connector documentation if applicable. pub param: Option<String>, /// Optionally specifies the connector to be used for a 'force_sync' retrieve operation. If provided, Hyperswitch will attempt to sync the payment status from this specific connector. pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, /// If enabled, provides whole connector response pub all_keys_required: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, /// Description for the item pub description: Option<String>, /// Stock Keeping Unit (SKU) or the item identifier for this item. pub sku: Option<String>, /// Universal Product Code for the item. pub upc: Option<String>, /// Code describing a commodity or a group of commodities pertaining to goods classification. pub commodity_code: Option<String>, /// Unit of measure used for the item quantity. pub unit_of_measure: Option<String>, /// Total amount for the item. #[schema(value_type = Option<i64>)] pub total_amount: Option<MinorUnit>, // total_amount, /// Discount amount applied to this item. #[schema(value_type = Option<i64>)] pub unit_discount_amount: Option<MinorUnit>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsUpdateMetadataRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Object, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: pii::SecretSerdeValue, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsUpdateMetadataResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, pub adyen: Option<AdyenConnectorMetadata>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AdyenConnectorMetadata { pub testing: AdyenTestingData, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AdyenTestingData { /// Holder name to be sent to Adyen for a card payment(CIT) or a generic payment(MIT). This value overrides the values for card.card_holder_name and applies during both CIT and MIT payment transactions. #[schema(value_type = String)] pub holder_name: Option<Secret<String>>, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// The session response structure for Amazon Pay AmazonPay(Box<AmazonPaySessionTokenResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VaultSessionDetails { Vgs(VgsSessionDetails), HyperswitchVault(HyperswitchVaultSessionDetails), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct VgsSessionDetails { /// The identifier of the external vault #[schema(value_type = String)] pub external_vault_id: Secret<String>, /// The environment for the external vault initiation pub sdk_env: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct HyperswitchVaultSessionDetails { /// Session ID for Hyperswitch Vault #[schema(value_type = String)] pub payment_method_session_id: Secret<String>, /// Client secret for Hyperswitch Vault #[schema(value_type = String)] pub client_secret: Secret<String>, /// Publishable key for Hyperswitch Vault #[schema(value_type = String)] pub publishable_key: Secret<String>, /// Profile ID for Hyperswitch Vault #[schema(value_type = String)] pub profile_id: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaypalFlow { Checkout, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaypalTransactionInfo { /// Paypal flow type #[schema(value_type = PaypalFlow, example = "checkout")] pub flow: PaypalFlow, /// Currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Authorization token used by client to initiate sdk pub client_token: Option<String>, /// The transaction info Paypal requires pub transaction_info: Option<PaypalTransactionInfo>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, /// The next action is to await for a merchant callback AwaitMerchantCallback, /// The next action is to deny the payment with an error message Deny { message: String }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse(NullObject), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPaySessionTokenResponse { /// Amazon Pay merchant account identifier pub merchant_id: String, /// Ledger currency provided during registration for the given merchant identifier #[schema(example = "USD", value_type = Currency)] pub ledger_currency: common_enums::Currency, /// Amazon Pay store ID pub store_id: String, /// Payment flow for charging the buyer pub payment_intent: AmazonPayPaymentIntent, /// The total shipping costs #[schema(value_type = String)] pub total_shipping_amount: StringMajorUnit, /// The total tax amount for the order #[schema(value_type = String)] pub total_tax_amount: StringMajorUnit, /// The total amount for items in the cart #[schema(value_type = String)] pub total_base_amount: StringMajorUnit, /// The delivery options available for the provided address pub delivery_options: Vec<AmazonPayDeliveryOptions>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum AmazonPayPaymentIntent { /// Create a Charge Permission to authorize and capture funds at a later time Confirm, /// Authorize funds immediately and capture at a later time Authorize, /// Authorize and capture funds immediately AuthorizeWithCapture, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPayDeliveryOptions { /// Delivery Option identifier pub id: String, /// Total delivery cost pub price: AmazonPayDeliveryPrice, /// Shipping method details pub shipping_method: AmazonPayShippingMethod, /// Specifies if this delivery option is the default pub is_default: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPayDeliveryPrice { /// Transaction amount in MinorUnit pub amount: MinorUnit, #[serde(skip_deserializing)] /// Transaction amount in StringMajorUnit #[schema(value_type = String)] pub display_amount: StringMajorUnit, /// Transaction currency code in ISO 4217 format #[schema(example = "USD", value_type = Currency)] pub currency_code: common_enums::Currency, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPayShippingMethod { /// Name of the shipping method pub shipping_method_name: String, /// Code of the shipping method pub shipping_method_code: String, } impl AmazonPayDeliveryOptions { pub fn parse_delivery_options_request( delivery_options_request: &[serde_json::Value], ) -> Result<Vec<Self>, common_utils::errors::ParsingError> { delivery_options_request .iter() .map(|option| { serde_json::from_value(option.clone()).map_err(|_| { common_utils::errors::ParsingError::StructParseFailure( "AmazonPayDeliveryOptions", ) }) }) .collect() } pub fn get_default_delivery_amount( delivery_options: Vec<Self>, ) -> Result<MinorUnit, error_stack::Report<ValidationError>> { let mut default_options = delivery_options .into_iter() .filter(|delivery_option| delivery_option.is_default); match (default_options.next(), default_options.next()) { (Some(default_option), None) => Ok(default_option.price.amount), _ => Err(ValidationError::InvalidValue { message: "Amazon Pay Delivery Option".to_string(), }) .attach_printable("Expected exactly one default Amazon Pay Delivery Option"), } } pub fn validate_currency( currency_code: common_enums::Currency, amazonpay_supported_currencies: HashSet<common_enums::Currency>, ) -> Result<(), ValidationError> { if !amazonpay_supported_currencies.contains(&currency_code) { return Err(ValidationError::InvalidValue { message: format!("{currency_code:?} is not a supported currency."), }); } Ok(()) } pub fn insert_display_amount( delivery_options: &mut Vec<Self>, currency_code: common_enums::Currency, ) -> Result<(), error_stack::Report<common_utils::errors::ParsingError>> { let required_amount_type = common_utils::types::StringMajorUnitForCore; for option in delivery_options { let display_amount = required_amount_type .convert(option.price.amount, currency_code) .change_context(common_utils::errors::ParsingError::I64ToStringConversionFailure)?; option.price.display_amount = display_amount; } Ok(()) } } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, /// External vault session details pub vault_details: Option<VaultSessionDetails>, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, /// If enabled, provides whole connector response pub all_keys_required: Option<bool>, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } /// Request to cancel a payment when the payment is already captured #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelPostCaptureRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] /// Request constructed internally for extending authorization pub struct PaymentsExtendAuthorizationRequest { /// The identifier for the payment pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: 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, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] /// Indicates if 3DS method data was successfully completed or not pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct ListMethodsForPaymentsRequest { /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, /// The two-letter ISO currency code #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))] pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>, /// Filter by amount #[schema(example = 60)] pub amount: Option<MinorUnit>, /// The three-letter ISO currency code #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))] pub accepted_currencies: Option<Vec<api_enums::Currency>>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for card networks #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// Indicates the limit of last used payment methods #[schema(example = 1)] pub limit: Option<i64>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethodResponseItem>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethodResponseItem>>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The payment experience for the payment method #[schema(value_type = Option<Vec<PaymentExperience>>)] pub payment_experience: Option<Vec<common_enums::PaymentExperience>>, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = RequiredFieldInfo)] pub required_fields: Vec<payment_methods::RequiredFieldInfo>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Challenge request key which should be set as form field name for creq pub challenge_request_key: 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_dsserver_trans_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>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub revenue_recovery: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.revenue_recovery .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, revenue_recovery: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } #[allow(dead_code)] pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, pub payment_form_header_text: Option<String>, pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, pub is_setup_mandate_flow: Option<bool>, pub capture_method: Option<common_enums::CaptureMethod>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, pub color_icon_card_cvc_error: Option<String>, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, pub payment_form_header_text: Option<String>, pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, pub color_icon_card_cvc_error: Option<String>, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub capture_method: Option<common_enums::CaptureMethod>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, #[schema(value_type = Vec<CardNetwork>, example = "[Visa, Mastercard]")] pub card_brands: HashSet<api_enums::CardNetwork>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsEligibilityRequest { /// The identifier for the payment /// Added in the payload for ApiEventMetrics, populated from the path param #[serde(skip)] pub payment_id: id_type::PaymentId, /// Token used for client side verification #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// The payment method to be used for the payment #[schema(value_type = PaymentMethod, example = "wallet")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method type to be used for the payment #[schema(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The browser information for the payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<BrowserInformation>, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsEligibilityResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Next action to be performed by the SDK pub sdk_next_action: SdkNextAction, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: Option<PaymentConnectorTransmission>, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, #[schema(value_type = BillingConnectorPaymentMethodDetails)] /// Extra Payment Method Details that are needed to be stored pub billing_connector_payment_method_details: Option<BillingConnectorPaymentMethodDetails>, /// Invoice Next billing time #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub invoice_next_billing_time: Option<PrimitiveDateTime>, /// Invoice Next billing time #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub invoice_billing_started_at_time: Option<PrimitiveDateTime>, /// First Payment Attempt Payment Gateway Error Code #[schema(value_type = Option<String>, example = "card_declined")] pub first_payment_attempt_pg_error_code: Option<String>, /// First Payment Attempt Network Error Code #[schema(value_type = Option<String>, example = "05")] pub first_payment_attempt_network_decline_code: Option<String>, /// First Payment Attempt Network Advice Code #[schema(value_type = Option<String>, example = "02")] pub first_payment_attempt_network_advice_code: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum BillingConnectorPaymentMethodDetails { Card(BillingConnectorAdditionalCardInfo), } #[cfg(feature = "v2")] #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)] pub struct BillingConnectorAdditionalCardInfo { #[schema(value_type = CardNetwork, example = "Visa")] /// Card Network pub card_network: Option<common_enums::enums::CardNetwork>, #[schema(value_type = Option<String>, example = "JP MORGAN CHASE")] /// Card Issuer pub card_issuer: Option<String>, } #[cfg(feature = "v2")] impl BillingConnectorPaymentMethodDetails { pub fn get_billing_connector_card_info(&self) -> Option<&BillingConnectorAdditionalCardInfo> { match self { Self::Card(card_details) => Some(card_details), } } } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = Some(payment_connector_transmission); } pub fn get_payment_token_for_api_request(&self) -> mandates::ProcessorPaymentToken { mandates::ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } pub fn get_connector_customer_id(&self) -> String { self.billing_connector_payment_details .connector_customer_id .to_owned() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The additional payment data to be used for the payment attempt. pub payment_method_data: Option<RecordAttemptPaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, /// Number of attempts made for invoice #[schema(value_type = Option<u16>, example = 1)] pub retry_count: Option<u16>, /// Next Billing time of the Invoice #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub invoice_next_billing_time: Option<PrimitiveDateTime>, /// Next Billing time of the Invoice #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub invoice_billing_started_at_time: Option<PrimitiveDateTime>, /// source where the payment was triggered by #[schema(value_type = TriggeredBy, example = "internal" )] pub triggered_by: common_enums::TriggeredBy, #[schema(value_type = CardNetwork, example = "Visa" )] /// card_network pub card_network: Option<common_enums::CardNetwork>, #[schema(example = "Chase")] /// Card Issuer pub card_issuer: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct RecoveryPaymentsCreate { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: id_type::PaymentReferenceId, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_merchant_connector_id: id_type::MerchantConnectorAccountId, /// Payments connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: id_type::MerchantConnectorAccountId, #[schema(value_type = AttemptStatus, example = "charged")] pub attempt_status: enums::AttemptStatus, /// The billing details of the payment attempt. pub billing: Option<Address>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_sub_type: api_enums::PaymentMethodType, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: Secret<String>, /// Invoice billing started at billing connector end. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub billing_started_at: Option<PrimitiveDateTime>, /// A unique identifier for a payment provided by the payment connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<Secret<String>>, /// payment method token units at payment processor end. pub payment_method_data: CustomRecoveryPaymentMethodData, /// Type of action that needs to be taken after consuming the recovery payload. For example: scheduling a failed payment or stopping the invoice. pub action: common_payments_types::RecoveryAction, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, /// 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>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema)] pub struct NullObject; impl Serialize for NullObject { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_none() } } #[cfg(test)] mod null_object_test { use serde_json; use super::*; #[allow(clippy::unwrap_used)] #[test] fn test_null_object_serialization() { let null_object = NullObject; let serialized = serde_json::to_string(&null_object).unwrap(); assert_eq!(serialized, "null"); } }
{ "crate": "api_models", "file": "crates/api_models/src/payments.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 11, "num_structs": 20, "num_tables": null, "score": null, "total_crates": null }
file_api_models_3693078986080439933
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/conditional_configs.rs // Contains: 4 structs, 1 enums use common_utils::events; use euclid::frontend::ast::Program; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DecisionManagerRecord { pub name: String, pub program: Program<common_types::payments::ConditionalConfigs>, pub created_at: i64, pub modified_at: i64, } impl events::ApiEventMetric for DecisionManagerRecord { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct ConditionalConfigReq { pub name: Option<String>, pub algorithm: Option<Program<common_types::payments::ConditionalConfigs>>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DecisionManagerRequest { pub name: Option<String>, pub program: Option<Program<common_types::payments::ConditionalConfigs>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum DecisionManager { DecisionManagerv0(ConditionalConfigReq), DecisionManagerv1(DecisionManagerRequest), } impl events::ApiEventMetric for DecisionManager { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } pub type DecisionManagerResponse = DecisionManagerRecord; #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DecisionManagerRequest { pub name: String, pub program: Program<common_types::payments::ConditionalConfigs>, } #[cfg(feature = "v2")] impl events::ApiEventMetric for DecisionManagerRequest { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } }
{ "crate": "api_models", "file": "crates/api_models/src/conditional_configs.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_api_models_2556802123311209961
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/disputes.rs // Contains: 10 structs, 1 enums use std::collections::HashMap; use common_utils::types::{StringMinorUnit, TimeRange}; use masking::{Deserialize, Serialize}; use serde::de::Error; use time::PrimitiveDateTime; use utoipa::ToSchema; use super::enums::{Currency, DisputeStage, DisputeStatus}; use crate::{admin::MerchantConnectorInfo, files}; #[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq)] pub struct DisputeResponse { /// The identifier for dispute pub dispute_id: String, /// The identifier for payment_intent #[schema(value_type = String)] pub payment_id: common_utils::id_type::PaymentId, /// The identifier for payment_attempt pub attempt_id: String, /// The dispute amount pub amount: StringMinorUnit, /// The three-letter ISO currency code #[schema(value_type = Currency)] pub currency: Currency, /// Stage of the dispute pub dispute_stage: DisputeStage, /// Status of the dispute pub dispute_status: DisputeStatus, /// connector to which dispute is associated with pub connector: String, /// Status of the dispute sent by connector pub connector_status: String, /// Dispute id sent by connector pub connector_dispute_id: String, /// Reason of dispute sent by connector pub connector_reason: Option<String>, /// Reason code of dispute sent by connector pub connector_reason_code: Option<String>, /// Evidence deadline of dispute sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub challenge_required_by: Option<PrimitiveDateTime>, /// Dispute created time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_created_at: Option<PrimitiveDateTime>, /// Dispute updated time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_updated_at: Option<PrimitiveDateTime>, /// Time at which dispute is received #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The `profile_id` associated with the dispute #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The `merchant_connector_id` of the connector / processor through which the dispute was processed #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq)] pub struct DisputeResponsePaymentsRetrieve { /// The identifier for dispute pub dispute_id: String, /// Stage of the dispute pub dispute_stage: DisputeStage, /// Status of the dispute pub dispute_status: DisputeStatus, /// Status of the dispute sent by connector pub connector_status: String, /// Dispute id sent by connector pub connector_dispute_id: String, /// Reason of dispute sent by connector pub connector_reason: Option<String>, /// Reason code of dispute sent by connector pub connector_reason_code: Option<String>, /// Evidence deadline of dispute sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub challenge_required_by: Option<PrimitiveDateTime>, /// Dispute created time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_created_at: Option<PrimitiveDateTime>, /// Dispute updated time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_updated_at: Option<PrimitiveDateTime>, /// Time at which dispute is received #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, } #[derive(Debug, Serialize, Deserialize, strum::Display, Clone)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EvidenceType { CancellationPolicy, CustomerCommunication, CustomerSignature, Receipt, RefundPolicy, ServiceDocumentation, ShippingDocumentation, InvoiceShowingDistinctTransactions, RecurringTransactionAgreement, UncategorizedFile, } #[derive(Clone, Debug, Serialize, ToSchema)] pub struct DisputeEvidenceBlock { /// Evidence type pub evidence_type: EvidenceType, /// File metadata pub file_metadata_response: files::FileMetadataResponse, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct DisputeListGetConstraints { /// The identifier for dispute pub dispute_id: Option<String>, /// The payment_id against which dispute is raised pub payment_id: Option<common_utils::id_type::PaymentId>, /// Limit on the number of objects to return pub limit: Option<u32>, /// The starting point within a list of object pub offset: Option<u32>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The comma separated list of status of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub dispute_status: Option<Vec<DisputeStatus>>, /// The comma separated list of stages of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub dispute_stage: Option<Vec<DisputeStage>>, /// Reason for the dispute pub reason: Option<String>, /// The comma separated list of connectors linked to disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub connector: Option<Vec<String>>, /// The comma separated list of currencies of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub currency: Option<Vec<Currency>>, /// The merchant connector id to filter the disputes list pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<TimeRange>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct DisputeListFilters { /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<Currency>, /// The list of available dispute status filters pub dispute_status: Vec<DisputeStatus>, /// The list of available dispute stage filters pub dispute_stage: Vec<DisputeStage>, } #[derive(Default, Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct SubmitEvidenceRequest { ///Dispute Id pub dispute_id: String, /// Logs showing the usage of service by customer pub access_activity_log: Option<String>, /// Billing address of the customer pub billing_address: Option<String>, /// File Id of cancellation policy pub cancellation_policy: Option<String>, /// Details of showing cancellation policy to customer before purchase pub cancellation_policy_disclosure: Option<String>, /// Details telling why customer's subscription was not cancelled pub cancellation_rebuttal: Option<String>, /// File Id of customer communication pub customer_communication: Option<String>, /// Customer email address pub customer_email_address: Option<String>, /// Customer name pub customer_name: Option<String>, /// IP address of the customer pub customer_purchase_ip: Option<String>, /// Fild Id of customer signature pub customer_signature: Option<String>, /// Product Description pub product_description: Option<String>, /// File Id of receipt pub receipt: Option<String>, /// File Id of refund policy pub refund_policy: Option<String>, /// Details of showing refund policy to customer before purchase pub refund_policy_disclosure: Option<String>, /// Details why customer is not entitled to refund pub refund_refusal_explanation: Option<String>, /// Customer service date pub service_date: Option<String>, /// File Id service documentation pub service_documentation: Option<String>, /// Shipping address of the customer pub shipping_address: Option<String>, /// Delivery service that shipped the product pub shipping_carrier: Option<String>, /// Shipping date pub shipping_date: Option<String>, /// File Id shipping documentation pub shipping_documentation: Option<String>, /// Tracking number of shipped product pub shipping_tracking_number: Option<String>, /// File Id showing two distinct transactions when customer claims a payment was charged twice pub invoice_showing_distinct_transactions: Option<String>, /// File Id of recurring transaction agreement pub recurring_transaction_agreement: Option<String>, /// Any additional supporting file pub uncategorized_file: Option<String>, /// Any additional evidence statements pub uncategorized_text: Option<String>, } #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct DeleteEvidenceRequest { /// Id of the dispute pub dispute_id: String, /// Evidence Type to be deleted pub evidence_type: EvidenceType, } #[derive(Debug, Deserialize, Serialize)] pub struct DisputeRetrieveRequest { /// The identifier for dispute pub dispute_id: String, /// Decider to enable or disable the connector call for dispute retrieve request pub force_sync: Option<bool>, } #[derive(Clone, Debug, serde::Serialize)] pub struct DisputesAggregateResponse { /// Different status of disputes with their count pub status_with_count: HashMap<DisputeStatus, i64>, } #[derive(Debug, Deserialize, Serialize)] pub struct DisputeRetrieveBody { /// Decider to enable or disable the connector call for dispute retrieve request pub force_sync: Option<bool>, } fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error> where D: serde::Deserializer<'de>, T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error, { let output = Option::<&str>::deserialize(v)?; output .map(|s| { s.split(",") .map(|x| x.parse::<T>().map_err(D::Error::custom)) .collect::<Result<_, _>>() }) .transpose() }
{ "crate": "api_models", "file": "crates/api_models/src/disputes.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 10, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-2998818449555947580
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/subscription.rs // Contains: 22 structs, 2 enums use common_enums::connector_enums::InvoiceStatus; use common_types::payments::CustomerAcceptance; use common_utils::{ events::ApiEventMetric, id_type::{ CustomerId, InvoiceId, MerchantConnectorAccountId, MerchantId, PaymentId, ProfileId, SubscriptionId, }, types::{MinorUnit, Url}, }; use masking::Secret; use utoipa::ToSchema; use crate::{ enums::{ AuthenticationType, CaptureMethod, Currency, FutureUsage, IntentStatus, PaymentExperience, PaymentMethod, PaymentMethodType, PaymentType, }, mandates::RecurringDetails, payments::{Address, NextActionData, PaymentMethodDataRequest}, }; /// Request payload for creating a subscription. /// /// This struct captures details required to create a subscription, /// including plan, profile, merchant connector, and optional customer info. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateSubscriptionRequest { /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, /// Identifier for the subscription plan. pub plan_id: Option<String>, /// Optional coupon code applied to the subscription. pub coupon_code: Option<String>, /// customer ID associated with this subscription. pub customer_id: CustomerId, /// payment details for the subscription. pub payment_details: CreateSubscriptionPaymentDetails, /// billing address for the subscription. pub billing: Option<Address>, /// shipping address for the subscription. pub shipping: Option<Address>, } /// Response payload returned after successfully creating a subscription. /// /// Includes details such as subscription ID, status, plan, merchant, and customer info. #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct SubscriptionResponse { /// Unique identifier for the subscription. pub id: SubscriptionId, /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, /// Current status of the subscription. pub status: SubscriptionStatus, /// Identifier for the associated subscription plan. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: Option<String>, /// Associated profile ID. pub profile_id: ProfileId, #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<Secret<String>>, /// Merchant identifier owning this subscription. pub merchant_id: MerchantId, /// Optional coupon code applied to this subscription. pub coupon_code: Option<String>, /// Optional customer ID associated with this subscription. pub customer_id: CustomerId, /// Payment details for the invoice. pub payment: Option<PaymentResponseData>, /// Invoice Details for the subscription. pub invoice: Option<Invoice>, } /// Possible states of a subscription lifecycle. /// /// - `Created`: Subscription was created but not yet activated. /// - `Active`: Subscription is currently active. /// - `InActive`: Subscription is inactive. /// - `Pending`: Subscription is pending activation. /// - `Trial`: Subscription is in a trial period. /// - `Paused`: Subscription is paused. /// - `Unpaid`: Subscription is unpaid. /// - `Onetime`: Subscription is a one-time payment. /// - `Cancelled`: Subscription has been cancelled. /// - `Failed`: Subscription has failed. #[derive(Debug, Clone, serde::Serialize, strum::EnumString, strum::Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SubscriptionStatus { /// Subscription is active. Active, /// Subscription is created but not yet active. Created, /// Subscription is inactive. InActive, /// Subscription is in pending state. Pending, /// Subscription is in trial state. Trial, /// Subscription is paused. Paused, /// Subscription is unpaid. Unpaid, /// Subscription is a one-time payment. Onetime, /// Subscription is cancelled. Cancelled, /// Subscription has failed. Failed, } impl SubscriptionResponse { /// Creates a new [`CreateSubscriptionResponse`] with the given identifiers. /// /// By default, `client_secret`, `coupon_code`, and `customer` fields are `None`. #[allow(clippy::too_many_arguments)] pub fn new( id: SubscriptionId, merchant_reference_id: Option<String>, status: SubscriptionStatus, plan_id: Option<String>, item_price_id: Option<String>, profile_id: ProfileId, merchant_id: MerchantId, client_secret: Option<Secret<String>>, customer_id: CustomerId, payment: Option<PaymentResponseData>, invoice: Option<Invoice>, ) -> Self { Self { id, merchant_reference_id, status, plan_id, item_price_id, profile_id, client_secret, merchant_id, coupon_code: None, customer_id, payment, invoice, } } } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct GetPlansResponse { pub plan_id: String, pub name: String, pub description: Option<String>, pub price_id: Vec<SubscriptionPlanPrices>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct SubscriptionPlanPrices { pub price_id: String, pub plan_id: Option<String>, pub amount: MinorUnit, pub currency: Currency, pub interval: PeriodUnit, pub interval_count: i64, pub trial_period: Option<i64>, pub trial_period_unit: Option<PeriodUnit>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub enum PeriodUnit { Day, Week, Month, Year, } /// For Client based calls, SDK will use the client_secret\nin order to call /payment_methods\nClient secret will be generated whenever a new\npayment method is created #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ClientSecret(String); impl ClientSecret { pub fn new(secret: String) -> Self { Self(secret) } pub fn as_str(&self) -> &str { &self.0 } pub fn as_string(&self) -> &String { &self.0 } } #[derive(serde::Deserialize, serde::Serialize, Debug, ToSchema)] pub struct GetPlansQuery { #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<ClientSecret>, pub limit: Option<u32>, pub offset: Option<u32>, } impl ApiEventMetric for SubscriptionResponse {} impl ApiEventMetric for CreateSubscriptionRequest {} impl ApiEventMetric for GetPlansQuery {} impl ApiEventMetric for GetPlansResponse {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionPaymentDetails { pub shipping: Option<Address>, pub billing: Option<Address>, pub payment_method: PaymentMethod, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: PaymentMethodDataRequest, pub customer_acceptance: Option<CustomerAcceptance>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateSubscriptionPaymentDetails { /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = String)] pub return_url: Url, pub setup_future_usage: Option<FutureUsage>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentDetails { pub payment_method: Option<PaymentMethod>, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: Option<PaymentMethodDataRequest>, pub setup_future_usage: Option<FutureUsage>, pub customer_acceptance: Option<CustomerAcceptance>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, pub payment_type: Option<PaymentType>, } // Creating new type for PaymentRequest API call as usage of api_models::PaymentsRequest will result in invalid payment request during serialization // Eg: Amount will be serialized as { amount: {Value: 100 }} #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CreatePaymentsRequestData { pub amount: MinorUnit, pub currency: Currency, pub customer_id: Option<CustomerId>, pub billing: Option<Address>, pub shipping: Option<Address>, pub profile_id: Option<ProfileId>, pub setup_future_usage: Option<FutureUsage>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct ConfirmPaymentsRequestData { pub billing: Option<Address>, pub shipping: Option<Address>, pub profile_id: Option<ProfileId>, pub payment_method: PaymentMethod, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: PaymentMethodDataRequest, pub customer_acceptance: Option<CustomerAcceptance>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CreateAndConfirmPaymentsRequestData { pub amount: MinorUnit, pub currency: Currency, pub customer_id: Option<CustomerId>, pub confirm: bool, pub billing: Option<Address>, pub shipping: Option<Address>, pub profile_id: Option<ProfileId>, pub setup_future_usage: Option<FutureUsage>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, pub payment_method: Option<PaymentMethod>, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: Option<PaymentMethodDataRequest>, pub customer_acceptance: Option<CustomerAcceptance>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentResponseData { pub payment_id: PaymentId, pub status: IntentStatus, pub amount: MinorUnit, pub currency: Currency, pub profile_id: Option<ProfileId>, pub connector: Option<String>, /// Identifier for Payment Method #[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<Secret<String>>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub next_action: Option<NextActionData>, pub payment_experience: Option<PaymentExperience>, pub error_code: Option<String>, pub error_message: Option<String>, pub payment_method_type: Option<PaymentMethodType>, #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<Secret<String>>, pub billing: Option<Address>, pub shipping: Option<Address>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateMitPaymentRequestData { pub amount: MinorUnit, pub currency: Currency, pub confirm: bool, pub customer_id: Option<CustomerId>, pub recurring_details: Option<RecurringDetails>, pub off_session: Option<bool>, pub profile_id: Option<ProfileId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionRequest { #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<ClientSecret>, /// Payment details for the invoice. pub payment_details: ConfirmSubscriptionPaymentDetails, } impl ConfirmSubscriptionRequest { pub fn get_billing_address(&self) -> Option<Address> { self.payment_details .payment_method_data .billing .as_ref() .or(self.payment_details.billing.as_ref()) .cloned() } } impl ApiEventMetric for ConfirmSubscriptionRequest {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateAndConfirmSubscriptionRequest { /// Identifier for the associated plan_id. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, /// Identifier for the coupon code for the subscription. pub coupon_code: Option<String>, /// Identifier for customer. pub customer_id: CustomerId, /// Billing address for the subscription. pub billing: Option<Address>, /// Shipping address for the subscription. pub shipping: Option<Address>, /// Payment details for the invoice. pub payment_details: PaymentDetails, /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, } impl CreateAndConfirmSubscriptionRequest { pub fn get_billing_address(&self) -> Option<Address> { self.payment_details .payment_method_data .as_ref() .and_then(|data| data.billing.clone()) .or(self.billing.clone()) } } impl ApiEventMetric for CreateAndConfirmSubscriptionRequest {} #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct ConfirmSubscriptionResponse { /// Unique identifier for the subscription. pub id: SubscriptionId, /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, /// Current status of the subscription. pub status: SubscriptionStatus, /// Identifier for the associated subscription plan. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: Option<String>, /// Optional coupon code applied to this subscription. pub coupon: Option<String>, /// Associated profile ID. pub profile_id: ProfileId, /// Payment details for the invoice. pub payment: Option<PaymentResponseData>, /// Customer ID associated with this subscription. pub customer_id: Option<CustomerId>, /// Invoice Details for the subscription. pub invoice: Option<Invoice>, /// Billing Processor subscription ID. pub billing_processor_subscription_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct Invoice { /// Unique identifier for the invoice. pub id: InvoiceId, /// Unique identifier for the subscription. pub subscription_id: SubscriptionId, /// Identifier for the merchant. pub merchant_id: MerchantId, /// Identifier for the profile. pub profile_id: ProfileId, /// Identifier for the merchant connector account. pub merchant_connector_id: MerchantConnectorAccountId, /// Identifier for the Payment. pub payment_intent_id: Option<PaymentId>, /// Identifier for Payment Method #[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<String>, /// Identifier for the Customer. pub customer_id: CustomerId, /// Invoice amount. pub amount: MinorUnit, /// Currency for the invoice payment. pub currency: Currency, /// Status of the invoice. pub status: InvoiceStatus, } impl ApiEventMetric for ConfirmSubscriptionResponse {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpdateSubscriptionRequest { /// Identifier for the associated plan_id. pub plan_id: String, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, } impl ApiEventMetric for UpdateSubscriptionRequest {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct EstimateSubscriptionQuery { /// Identifier for the associated subscription plan. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, /// Identifier for the coupon code for the subscription. pub coupon_code: Option<String>, } impl ApiEventMetric for EstimateSubscriptionQuery {} #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct EstimateSubscriptionResponse { /// Estimated amount to be charged for the invoice. pub amount: MinorUnit, /// Currency for the amount. pub currency: Currency, /// Identifier for the associated plan_id. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: Option<String>, /// Identifier for the coupon code for the subscription. pub coupon_code: Option<String>, /// Identifier for customer. pub customer_id: Option<CustomerId>, pub line_items: Vec<SubscriptionLineItem>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct SubscriptionLineItem { /// Unique identifier for the line item. pub item_id: String, /// Type of the line item. pub item_type: String, /// Description of the line item. pub description: String, /// Amount for the line item. pub amount: MinorUnit, /// Currency for the line item pub currency: Currency, /// Quantity of the line item. pub quantity: i64, } impl ApiEventMetric for EstimateSubscriptionResponse {}
{ "crate": "api_models", "file": "crates/api_models/src/subscription.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 22, "num_tables": null, "score": null, "total_crates": null }
file_api_models_3348291150145270102
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/enums.rs // Contains: 1 structs, 15 enums use std::str::FromStr; pub use common_enums::*; use utoipa::ToSchema; pub use super::connector_enums::Connector; #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] /// 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(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithm { RoundRobin, MaxConversion, MinCost, Custom, } #[cfg(feature = "payouts")] #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutConnectors { Adyen, Adyenplatform, Cybersource, Ebanx, Gigadat, Loonio, Nomupay, Nuvei, Payone, Paypal, Stripe, Wise, Worldpay, } #[cfg(feature = "v2")] /// Whether active attempt is to be set/unset #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum UpdateActiveAttempt { /// Request to set the active attempt id #[schema(value_type = Option<String>)] Set(common_utils::id_type::GlobalAttemptId), /// To unset the active attempt id Unset, } #[cfg(feature = "payouts")] impl From<PayoutConnectors> for RoutableConnectors { fn from(value: PayoutConnectors) -> Self { match value { PayoutConnectors::Adyen => Self::Adyen, PayoutConnectors::Adyenplatform => Self::Adyenplatform, PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Gigadat => Self::Gigadat, PayoutConnectors::Loonio => Self::Loonio, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Stripe => Self::Stripe, PayoutConnectors::Wise => Self::Wise, PayoutConnectors::Worldpay => Self::Worldpay, } } } #[cfg(feature = "payouts")] impl From<PayoutConnectors> for Connector { fn from(value: PayoutConnectors) -> Self { match value { PayoutConnectors::Adyen => Self::Adyen, PayoutConnectors::Adyenplatform => Self::Adyenplatform, PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Gigadat => Self::Gigadat, PayoutConnectors::Loonio => Self::Loonio, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Stripe => Self::Stripe, PayoutConnectors::Wise => Self::Wise, PayoutConnectors::Worldpay => Self::Worldpay, } } } #[cfg(feature = "payouts")] impl TryFrom<Connector> for PayoutConnectors { type Error = String; fn try_from(value: Connector) -> Result<Self, Self::Error> { match value { Connector::Adyen => Ok(Self::Adyen), Connector::Adyenplatform => Ok(Self::Adyenplatform), Connector::Cybersource => Ok(Self::Cybersource), Connector::Ebanx => Ok(Self::Ebanx), Connector::Gigadat => Ok(Self::Gigadat), Connector::Loonio => Ok(Self::Loonio), Connector::Nuvei => Ok(Self::Nuvei), Connector::Nomupay => Ok(Self::Nomupay), Connector::Payone => Ok(Self::Payone), Connector::Paypal => Ok(Self::Paypal), Connector::Stripe => Ok(Self::Stripe), Connector::Wise => Ok(Self::Wise), Connector::Worldpay => Ok(Self::Worldpay), _ => Err(format!("Invalid payout connector {value}")), } } } #[cfg(feature = "frm")] #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmConnectors { /// Signifyd Risk Manager. Official docs: https://docs.signifyd.com/ Signifyd, Riskified, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum TaxConnectors { Taxjar, } #[derive(Clone, Debug, serde::Serialize, strum::EnumString, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BillingConnectors { Chargebee, Recurly, Stripebilling, Custombilling, #[cfg(feature = "dummy_connector")] DummyBillingConnector, } #[derive(Clone, Copy, Debug, serde::Serialize, strum::EnumString, Eq, PartialEq)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum VaultConnectors { Vgs, HyperswitchVault, Tokenex, } impl From<VaultConnectors> for Connector { fn from(value: VaultConnectors) -> Self { match value { VaultConnectors::Vgs => Self::Vgs, VaultConnectors::HyperswitchVault => Self::HyperswitchVault, VaultConnectors::Tokenex => Self::Tokenex, } } } #[derive( Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FrmAction { CancelTxn, AutoRefund, ManualReview, } #[derive( Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FrmPreferredFlowTypes { Pre, Post, } #[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] pub struct UnresolvedResponseReason { pub code: String, /// A message to merchant to give hint on next action he/she should do to resolve pub message: String, } /// Possible field type of required fields in payment_method_data #[derive( Clone, Debug, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FieldType { UserCardNumber, UserCardExpiryMonth, UserCardExpiryYear, UserCardCvc, UserCardNetwork, UserFullName, UserEmailAddress, UserPhoneNumber, UserPhoneNumberCountryCode, //phone number's country code UserCountry { options: Vec<String> }, //for country inside payment method data ex- bank redirect UserCurrency { options: Vec<String> }, UserCryptoCurrencyNetwork, //for crypto network associated with the cryptopcurrency UserBillingName, UserAddressLine1, UserAddressLine2, UserAddressCity, UserAddressPincode, UserAddressState, UserAddressCountry { options: Vec<String> }, UserShippingName, UserShippingAddressLine1, UserShippingAddressLine2, UserShippingAddressCity, UserShippingAddressPincode, UserShippingAddressState, UserShippingAddressCountry { options: Vec<String> }, UserSocialSecurityNumber, UserBlikCode, UserBank, UserBankOptions { options: Vec<String> }, UserBankAccountNumber, UserSourceBankAccountId, UserDestinationBankAccountId, Text, DropDown { options: Vec<String> }, UserDateOfBirth, UserVpaId, LanguagePreference { options: Vec<String> }, UserPixKey, UserCpf, UserCnpj, UserIban, UserBsbNumber, UserBankSortCode, UserBankRoutingNumber, UserBankType { options: Vec<String> }, UserBankAccountHolderName, UserMsisdn, UserClientIdentifier, OrderDetailsProductName, } impl FieldType { pub fn get_billing_variants() -> Vec<Self> { vec![ Self::UserBillingName, Self::UserAddressLine1, Self::UserAddressLine2, Self::UserAddressCity, Self::UserAddressPincode, Self::UserAddressState, Self::UserAddressCountry { options: vec![] }, ] } pub fn get_shipping_variants() -> Vec<Self> { vec![ Self::UserShippingName, Self::UserShippingAddressLine1, Self::UserShippingAddressLine2, Self::UserShippingAddressCity, Self::UserShippingAddressPincode, Self::UserShippingAddressState, Self::UserShippingAddressCountry { options: vec![] }, ] } } /// This implementatiobn is to ignore the inner value of UserAddressCountry enum while comparing impl PartialEq for FieldType { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::UserCardNumber, Self::UserCardNumber) => true, (Self::UserCardExpiryMonth, Self::UserCardExpiryMonth) => true, (Self::UserCardExpiryYear, Self::UserCardExpiryYear) => true, (Self::UserCardCvc, Self::UserCardCvc) => true, (Self::UserFullName, Self::UserFullName) => true, (Self::UserEmailAddress, Self::UserEmailAddress) => true, (Self::UserPhoneNumber, Self::UserPhoneNumber) => true, (Self::UserPhoneNumberCountryCode, Self::UserPhoneNumberCountryCode) => true, ( Self::UserCountry { options: options_self, }, Self::UserCountry { options: options_other, }, ) => options_self.eq(options_other), ( Self::UserCurrency { options: options_self, }, Self::UserCurrency { options: options_other, }, ) => options_self.eq(options_other), (Self::UserCryptoCurrencyNetwork, Self::UserCryptoCurrencyNetwork) => true, (Self::UserBillingName, Self::UserBillingName) => true, (Self::UserAddressLine1, Self::UserAddressLine1) => true, (Self::UserAddressLine2, Self::UserAddressLine2) => true, (Self::UserAddressCity, Self::UserAddressCity) => true, (Self::UserAddressPincode, Self::UserAddressPincode) => true, (Self::UserAddressState, Self::UserAddressState) => true, (Self::UserAddressCountry { .. }, Self::UserAddressCountry { .. }) => true, (Self::UserShippingName, Self::UserShippingName) => true, (Self::UserShippingAddressLine1, Self::UserShippingAddressLine1) => true, (Self::UserShippingAddressLine2, Self::UserShippingAddressLine2) => true, (Self::UserShippingAddressCity, Self::UserShippingAddressCity) => true, (Self::UserShippingAddressPincode, Self::UserShippingAddressPincode) => true, (Self::UserShippingAddressState, Self::UserShippingAddressState) => true, (Self::UserShippingAddressCountry { .. }, Self::UserShippingAddressCountry { .. }) => { true } (Self::UserBlikCode, Self::UserBlikCode) => true, (Self::UserBank, Self::UserBank) => true, (Self::Text, Self::Text) => true, ( Self::DropDown { options: options_self, }, Self::DropDown { options: options_other, }, ) => options_self.eq(options_other), (Self::UserDateOfBirth, Self::UserDateOfBirth) => true, (Self::UserVpaId, Self::UserVpaId) => true, (Self::UserPixKey, Self::UserPixKey) => true, (Self::UserCpf, Self::UserCpf) => true, (Self::UserCnpj, Self::UserCnpj) => true, (Self::LanguagePreference { .. }, Self::LanguagePreference { .. }) => true, (Self::UserMsisdn, Self::UserMsisdn) => true, (Self::UserClientIdentifier, Self::UserClientIdentifier) => true, (Self::OrderDetailsProductName, Self::OrderDetailsProductName) => true, _unused => false, } } } #[cfg(test)] mod test { use super::*; #[test] fn test_partialeq_for_field_type() { let user_address_country_is_us = FieldType::UserAddressCountry { options: vec!["US".to_string()], }; let user_address_country_is_all = FieldType::UserAddressCountry { options: vec!["ALL".to_string()], }; assert!(user_address_country_is_us.eq(&user_address_country_is_all)) } } /// Denotes the retry action #[derive( Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, Clone, PartialEq, Eq, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RetryAction { /// Manual retry through request is being deprecated, now it is available through profile ManualRetry, /// Denotes that the payment is requeued Requeue, } #[derive(Clone, Copy)] pub enum LockerChoice { HyperswitchCardVault, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PmAuthConnectors { Plaid, } pub fn convert_pm_auth_connector(connector_name: &str) -> Option<PmAuthConnectors> { PmAuthConnectors::from_str(connector_name).ok() } pub fn convert_authentication_connector(connector_name: &str) -> Option<AuthenticationConnectors> { AuthenticationConnectors::from_str(connector_name).ok() } pub fn convert_tax_connector(connector_name: &str) -> Option<TaxConnectors> { TaxConnectors::from_str(connector_name).ok() } pub fn convert_billing_connector(connector_name: &str) -> Option<BillingConnectors> { BillingConnectors::from_str(connector_name).ok() } #[cfg(feature = "frm")] pub fn convert_frm_connector(connector_name: &str) -> Option<FrmConnectors> { FrmConnectors::from_str(connector_name).ok() } pub fn convert_vault_connector(connector_name: &str) -> Option<VaultConnectors> { VaultConnectors::from_str(connector_name).ok() } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] pub enum ReconPermissionScope { #[serde(rename = "R")] Read = 0, #[serde(rename = "RW")] Write = 1, } impl From<PermissionScope> for ReconPermissionScope { fn from(scope: PermissionScope) -> Self { match scope { PermissionScope::Read => Self::Read, PermissionScope::Write => Self::Write, } } } #[cfg(feature = "v2")] #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[serde(rename_all = "UPPERCASE")] #[strum(serialize_all = "UPPERCASE")] pub enum TokenStatus { /// Indicates that the token is active and can be used for payments Active, /// Indicates that the token is suspended from network's end for some reason and can't be used for payments until it is re-activated Suspended, /// Indicates that the token is deactivated and further can't be used for payments Deactivated, }
{ "crate": "api_models", "file": "crates/api_models/src/enums.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 15, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_api_models_1295636377588420235
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/blocklist.rs // Contains: 7 structs, 1 enums use common_enums::enums; use common_utils::events::ApiEventMetric; use masking::StrongSecret; use utoipa::ToSchema; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type", content = "data")] pub enum BlocklistRequest { CardBin(String), Fingerprint(String), ExtendedCardBin(String), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GenerateFingerprintRequest { pub card: Card, pub hash_key: StrongSecret<String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct Card { pub card_number: StrongSecret<String>, } pub type AddToBlocklistRequest = BlocklistRequest; pub type DeleteFromBlocklistRequest = BlocklistRequest; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BlocklistResponse { pub fingerprint_id: String, #[schema(value_type = BlocklistDataKind)] pub data_kind: enums::BlocklistDataKind, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct GenerateFingerprintResponsePayload { pub card_fingerprint: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleBlocklistResponse { pub blocklist_guard_status: String, } pub type AddToBlocklistResponse = BlocklistResponse; pub type DeleteFromBlocklistResponse = BlocklistResponse; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ListBlocklistQuery { #[schema(value_type = BlocklistDataKind)] pub data_kind: enums::BlocklistDataKind, #[serde(default = "default_list_limit")] pub limit: u16, #[serde(default)] pub offset: u16, pub client_secret: Option<String>, } fn default_list_limit() -> u16 { 10 } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleBlocklistQuery { #[schema(value_type = BlocklistDataKind)] pub status: bool, } impl ApiEventMetric for BlocklistRequest {} impl ApiEventMetric for BlocklistResponse {} impl ApiEventMetric for ToggleBlocklistResponse {} impl ApiEventMetric for ListBlocklistQuery {} impl ApiEventMetric for GenerateFingerprintRequest {} impl ApiEventMetric for ToggleBlocklistQuery {} impl ApiEventMetric for GenerateFingerprintResponsePayload {} impl ApiEventMetric for Card {}
{ "crate": "api_models", "file": "crates/api_models/src/blocklist.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 7, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-2585142289153246131
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/user.rs // Contains: 60 structs, 3 enums use std::fmt::Debug; use common_enums::{EntityType, TokenPurpose}; use common_utils::{crypto::OptionalEncryptableName, id_type, pii}; use masking::Secret; use utoipa::ToSchema; use crate::user_role::UserStatus; pub mod dashboard_metadata; #[cfg(feature = "dummy_connector")] pub mod sample_data; #[cfg(feature = "control_center_theme")] pub mod theme; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct SignUpWithMerchantIdRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, pub company_name: String, } pub type SignUpWithMerchantIdResponse = AuthorizeResponse; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct SignUpRequest { pub email: pii::Email, pub password: Secret<String>, } pub type SignInRequest = SignUpRequest; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct ConnectAccountRequest { pub email: pii::Email, } pub type ConnectAccountResponse = AuthorizeResponse; #[derive(serde::Serialize, Debug, Clone)] pub struct AuthorizeResponse { pub is_email_sent: bool, //this field is added for audit/debug reasons #[serde(skip_serializing)] pub user_id: String, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ChangePasswordRequest { pub new_password: Secret<String>, pub old_password: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ForgotPasswordRequest { pub email: pii::Email, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ResetPasswordRequest { pub token: Secret<String>, pub password: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct RotatePasswordRequest { pub password: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct InviteUserRequest { pub email: pii::Email, pub name: Secret<String>, pub role_id: String, } #[derive(Debug, serde::Serialize)] pub struct InviteMultipleUserResponse { pub email: pii::Email, pub is_email_sent: bool, #[serde(skip_serializing_if = "Option::is_none")] pub password: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub error: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ReInviteUserRequest { pub email: pii::Email, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct AcceptInviteFromEmailRequest { pub token: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchOrganizationRequest { pub org_id: id_type::OrganizationId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchMerchantRequest { pub merchant_id: id_type::MerchantId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchProfileRequest { pub profile_id: id_type::ProfileId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CloneConnectorSource { pub mca_id: id_type::MerchantConnectorAccountId, pub merchant_id: id_type::MerchantId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CloneConnectorDestination { pub connector_label: Option<String>, pub profile_id: id_type::ProfileId, pub merchant_id: id_type::MerchantId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CloneConnectorRequest { pub source: CloneConnectorSource, pub destination: CloneConnectorDestination, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CreateInternalUserRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, pub role_id: String, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CreateTenantUserRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct UserOrgMerchantCreateRequest { pub organization_name: Secret<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub merchant_name: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PlatformAccountCreateRequest { #[schema(max_length = 64, value_type = String, example = "organization_abc")] pub organization_name: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PlatformAccountCreateResponse { #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_abc")] pub org_id: id_type::OrganizationId, #[schema(value_type = Option<String>, example = "organization_abc")] pub org_name: Option<String>, #[schema(value_type = OrganizationType, example = "standard")] pub org_type: common_enums::OrganizationType, #[schema(value_type = String, example = "merchant_abc")] pub merchant_id: id_type::MerchantId, #[schema(value_type = MerchantAccountType, example = "standard")] pub merchant_account_type: common_enums::MerchantAccountType, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserMerchantCreate { pub company_name: String, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: Option<common_enums::MerchantAccountRequestType>, } #[derive(serde::Serialize, Debug, Clone)] pub struct GetUserDetailsResponse { pub merchant_id: id_type::MerchantId, pub name: Secret<String>, pub email: pii::Email, pub verification_days_left: Option<i64>, pub role_id: String, // This field is added for audit/debug reasons #[serde(skip_serializing)] pub user_id: String, pub org_id: id_type::OrganizationId, pub is_two_factor_auth_setup: bool, pub recovery_codes_left: Option<usize>, pub profile_id: id_type::ProfileId, pub entity_type: EntityType, pub theme_id: Option<String>, pub version: common_enums::ApiVersion, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetUserRoleDetailsRequest { pub email: pii::Email, } #[derive(Debug, serde::Serialize)] pub struct GetUserRoleDetailsResponseV2 { pub role_id: String, pub org: NameIdUnit<Option<String>, id_type::OrganizationId>, pub merchant: Option<NameIdUnit<OptionalEncryptableName, id_type::MerchantId>>, pub profile: Option<NameIdUnit<String, id_type::ProfileId>>, pub status: UserStatus, pub entity_type: EntityType, pub role_name: String, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct NameIdUnit<N: Debug + Clone, I: Debug + Clone> { pub name: N, pub id: I, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyEmailRequest { pub token: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct SendVerifyEmailRequest { pub email: pii::Email, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateUserAccountDetailsRequest { pub name: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SkipTwoFactorAuthQueryParam { pub skip_two_factor_auth: Option<bool>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TokenResponse { pub token: Secret<String>, pub token_type: TokenPurpose, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthStatusResponse { pub totp: bool, pub recovery_code: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthAttempts { pub is_completed: bool, pub remaining_attempts: u8, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthStatusResponseWithAttempts { pub totp: TwoFactorAuthAttempts, pub recovery_code: TwoFactorAuthAttempts, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorStatus { pub status: Option<TwoFactorAuthStatusResponseWithAttempts>, pub is_skippable: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserFromEmailRequest { pub token: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct BeginTotpResponse { pub secret: Option<TotpSecret>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TotpSecret { pub secret: Secret<String>, pub totp_url: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyTotpRequest { pub totp: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyRecoveryCodeRequest { pub recovery_code: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct RecoveryCodes { pub recovery_codes: Vec<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(tag = "auth_type")] #[serde(rename_all = "snake_case")] pub enum AuthConfig { OpenIdConnect { private_config: OpenIdConnectPrivateConfig, public_config: OpenIdConnectPublicConfig, }, MagicLink, Password, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct OpenIdConnectPrivateConfig { pub base_url: String, pub client_id: Secret<String>, pub client_secret: Secret<String>, pub private_key: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct OpenIdConnectPublicConfig { pub name: OpenIdProvider, } #[derive( Debug, serde::Deserialize, serde::Serialize, Copy, Clone, strum::Display, Eq, PartialEq, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OpenIdProvider { Okta, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct OpenIdConnect { pub name: OpenIdProvider, pub base_url: String, pub client_id: String, pub client_secret: Secret<String>, pub private_key: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateUserAuthenticationMethodRequest { pub owner_id: String, pub owner_type: common_enums::Owner, pub auth_method: AuthConfig, pub allow_signup: bool, pub email_domain: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateUserAuthenticationMethodResponse { pub id: String, pub auth_id: String, pub owner_id: String, pub owner_type: common_enums::Owner, pub auth_type: common_enums::UserAuthType, pub email_domain: Option<String>, pub allow_signup: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum UpdateUserAuthenticationMethodRequest { AuthMethod { id: String, auth_config: AuthConfig, }, EmailDomain { owner_id: String, email_domain: String, }, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetUserAuthenticationMethodsRequest { pub auth_id: Option<String>, pub email_domain: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserAuthenticationMethodResponse { pub id: String, pub auth_id: String, pub auth_method: AuthMethodDetails, pub allow_signup: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthMethodDetails { #[serde(rename = "type")] pub auth_type: common_enums::UserAuthType, pub name: Option<OpenIdProvider>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetSsoAuthUrlRequest { pub id: String, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SsoSignInRequest { pub state: Secret<String>, pub code: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthIdAndThemeIdQueryParam { pub auth_id: Option<String>, pub theme_id: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthSelectRequest { pub id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct UserKeyTransferRequest { pub from: u32, pub limit: u32, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserTransferKeyResponse { pub total_transferred: usize, } #[derive(Debug, serde::Serialize)] pub struct ListOrgsForUserResponse { pub org_id: id_type::OrganizationId, pub org_name: Option<String>, pub org_type: common_enums::OrganizationType, } #[derive(Debug, serde::Serialize)] pub struct UserMerchantAccountResponse { pub merchant_id: id_type::MerchantId, pub merchant_name: OptionalEncryptableName, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, pub version: common_enums::ApiVersion, } #[derive(Debug, serde::Serialize)] pub struct ListProfilesForUserInOrgAndMerchantAccountResponse { pub profile_id: id_type::ProfileId, pub profile_name: String, }
{ "crate": "api_models", "file": "crates/api_models/src/user.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 60, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-2397347078680421512
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/user_role.rs // Contains: 9 structs, 2 enums use common_enums::{ParentGroup, PermissionGroup}; use common_utils::pii; use masking::Secret; pub mod role; #[derive(Debug, serde::Serialize)] pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>); #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum AuthorizationInfo { Group(GroupInfo), GroupWithTag(ParentInfo), } // TODO: To be deprecated #[derive(Debug, serde::Serialize)] pub struct GroupInfo { pub group: PermissionGroup, pub description: &'static str, } #[derive(Debug, serde::Serialize, Clone)] pub struct ParentInfo { pub name: ParentGroup, pub description: &'static str, pub groups: Vec<PermissionGroup>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateUserRoleRequest { pub email: pii::Email, pub role_id: String, } #[derive(Debug, serde::Serialize)] pub enum UserStatus { Active, InvitationSent, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct DeleteUserRoleRequest { pub email: pii::Email, } #[derive(Debug, serde::Serialize)] pub struct ListUsersInEntityResponse { pub email: pii::Email, pub roles: Vec<role::MinimalRoleInfo>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ListInvitationForUserResponse { pub entity_id: String, pub entity_type: common_enums::EntityType, pub entity_name: Option<Secret<String>>, pub role_id: String, } pub type AcceptInvitationsV2Request = Vec<Entity>; pub type AcceptInvitationsPreAuthRequest = Vec<Entity>; #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct Entity { pub entity_id: String, pub entity_type: common_enums::EntityType, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ListUsersInEntityRequest { pub entity_type: Option<common_enums::EntityType>, }
{ "crate": "api_models", "file": "crates/api_models/src/user_role.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 9, "num_tables": null, "score": null, "total_crates": null }
file_api_models_-3439127540414128956
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/files.rs // Contains: 3 structs, 0 enums use utoipa::ToSchema; #[derive(Debug, serde::Serialize, ToSchema)] pub struct CreateFileResponse { /// ID of the file created pub file_id: String, } #[derive(Debug, serde::Serialize, ToSchema, Clone)] pub struct FileMetadataResponse { /// ID of the file created pub file_id: String, /// Name of the file pub file_name: Option<String>, /// Size of the file pub file_size: i32, /// Type of the file pub file_type: String, /// File availability pub available: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct FileRetrieveQuery { ///Dispute Id pub dispute_id: Option<String>, }
{ "crate": "api_models", "file": "crates/api_models/src/files.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }