text
stringlengths
81
477k
file_path
stringlengths
22
92
module
stringlengths
13
87
token_count
int64
24
94.8k
has_source_code
bool
1 class
// File: crates/common_types/src/payment_methods.rs // Module: common_types::src::payment_methods //! Common types to be used in payment methods use diesel::{ backend::Backend, deserialize, deserialize::FromSql, serialize::ToSql, sql_types::{Json, Jsonb}, AsExpression, Queryable, }; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; /// Details of all the payment methods enabled for the connector for the given merchant account // sql_type for this can be json instead of jsonb. This is because validation at database is not required since it will always be written by the application. // This is a performance optimization to avoid json validation at database level. // jsonb enables faster querying on json columns, but it doesn't justify here since we are not querying on this column. // https://docs.rs/diesel/latest/diesel/sql_types/struct.Jsonb.html #[derive(Debug, Clone, Serialize, Deserialize, ToSchema, AsExpression)] #[serde(deny_unknown_fields)] #[diesel(sql_type = Json)] pub struct PaymentMethodsEnabled { /// Type of payment method. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: common_enums::PaymentMethod, /// Payment method configuration, this includes all the filters associated with the payment method pub payment_method_subtypes: Option<Vec<RequestPaymentMethodTypes>>, } // Custom FromSql implementation to handle deserialization of v1 data format impl FromSql<Json, diesel::pg::Pg> for PaymentMethodsEnabled { fn from_sql(bytes: <diesel::pg::Pg as Backend>::RawValue<'_>) -> deserialize::Result<Self> { let helper: PaymentMethodsEnabledHelper = serde_json::from_slice(bytes.as_bytes()) .map_err(|e| Box::new(diesel::result::Error::DeserializationError(Box::new(e))))?; Ok(helper.into()) } } // In this ToSql implementation, we are directly serializing the PaymentMethodsEnabled struct to JSON impl ToSql<Json, diesel::pg::Pg> for PaymentMethodsEnabled { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>, ) -> diesel::serialize::Result { let value = serde_json::to_value(self)?; // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends // please refer to the diesel migration blog: // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations <serde_json::Value as ToSql<Json, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow()) } } // Intermediate type to handle deserialization of v1 data format of PaymentMethodsEnabled #[derive(serde::Deserialize)] #[serde(untagged)] enum PaymentMethodsEnabledHelper { V2 { payment_method_type: common_enums::PaymentMethod, payment_method_subtypes: Option<Vec<RequestPaymentMethodTypes>>, }, V1 { payment_method: common_enums::PaymentMethod, payment_method_types: Option<Vec<RequestPaymentMethodTypesV1>>, }, } impl From<PaymentMethodsEnabledHelper> for PaymentMethodsEnabled { fn from(helper: PaymentMethodsEnabledHelper) -> Self { match helper { PaymentMethodsEnabledHelper::V2 { payment_method_type, payment_method_subtypes, } => Self { payment_method_type, payment_method_subtypes, }, PaymentMethodsEnabledHelper::V1 { payment_method, payment_method_types, } => Self { payment_method_type: payment_method, payment_method_subtypes: payment_method_types.map(|subtypes| { subtypes .into_iter() .map(RequestPaymentMethodTypes::from) .collect() }), }, } } } impl PaymentMethodsEnabled { /// Get payment_method_type #[cfg(feature = "v2")] pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> { Some(self.payment_method_type) } /// Get payment_method_subtypes #[cfg(feature = "v2")] pub fn get_payment_method_type(&self) -> Option<&Vec<RequestPaymentMethodTypes>> { self.payment_method_subtypes.as_ref() } } /// Details of a specific payment method subtype enabled for the connector for the given merchant account #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, Hash)] pub struct RequestPaymentMethodTypes { /// The payment method subtype #[schema(value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The payment experience for the payment method #[schema(value_type = Option<PaymentExperience>)] pub payment_experience: Option<common_enums::PaymentExperience>, /// List of cards networks that are enabled for this payment method, applicable for credit and debit payment method subtypes only #[schema(value_type = Option<Vec<CardNetwork>>)] pub card_networks: Option<Vec<common_enums::CardNetwork>>, /// List of currencies accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "enable_only", "list": ["USD", "INR"] } ), value_type = Option<AcceptedCurrencies>)] pub accepted_currencies: Option<AcceptedCurrencies>, /// List of Countries accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "enable_only", "list": ["UK", "AU"] } ), value_type = Option<AcceptedCountries>)] pub accepted_countries: Option<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<common_utils::types::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<common_utils::types::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>, } impl From<RequestPaymentMethodTypesV1> for RequestPaymentMethodTypes { fn from(value: RequestPaymentMethodTypesV1) -> Self { Self { payment_method_subtype: value.payment_method_type, payment_experience: value.payment_experience, card_networks: value.card_networks, accepted_currencies: value.accepted_currencies, accepted_countries: value.accepted_countries, minimum_amount: value.minimum_amount, maximum_amount: value.maximum_amount, recurring_enabled: value.recurring_enabled, installment_payment_enabled: value.installment_payment_enabled, } } } #[derive(serde::Deserialize)] struct RequestPaymentMethodTypesV1 { pub payment_method_type: common_enums::PaymentMethodType, pub payment_experience: Option<common_enums::PaymentExperience>, pub card_networks: Option<Vec<common_enums::CardNetwork>>, pub accepted_currencies: Option<AcceptedCurrencies>, pub accepted_countries: Option<AcceptedCountries>, pub minimum_amount: Option<common_utils::types::MinorUnit>, pub maximum_amount: Option<common_utils::types::MinorUnit>, pub recurring_enabled: Option<bool>, pub installment_payment_enabled: Option<bool>, } impl RequestPaymentMethodTypes { ///Get payment_method_subtype pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethodType> { Some(self.payment_method_subtype) } } #[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)] #[serde( deny_unknown_fields, tag = "type", content = "list", rename_all = "snake_case" )] /// Object to filter the countries for which the payment method subtype is enabled pub enum AcceptedCountries { /// Only enable the payment method subtype for specific countries #[schema(value_type = Vec<CountryAlpha2>)] EnableOnly(Vec<common_enums::CountryAlpha2>), /// Only disable the payment method subtype for specific countries #[schema(value_type = Vec<CountryAlpha2>)] DisableOnly(Vec<common_enums::CountryAlpha2>), /// Enable the payment method subtype for all countries, in which the processor has the processing capabilities AllAccepted, } #[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)] #[serde( deny_unknown_fields, tag = "type", content = "list", rename_all = "snake_case" )] /// Object to filter the countries for which the payment method subtype is enabled pub enum AcceptedCurrencies { /// Only enable the payment method subtype for specific currencies #[schema(value_type = Vec<Currency>)] EnableOnly(Vec<common_enums::Currency>), /// Only disable the payment method subtype for specific currencies #[schema(value_type = Vec<Currency>)] DisableOnly(Vec<common_enums::Currency>), /// Enable the payment method subtype for all currencies, in which the processor has the processing capabilities AllAccepted, } impl<DB> Queryable<Jsonb, DB> for PaymentMethodsEnabled where DB: Backend, Self: FromSql<Jsonb, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } /// The network tokenization configuration for creating the payment method session #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct NetworkTokenization { /// Enable the network tokenization for payment methods that are created using the payment method session #[schema(value_type = NetworkTokenizationToggle)] pub enable: common_enums::NetworkTokenizationToggle, } /// The Payment Service Provider Configuration for payment methods that are created using the payment method session #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PspTokenization { /// The tokenization type to be applied for the payment method #[schema(value_type = TokenizationType)] pub tokenization_type: common_enums::TokenizationType, /// The merchant connector id to be used for tokenization #[schema(value_type = String)] pub connector_id: common_utils::id_type::MerchantConnectorAccountId, }
crates/common_types/src/payment_methods.rs
common_types::src::payment_methods
2,342
true
// File: crates/common_types/src/refunds.rs // Module: common_types::src::refunds //! Refund related types use common_utils::impl_to_sql_from_sql_json; use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::domain::{AdyenSplitData, XenditSplitSubMerchantData}; #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] /// Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details. pub enum SplitRefund { /// StripeSplitRefundRequest StripeSplitRefund(StripeSplitRefundRequest), /// AdyenSplitRefundRequest AdyenSplitRefund(AdyenSplitData), /// XenditSplitRefundRequest XenditSplitRefund(XenditSplitSubMerchantData), } impl_to_sql_from_sql_json!(SplitRefund); #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(deny_unknown_fields)] /// Charge specific fields for controlling the revert of funds from either platform or connected account for Stripe. Check sub-fields for more details. pub struct StripeSplitRefundRequest { /// Toggle for reverting the application fee that was collected for the payment. /// If set to false, the funds are pulled from the destination account. pub revert_platform_fee: Option<bool>, /// Toggle for reverting the transfer that was made during the charge. /// If set to false, the funds are pulled from the main platform's account. pub revert_transfer: Option<bool>, } impl_to_sql_from_sql_json!(StripeSplitRefundRequest);
crates/common_types/src/refunds.rs
common_types::src::refunds
422
true
// File: crates/common_types/src/payments.rs // Module: common_types::src::payments //! Payment related types use std::collections::HashMap; use common_enums::enums; use common_utils::{ date_time, errors, events, ext_traits::OptionExt, impl_to_sql_from_sql_json, pii, types::MinorUnit, }; use diesel::{ sql_types::{Jsonb, Text}, AsExpression, FromSqlRow, }; use error_stack::{Report, Result, ResultExt}; use euclid::frontend::{ ast::Program, dir::{DirKeyKind, EuclidDirFilter}, }; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::domain::{AdyenSplitData, XenditSplitSubMerchantData}; #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] /// Fee information for Split Payments to be charged on the payment being collected pub enum SplitPaymentsRequest { /// StripeSplitPayment StripeSplitPayment(StripeSplitPaymentRequest), /// AdyenSplitPayment AdyenSplitPayment(AdyenSplitData), /// XenditSplitPayment XenditSplitPayment(XenditSplitRequest), } impl_to_sql_from_sql_json!(SplitPaymentsRequest); #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(deny_unknown_fields)] /// Fee information for Split Payments to be charged on the payment being collected for Stripe pub struct StripeSplitPaymentRequest { /// Stripe's charge type #[schema(value_type = PaymentChargeType, example = "direct")] pub charge_type: enums::PaymentChargeType, /// Platform fees to be collected on the payment #[schema(value_type = i64, example = 6540)] pub application_fees: Option<MinorUnit>, /// Identifier for the reseller's account where the funds were transferred pub transfer_account_id: String, } impl_to_sql_from_sql_json!(StripeSplitPaymentRequest); #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(deny_unknown_fields)] /// Hashmap to store mca_id's with product names pub struct AuthenticationConnectorAccountMap( HashMap<enums::AuthenticationProduct, common_utils::id_type::MerchantConnectorAccountId>, ); impl_to_sql_from_sql_json!(AuthenticationConnectorAccountMap); impl AuthenticationConnectorAccountMap { /// fn to get click to pay connector_account_id pub fn get_click_to_pay_connector_account_id( &self, ) -> Result<common_utils::id_type::MerchantConnectorAccountId, errors::ValidationError> { self.0 .get(&enums::AuthenticationProduct::ClickToPay) .ok_or(errors::ValidationError::MissingRequiredField { field_name: "authentication_product_id.click_to_pay".to_string(), }) .map_err(Report::from) .cloned() } } /// A wrapper type for merchant country codes that provides validation and conversion functionality. /// /// This type stores a country code as a string and provides methods to validate it /// and convert it to a `Country` enum variant. #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Text)] #[serde(deny_unknown_fields)] pub struct MerchantCountryCode(String); impl MerchantCountryCode { /// Returns the country code as a string. pub fn get_country_code(&self) -> String { self.0.clone() } /// Validates the country code and returns a `Country` enum variant. /// /// This method attempts to parse the country code as a u32 and convert it to a `Country` enum variant. /// If the country code is invalid, it returns a `ValidationError` with the appropriate error message. pub fn validate_and_get_country_from_merchant_country_code( &self, ) -> errors::CustomResult<common_enums::Country, errors::ValidationError> { let country_code = self.get_country_code(); let code = country_code .parse::<u32>() .map_err(Report::from) .change_context(errors::ValidationError::IncorrectValueProvided { field_name: "merchant_country_code", }) .attach_printable_lazy(|| { format!("Country code {country_code} is negative or too large") })?; common_enums::Country::from_numeric(code) .map_err(|_| errors::ValidationError::IncorrectValueProvided { field_name: "merchant_country_code", }) .attach_printable_lazy(|| format!("Invalid country code {code}")) } /// Creates a new `MerchantCountryCode` instance from a string. pub fn new(country_code: String) -> Self { Self(country_code) } } impl diesel::serialize::ToSql<Text, diesel::pg::Pg> for MerchantCountryCode { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>, ) -> diesel::serialize::Result { <String as diesel::serialize::ToSql<Text, diesel::pg::Pg>>::to_sql(&self.0, out) } } impl diesel::deserialize::FromSql<Text, diesel::pg::Pg> for MerchantCountryCode { fn from_sql(bytes: diesel::pg::PgValue<'_>) -> diesel::deserialize::Result<Self> { let s = <String as diesel::deserialize::FromSql<Text, diesel::pg::Pg>>::from_sql(bytes)?; Ok(Self(s)) } } #[derive( Serialize, Default, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] /// ConditionalConfigs pub struct ConditionalConfigs { /// Override 3DS pub override_3ds: Option<common_enums::AuthenticationType>, } impl EuclidDirFilter for ConditionalConfigs { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::PaymentMethod, DirKeyKind::CardType, DirKeyKind::CardNetwork, DirKeyKind::MetaData, DirKeyKind::PaymentAmount, DirKeyKind::PaymentCurrency, DirKeyKind::CaptureMethod, DirKeyKind::BillingCountry, DirKeyKind::BusinessCountry, ]; } impl_to_sql_from_sql_json!(ConditionalConfigs); /// 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. #[derive( Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, AsExpression, ToSchema, )] #[serde(deny_unknown_fields)] #[diesel(sql_type = Jsonb)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } impl_to_sql_from_sql_json!(CustomerAcceptance); impl CustomerAcceptance { /// Get the IP address pub fn get_ip_address(&self) -> Option<String> { self.online .as_ref() .and_then(|data| data.ip_address.as_ref().map(|ip| ip.peek().to_owned())) } /// Get the User Agent pub fn get_user_agent(&self) -> Option<String> { self.online.as_ref().map(|data| data.user_agent.clone()) } /// Get when the customer acceptance was provided pub fn get_accepted_at(&self) -> PrimitiveDateTime { self.accepted_at.unwrap_or_else(date_time::now) } } impl masking::SerializableSecret for CustomerAcceptance {} #[derive( Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, Copy, ToSchema, )] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { /// Online Online, /// Offline #[default] Offline, } #[derive( Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, AsExpression, Clone, ToSchema, )] #[serde(deny_unknown_fields)] /// Details of online mandate #[diesel(sql_type = Jsonb)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } impl_to_sql_from_sql_json!(OnlineMandate); #[derive(Serialize, Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)] #[diesel(sql_type = Jsonb)] /// DecisionManagerRecord pub struct DecisionManagerRecord { /// Name of the Decision Manager pub name: String, /// Program to be executed pub program: Program<ConditionalConfigs>, /// Created at timestamp pub created_at: i64, } impl events::ApiEventMetric for DecisionManagerRecord { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } impl_to_sql_from_sql_json!(DecisionManagerRecord); /// DecisionManagerResponse pub type DecisionManagerResponse = DecisionManagerRecord; /// Fee information to be charged on the payment being collected via Stripe #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(deny_unknown_fields)] pub struct StripeChargeResponseData { /// Identifier for charge created for the payment pub charge_id: Option<String>, /// Type of charge (connector specific) #[schema(value_type = PaymentChargeType, example = "direct")] pub charge_type: enums::PaymentChargeType, /// Platform fees collected on the payment #[schema(value_type = i64, example = 6540)] pub application_fees: Option<MinorUnit>, /// Identifier for the reseller's account where the funds were transferred pub transfer_account_id: String, } impl_to_sql_from_sql_json!(StripeChargeResponseData); /// Charge Information #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] pub enum ConnectorChargeResponseData { /// StripeChargeResponseData StripeSplitPayment(StripeChargeResponseData), /// AdyenChargeResponseData AdyenSplitPayment(AdyenSplitData), /// XenditChargeResponseData XenditSplitPayment(XenditChargeResponseData), } impl_to_sql_from_sql_json!(ConnectorChargeResponseData); /// Fee information to be charged on the payment being collected via xendit #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(deny_unknown_fields)] pub struct XenditSplitRoute { /// Amount of payments to be split pub flat_amount: Option<MinorUnit>, /// Amount of payments to be split, using a percent rate as unit pub percent_amount: Option<i64>, /// Currency code #[schema(value_type = Currency, example = "USD")] pub currency: enums::Currency, /// ID of the destination account where the amount will be routed to pub destination_account_id: String, /// Reference ID which acts as an identifier of the route itself pub reference_id: String, } impl_to_sql_from_sql_json!(XenditSplitRoute); /// Fee information to be charged on the payment being collected via xendit #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(deny_unknown_fields)] pub struct XenditMultipleSplitRequest { /// Name to identify split rule. Not required to be unique. Typically based on transaction and/or sub-merchant types. pub name: String, /// Description to identify fee rule pub description: String, /// The sub-account user-id that you want to make this transaction for. pub for_user_id: Option<String>, /// Array of objects that define how the platform wants to route the fees and to which accounts. pub routes: Vec<XenditSplitRoute>, } impl_to_sql_from_sql_json!(XenditMultipleSplitRequest); /// Xendit Charge Request #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] pub enum XenditSplitRequest { /// Split Between Multiple Accounts MultipleSplits(XenditMultipleSplitRequest), /// Collect Fee for Single Account SingleSplit(XenditSplitSubMerchantData), } impl_to_sql_from_sql_json!(XenditSplitRequest); /// Charge Information #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] pub enum XenditChargeResponseData { /// Split Between Multiple Accounts MultipleSplits(XenditMultipleSplitResponse), /// Collect Fee for Single Account SingleSplit(XenditSplitSubMerchantData), } impl_to_sql_from_sql_json!(XenditChargeResponseData); /// Fee information charged on the payment being collected via xendit #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(deny_unknown_fields)] pub struct XenditMultipleSplitResponse { /// Identifier for split rule created for the payment pub split_rule_id: String, /// The sub-account user-id that you want to make this transaction for. pub for_user_id: Option<String>, /// Name to identify split rule. Not required to be unique. Typically based on transaction and/or sub-merchant types. pub name: String, /// Description to identify fee rule pub description: String, /// Array of objects that define how the platform wants to route the fees and to which accounts. pub routes: Vec<XenditSplitRoute>, } impl_to_sql_from_sql_json!(XenditMultipleSplitResponse); #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] /// This enum is used to represent the Gpay payment data, which can either be encrypted or decrypted. pub enum GpayTokenizationData { /// This variant contains the decrypted Gpay payment data as a structured object. Decrypted(GPayPredecryptData), /// This variant contains the encrypted Gpay payment data as a string. Encrypted(GpayEcryptedTokenizationData), } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] /// This struct represents the encrypted Gpay payment data pub struct GpayEcryptedTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] /// This struct represents the decrypted Google Pay payment data pub struct GPayPredecryptData { /// The card's expiry month #[schema(value_type = String)] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String)] pub card_exp_year: Secret<String>, /// The Primary Account Number (PAN) of the card #[schema(value_type = String, example = "4242424242424242")] pub application_primary_account_number: cards::CardNumber, /// Cryptogram generated by the Network #[schema(value_type = String, example = "AgAAAAAAAIR8CQrXcIhbQAAAAAA")] pub cryptogram: Option<Secret<String>>, /// Electronic Commerce Indicator #[schema(value_type = String, example = "07")] pub eci_indicator: Option<String>, } impl GpayTokenizationData { /// Get the encrypted Google Pay payment data, returning an error if it does not exist pub fn get_encrypted_google_pay_payment_data_mandatory( &self, ) -> Result<&GpayEcryptedTokenizationData, errors::ValidationError> { match self { Self::Encrypted(encrypted_data) => Ok(encrypted_data), Self::Decrypted(_) => Err(errors::ValidationError::InvalidValue { message: "Encrypted Google Pay payment data is mandatory".to_string(), } .into()), } } /// Get the token from Google Pay tokenization data /// Returns the token string if encrypted data exists, otherwise returns an error pub fn get_encrypted_google_pay_token(&self) -> Result<String, errors::ValidationError> { Ok(self .get_encrypted_google_pay_payment_data_mandatory()? .token .clone()) } /// Get the token type from Google Pay tokenization data /// Returns the token_type string if encrypted data exists, otherwise returns an error pub fn get_encrypted_token_type(&self) -> Result<String, errors::ValidationError> { Ok(self .get_encrypted_google_pay_payment_data_mandatory()? .token_type .clone()) } } impl GPayPredecryptData { /// Get the four-digit expiration year from the Google Pay pre-decrypt data pub fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> { let mut year = self.card_exp_year.peek().clone(); // If it's a 2-digit year, convert to 4-digit if year.len() == 2 { year = format!("20{year}"); } else if year.len() != 4 { return Err(errors::ValidationError::InvalidValue { message: format!( "Invalid expiry year length: {}. Must be 2 or 4 digits", year.len() ), } .into()); } Ok(Secret::new(year)) } /// Get the 2-digit expiration year from the Google Pay pre-decrypt data pub fn get_two_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> { let binding = self.card_exp_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ValidationError::InvalidValue { message: "Invalid two-digit year".to_string(), })? .to_string(), )) } /// Get the expiry date in MMYY format from the Google Pay pre-decrypt data pub fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ValidationError> { let year = self.get_two_digit_expiry_year()?.expose(); let month = self.get_expiry_month()?.clone().expose(); Ok(Secret::new(format!("{month}{year}"))) } /// Get the expiration month from the Google Pay pre-decrypt data pub fn get_expiry_month(&self) -> Result<Secret<String>, errors::ValidationError> { let month_str = self.card_exp_month.peek(); let month = month_str .parse::<u8>() .map_err(|_| errors::ValidationError::InvalidValue { message: format!("Failed to parse expiry month: {month_str}"), })?; if !(1..=12).contains(&month) { return Err(errors::ValidationError::InvalidValue { message: format!("Invalid expiry month: {month}. Must be between 1 and 12"), } .into()); } Ok(self.card_exp_month.clone()) } } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] /// This enum is used to represent the Apple Pay payment data, which can either be encrypted or decrypted. pub enum ApplePayPaymentData { /// This variant contains the decrypted Apple Pay payment data as a structured object. Decrypted(ApplePayPredecryptData), /// This variant contains the encrypted Apple Pay payment data as a string. Encrypted(String), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] /// This struct represents the decrypted Apple Pay payment data pub struct ApplePayPredecryptData { /// The primary account number #[schema(value_type = String, example = "4242424242424242")] pub application_primary_account_number: cards::CardNumber, /// The application expiration date (PAN expiry month) #[schema(value_type = String, example = "12")] pub application_expiration_month: Secret<String>, /// The application expiration date (PAN expiry year) #[schema(value_type = String, example = "24")] pub application_expiration_year: Secret<String>, /// The payment data, which contains the cryptogram and ECI indicator #[schema(value_type = ApplePayCryptogramData)] pub payment_data: ApplePayCryptogramData, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] /// This struct represents the cryptogram data for Apple Pay transactions pub struct ApplePayCryptogramData { /// The online payment cryptogram #[schema(value_type = String, example = "A1B2C3D4E5F6G7H8")] pub online_payment_cryptogram: Secret<String>, /// The ECI (Electronic Commerce Indicator) value #[schema(value_type = String, example = "05")] pub eci_indicator: Option<String>, } impl ApplePayPaymentData { /// Get the encrypted Apple Pay payment data if it exists pub fn get_encrypted_apple_pay_payment_data_optional(&self) -> Option<&String> { match self { Self::Encrypted(encrypted_data) => Some(encrypted_data), Self::Decrypted(_) => None, } } /// Get the decrypted Apple Pay payment data if it exists pub fn get_decrypted_apple_pay_payment_data_optional(&self) -> Option<&ApplePayPredecryptData> { match self { Self::Encrypted(_) => None, Self::Decrypted(decrypted_data) => Some(decrypted_data), } } /// Get the encrypted Apple Pay payment data, returning an error if it does not exist pub fn get_encrypted_apple_pay_payment_data_mandatory( &self, ) -> Result<&String, errors::ValidationError> { self.get_encrypted_apple_pay_payment_data_optional() .get_required_value("Encrypted Apple Pay payment data") .attach_printable("Encrypted Apple Pay payment data is mandatory") } /// Get the decrypted Apple Pay payment data, returning an error if it does not exist pub fn get_decrypted_apple_pay_payment_data_mandatory( &self, ) -> Result<&ApplePayPredecryptData, errors::ValidationError> { self.get_decrypted_apple_pay_payment_data_optional() .get_required_value("Decrypted Apple Pay payment data") .attach_printable("Decrypted Apple Pay payment data is mandatory") } } impl ApplePayPredecryptData { /// Get the four-digit expiration year from the Apple Pay pre-decrypt data pub fn get_two_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> { let binding = self.application_expiration_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ValidationError::InvalidValue { message: "Invalid two-digit year".to_string(), })? .to_string(), )) } /// Get the four-digit expiration year from the Apple Pay pre-decrypt data pub fn get_four_digit_expiry_year(&self) -> Secret<String> { let mut year = self.application_expiration_year.peek().clone(); if year.len() == 2 { year = format!("20{year}"); } Secret::new(year) } /// Get the expiration month from the Apple Pay pre-decrypt data pub fn get_expiry_month(&self) -> Result<Secret<String>, errors::ValidationError> { let month_str = self.application_expiration_month.peek(); let month = month_str .parse::<u8>() .map_err(|_| errors::ValidationError::InvalidValue { message: format!("Failed to parse expiry month: {month_str}"), })?; if !(1..=12).contains(&month) { return Err(errors::ValidationError::InvalidValue { message: format!("Invalid expiry month: {month}. Must be between 1 and 12"), } .into()); } Ok(self.application_expiration_month.clone()) } /// Get the expiry date in MMYY format from the Apple Pay pre-decrypt data pub fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ValidationError> { let year = self.get_two_digit_expiry_year()?.expose(); let month = self.get_expiry_month()?.expose(); Ok(Secret::new(format!("{month}{year}"))) } /// Get the expiry date in YYMM format from the Apple Pay pre-decrypt data pub fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ValidationError> { let year = self.get_two_digit_expiry_year()?.expose(); let month = self.get_expiry_month()?.expose(); Ok(Secret::new(format!("{year}{month}"))) } } /// type of action that needs to taken after consuming recovery payload #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RecoveryAction { /// Stops the process tracker and update the payment intent. CancelInvoice, /// Records the external transaction against payment intent. ScheduleFailedPayment, /// Records the external payment and stops the internal process tracker. SuccessPaymentExternal, /// Pending payments from billing processor. PendingPayment, /// No action required. NoAction, /// Invalid event has been received. InvalidAction, }
crates/common_types/src/payments.rs
common_types::src::payments
6,017
true
// File: crates/common_types/src/lib.rs // Module: common_types::src::lib //! Types shared across the request/response types and database types #![warn(missing_docs, missing_debug_implementations)] pub mod consts; pub mod customers; pub mod domain; pub mod payment_methods; pub mod payments; /// types that are wrappers around primitive types pub mod primitive_wrappers; pub mod refunds; /// types for three ds decision rule engine pub mod three_ds_decision_rule_engine; ///types for callback mapper pub mod callback_mapper;
crates/common_types/src/lib.rs
common_types::src::lib
112
true
// File: crates/common_types/src/domain.rs // Module: common_types::src::domain //! Common types use std::collections::HashMap; use common_enums::enums; use common_utils::{impl_to_sql_from_sql_json, types::MinorUnit}; use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow}; #[cfg(feature = "v2")] use masking::Secret; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(deny_unknown_fields)] /// Fee information for Split Payments to be charged on the payment being collected for Adyen pub struct AdyenSplitData { /// The store identifier pub store: Option<String>, /// Data for the split items pub split_items: Vec<AdyenSplitItem>, } impl_to_sql_from_sql_json!(AdyenSplitData); #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(deny_unknown_fields)] /// Data for the split items pub struct AdyenSplitItem { /// The amount of the split item #[schema(value_type = i64, example = 6540)] pub amount: Option<MinorUnit>, /// Defines type of split item #[schema(value_type = AdyenSplitType, example = "BalanceAccount")] pub split_type: enums::AdyenSplitType, /// The unique identifier of the account to which the split amount is allocated. pub account: Option<String>, /// Unique Identifier for the split item pub reference: String, /// Description for the part of the payment that will be allocated to the specified account. pub description: Option<String>, } impl_to_sql_from_sql_json!(AdyenSplitItem); /// Fee information to be charged on the payment being collected for sub-merchant via xendit #[derive( Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(deny_unknown_fields)] pub struct XenditSplitSubMerchantData { /// The sub-account user-id that you want to make this transaction for. pub for_user_id: String, } impl_to_sql_from_sql_json!(XenditSplitSubMerchantData); /// Acquirer configuration #[derive(Clone, Debug, Deserialize, ToSchema, Serialize, PartialEq)] pub struct AcquirerConfig { /// The merchant id assigned by the acquirer #[schema(value_type= String,example = "M123456789")] pub acquirer_assigned_merchant_id: String, /// merchant name #[schema(value_type= String,example = "NewAge Retailer")] pub merchant_name: String, /// Network provider #[schema(value_type= String,example = "VISA")] pub network: common_enums::CardNetwork, /// Acquirer bin #[schema(value_type= String,example = "456789")] pub acquirer_bin: String, /// Acquirer ica provided by acquirer #[schema(value_type= Option<String>,example = "401288")] pub acquirer_ica: Option<String>, /// Fraud rate for the particular acquirer configuration #[schema(value_type= String,example = "0.01")] pub acquirer_fraud_rate: f64, } #[derive(Serialize, Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)] #[diesel(sql_type = Jsonb)] /// Acquirer configs pub struct AcquirerConfigMap(pub HashMap<common_utils::id_type::ProfileAcquirerId, AcquirerConfig>); impl_to_sql_from_sql_json!(AcquirerConfigMap); /// Merchant connector details #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct MerchantConnectorAuthDetails { /// The connector used for the payment #[schema(value_type = Connector)] pub connector_name: common_enums::connector_enums::Connector, /// The merchant connector credentials used for the payment #[schema(value_type = Object, example = r#"{ "merchant_connector_creds": { "auth_type": "HeaderKey", "api_key":"sk_test_xxxxxexamplexxxxxx12345" }, }"#)] pub merchant_connector_creds: common_utils::pii::SecretSerdeValue, } /// Connector Response Data that are required to be populated in response, but not persisted in DB. #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct ConnectorResponseData { /// Stringified connector raw response body pub raw_connector_response: Option<Secret<String>>, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, AsExpression, ToSchema)] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] /// Contains the data relevant to the specified GSM feature, if applicable. /// For example, if the `feature` is `Retry`, this will include configuration /// details specific to the retry behavior. pub enum GsmFeatureData { /// Represents the data associated with a retry feature in GSM. Retry(RetryFeatureData), } /// Represents the data associated with a retry feature in GSM. #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, AsExpression, ToSchema)] #[diesel(sql_type = Jsonb)] pub struct RetryFeatureData { /// indicates if step_up retry is possible pub step_up_possible: bool, /// indicates if retry with pan is possible pub clear_pan_possible: bool, /// indicates if retry with alternate network possible pub alternate_network_possible: bool, /// decision to be taken for auto retries flow #[schema(value_type = GsmDecision)] pub decision: common_enums::GsmDecision, } impl_to_sql_from_sql_json!(GsmFeatureData); impl_to_sql_from_sql_json!(RetryFeatureData); impl GsmFeatureData { /// Retrieves the retry feature data if it exists. pub fn get_retry_feature_data(&self) -> Option<RetryFeatureData> { match self { Self::Retry(data) => Some(data.clone()), } } /// Retrieves the decision from the retry feature data. pub fn get_decision(&self) -> common_enums::GsmDecision { match self { Self::Retry(data) => data.decision, } } } /// Implementation of methods for `RetryFeatureData` impl RetryFeatureData { /// Checks if step-up retry is possible. pub fn is_step_up_possible(&self) -> bool { self.step_up_possible } /// Checks if retry with PAN is possible. pub fn is_clear_pan_possible(&self) -> bool { self.clear_pan_possible } /// Checks if retry with alternate network is possible. pub fn is_alternate_network_possible(&self) -> bool { self.alternate_network_possible } /// Retrieves the decision to be taken for auto retries flow. pub fn get_decision(&self) -> common_enums::GsmDecision { self.decision } }
crates/common_types/src/domain.rs
common_types::src::domain
1,571
true
// File: crates/common_types/src/primitive_wrappers.rs // Module: common_types::src::primitive_wrappers pub use bool_wrappers::*; pub use safe_string::*; pub use u32_wrappers::*; mod bool_wrappers { use std::ops::Deref; use serde::{Deserialize, Serialize}; /// Bool that represents if Extended Authorization is Applied or not #[derive( Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct ExtendedAuthorizationAppliedBool(bool); impl Deref for ExtendedAuthorizationAppliedBool { type Target = bool; fn deref(&self) -> &Self::Target { &self.0 } } impl From<bool> for ExtendedAuthorizationAppliedBool { fn from(value: bool) -> Self { Self(value) } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } /// Bool that represents if Extended Authorization is Requested or not #[derive( Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct RequestExtendedAuthorizationBool(bool); impl Deref for RequestExtendedAuthorizationBool { type Target = bool; fn deref(&self) -> &Self::Target { &self.0 } } impl From<bool> for RequestExtendedAuthorizationBool { fn from(value: bool) -> Self { Self(value) } } impl RequestExtendedAuthorizationBool { /// returns the inner bool value pub fn is_true(&self) -> bool { self.0 } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } /// Bool that represents if Enable Partial Authorization is Requested or not #[derive( Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct EnablePartialAuthorizationBool(bool); impl Deref for EnablePartialAuthorizationBool { type Target = bool; fn deref(&self) -> &Self::Target { &self.0 } } impl From<bool> for EnablePartialAuthorizationBool { fn from(value: bool) -> Self { Self(value) } } impl EnablePartialAuthorizationBool { /// returns the inner bool value pub fn is_true(&self) -> bool { self.0 } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for EnablePartialAuthorizationBool where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for EnablePartialAuthorizationBool where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } /// Bool that represents if Extended Authorization is always Requested or not #[derive( Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct AlwaysRequestExtendedAuthorization(bool); impl Deref for AlwaysRequestExtendedAuthorization { type Target = bool; fn deref(&self) -> &Self::Target { &self.0 } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for AlwaysRequestExtendedAuthorization where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for AlwaysRequestExtendedAuthorization where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } /// Bool that represents if Cvv should be collected during payment or not. Default is true #[derive( Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct ShouldCollectCvvDuringPayment(bool); impl Deref for ShouldCollectCvvDuringPayment { type Target = bool; fn deref(&self) -> &Self::Target { &self.0 } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } impl Default for ShouldCollectCvvDuringPayment { /// Default for `ShouldCollectCvvDuringPayment` is `true` fn default() -> Self { Self(true) } } /// Bool that represents if overcapture should always be requested #[derive( Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct AlwaysEnableOvercaptureBool(bool); impl AlwaysEnableOvercaptureBool { /// returns the inner bool value pub fn is_true(&self) -> bool { self.0 } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for AlwaysEnableOvercaptureBool where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for AlwaysEnableOvercaptureBool where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } impl Default for AlwaysEnableOvercaptureBool { /// Default for `AlwaysEnableOvercaptureBool` is `false` fn default() -> Self { Self(false) } } /// Bool that represents if overcapture is requested for this payment #[derive( Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct EnableOvercaptureBool(bool); impl From<bool> for EnableOvercaptureBool { fn from(value: bool) -> Self { Self(value) } } impl From<AlwaysEnableOvercaptureBool> for EnableOvercaptureBool { fn from(item: AlwaysEnableOvercaptureBool) -> Self { Self(item.is_true()) } } impl Deref for EnableOvercaptureBool { type Target = bool; fn deref(&self) -> &Self::Target { &self.0 } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for EnableOvercaptureBool where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for EnableOvercaptureBool where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } impl Default for EnableOvercaptureBool { /// Default for `EnableOvercaptureBool` is `false` fn default() -> Self { Self(false) } } /// Bool that represents if overcapture is applied for a payment by the connector #[derive( Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct OvercaptureEnabledBool(bool); impl OvercaptureEnabledBool { /// Creates a new instance of `OvercaptureEnabledBool` pub fn new(value: bool) -> Self { Self(value) } } impl Default for OvercaptureEnabledBool { /// Default for `OvercaptureEnabledBool` is `false` fn default() -> Self { Self(false) } } impl Deref for OvercaptureEnabledBool { type Target = bool; fn deref(&self) -> &Self::Target { &self.0 } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for OvercaptureEnabledBool where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for OvercaptureEnabledBool where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } } mod u32_wrappers { use std::ops::Deref; use serde::{de::Error, Deserialize, Serialize}; use crate::consts::{ DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS, MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS, }; /// Time interval in hours for polling disputes #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, diesel::expression::AsExpression)] #[diesel(sql_type = diesel::sql_types::Integer)] pub struct DisputePollingIntervalInHours(i32); impl Deref for DisputePollingIntervalInHours { type Target = i32; fn deref(&self) -> &Self::Target { &self.0 } } impl<'de> Deserialize<'de> for DisputePollingIntervalInHours { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let val = i32::deserialize(deserializer)?; if val < 0 { Err(D::Error::custom( "DisputePollingIntervalInHours cannot be negative", )) } else if val > MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS { Err(D::Error::custom( "DisputePollingIntervalInHours exceeds the maximum allowed value of 24", )) } else { Ok(Self(val)) } } } impl diesel::deserialize::FromSql<diesel::sql_types::Integer, diesel::pg::Pg> for DisputePollingIntervalInHours { fn from_sql(value: diesel::pg::PgValue<'_>) -> diesel::deserialize::Result<Self> { i32::from_sql(value).map(Self) } } impl diesel::serialize::ToSql<diesel::sql_types::Integer, diesel::pg::Pg> for DisputePollingIntervalInHours { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>, ) -> diesel::serialize::Result { <i32 as diesel::serialize::ToSql<diesel::sql_types::Integer, diesel::pg::Pg>>::to_sql( &self.0, out, ) } } impl Default for DisputePollingIntervalInHours { /// Default for `DisputePollingIntervalInHours` is `24` fn default() -> Self { Self(DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS) } } } /// Safe string wrapper that validates input against XSS attacks mod safe_string { use std::ops::Deref; use common_utils::validation::contains_potential_xss_or_sqli; use masking::SerializableSecret; use serde::{de::Error, Deserialize, Serialize}; /// String wrapper that prevents XSS and SQLi attacks #[derive(Clone, Debug, Eq, PartialEq, Default)] pub struct SafeString(String); impl SafeString { /// Creates a new SafeString after XSS and SQL injection validation pub fn new(value: String) -> Result<Self, String> { if contains_potential_xss_or_sqli(&value) { return Err("Input contains potentially malicious content".into()); } Ok(Self(value)) } /// Creates a SafeString from a string slice pub fn from_string_slice(value: &str) -> Result<Self, String> { Self::new(value.to_string()) } /// Returns the inner string as a string slice pub fn as_str(&self) -> &str { &self.0 } /// Consumes self and returns the inner String pub fn into_inner(self) -> String { self.0 } /// Returns true if the string is empty pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Returns the length of the string pub fn len(&self) -> usize { self.0.len() } } impl Deref for SafeString { type Target = String; fn deref(&self) -> &Self::Target { &self.0 } } // Custom serialization and deserialization impl Serialize for SafeString { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.serialize(serializer) } } impl<'de> Deserialize<'de> for SafeString { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let value = String::deserialize(deserializer)?; Self::new(value).map_err(D::Error::custom) } } // Implement SerializableSecret for SafeString to work with Secret<SafeString> impl SerializableSecret for SafeString {} // Diesel implementations for database operations impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for SafeString where DB: diesel::backend::Backend, String: diesel::serialize::ToSql<diesel::sql_types::Text, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for SafeString where DB: diesel::backend::Backend, String: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { String::from_sql(value).map(Self) } } }
crates/common_types/src/primitive_wrappers.rs
common_types::src::primitive_wrappers
4,273
true
// File: crates/common_types/src/three_ds_decision_rule_engine.rs // Module: common_types::src::three_ds_decision_rule_engine use common_utils::impl_to_sql_from_sql_json; use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow}; use euclid::frontend::dir::{DirKeyKind, EuclidDirFilter}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; /// Enum representing the possible outcomes of the 3DS Decision Rule Engine. #[derive( Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, Default, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] pub enum ThreeDSDecision { /// No 3DS authentication required #[default] NoThreeDs, /// Mandate 3DS Challenge ChallengeRequested, /// Prefer 3DS Challenge ChallengePreferred, /// Request 3DS Exemption, Type: Transaction Risk Analysis (TRA) ThreeDsExemptionRequestedTra, /// Request 3DS Exemption, Type: Low Value Transaction ThreeDsExemptionRequestedLowValue, /// No challenge requested by merchant (e.g., delegated authentication) IssuerThreeDsExemptionRequested, } impl_to_sql_from_sql_json!(ThreeDSDecision); impl ThreeDSDecision { /// Checks if the decision is to mandate a 3DS challenge pub fn should_force_3ds_challenge(self) -> bool { matches!(self, Self::ChallengeRequested) } } /// Struct representing the output configuration for the 3DS Decision Rule Engine. #[derive( Serialize, Default, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct ThreeDSDecisionRule { /// The decided 3DS action based on the rules pub decision: ThreeDSDecision, } impl ThreeDSDecisionRule { /// Returns the decision pub fn get_decision(&self) -> ThreeDSDecision { self.decision } } impl_to_sql_from_sql_json!(ThreeDSDecisionRule); impl EuclidDirFilter for ThreeDSDecisionRule { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::CardNetwork, DirKeyKind::PaymentAmount, DirKeyKind::PaymentCurrency, DirKeyKind::IssuerName, DirKeyKind::IssuerCountry, DirKeyKind::CustomerDevicePlatform, DirKeyKind::CustomerDeviceType, DirKeyKind::CustomerDeviceDisplaySize, DirKeyKind::AcquirerCountry, DirKeyKind::AcquirerFraudRate, ]; }
crates/common_types/src/three_ds_decision_rule_engine.rs
common_types::src::three_ds_decision_rule_engine
586
true
// File: crates/common_types/src/customers.rs // Module: common_types::src::customers //! Customer related types /// HashMap containing MerchantConnectorAccountId and corresponding customer id #[cfg(feature = "v2")] #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] #[serde(transparent)] pub struct ConnectorCustomerMap( std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>, ); #[cfg(feature = "v2")] impl ConnectorCustomerMap { /// Creates a new `ConnectorCustomerMap` from a HashMap pub fn new( map: std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>, ) -> Self { Self(map) } } #[cfg(feature = "v2")] common_utils::impl_to_sql_from_sql_json!(ConnectorCustomerMap); #[cfg(feature = "v2")] impl std::ops::Deref for ConnectorCustomerMap { type Target = std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>; fn deref(&self) -> &Self::Target { &self.0 } } #[cfg(feature = "v2")] impl std::ops::DerefMut for ConnectorCustomerMap { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
crates/common_types/src/customers.rs
common_types::src::customers
310
true
// File: crates/smithy-core/src/types.rs // Module: smithy-core::src::types // crates/smithy-core/types.rs use std::collections::HashMap; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SmithyModel { pub namespace: String, pub shapes: HashMap<String, SmithyShape>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type")] pub enum SmithyShape { #[serde(rename = "structure")] Structure { members: HashMap<String, SmithyMember>, #[serde(skip_serializing_if = "Option::is_none")] documentation: Option<String>, #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "string")] String { #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "integer")] Integer { #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "long")] Long { #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "boolean")] Boolean { #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "list")] List { member: Box<SmithyMember>, #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "union")] Union { members: HashMap<String, SmithyMember>, #[serde(skip_serializing_if = "Option::is_none")] documentation: Option<String>, #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, #[serde(rename = "enum")] Enum { values: HashMap<String, SmithyEnumValue>, #[serde(skip_serializing_if = "Option::is_none")] documentation: Option<String>, #[serde(skip_serializing_if = "Vec::is_empty")] traits: Vec<SmithyTrait>, }, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SmithyMember { pub target: String, #[serde(skip_serializing_if = "Option::is_none")] pub documentation: Option<String>, #[serde(skip_serializing_if = "Vec::is_empty")] pub traits: Vec<SmithyTrait>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SmithyEnumValue { pub name: String, #[serde(skip_serializing_if = "Option::is_none")] pub documentation: Option<String>, pub is_default: bool, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "trait")] pub enum SmithyTrait { #[serde(rename = "smithy.api#pattern")] Pattern { pattern: String }, #[serde(rename = "smithy.api#range")] Range { min: Option<i64>, max: Option<i64> }, #[serde(rename = "smithy.api#required")] Required, #[serde(rename = "smithy.api#documentation")] Documentation { documentation: String }, #[serde(rename = "smithy.api#length")] Length { min: Option<u64>, max: Option<u64> }, #[serde(rename = "smithy.api#httpLabel")] HttpLabel, #[serde(rename = "smithy.api#httpQuery")] HttpQuery { name: String }, #[serde(rename = "smithy.api#mixin")] Mixin, } #[derive(Debug, Clone)] pub struct SmithyField { pub name: String, pub value_type: String, pub constraints: Vec<SmithyConstraint>, pub documentation: Option<String>, pub optional: bool, pub flatten: bool, } #[derive(Debug, Clone)] pub struct SmithyEnumVariant { pub name: String, pub fields: Vec<SmithyField>, pub constraints: Vec<SmithyConstraint>, pub documentation: Option<String>, } #[derive(Debug, Clone)] pub enum SmithyConstraint { Pattern(String), Range(Option<i64>, Option<i64>), Length(Option<u64>, Option<u64>), Required, HttpLabel, HttpQuery(String), } pub trait SmithyModelGenerator { fn generate_smithy_model() -> SmithyModel; } // Helper functions moved from the proc-macro crate to be accessible by it. pub fn resolve_type_and_generate_shapes( value_type: &str, shapes: &mut HashMap<String, SmithyShape>, ) -> Result<(String, HashMap<String, SmithyShape>), syn::Error> { let value_type = value_type.trim(); let value_type_span = proc_macro2::Span::call_site(); let mut generated_shapes = HashMap::new(); let target_type = match value_type { "String" | "str" => "smithy.api#String".to_string(), "i8" | "i16" | "i32" | "u8" | "u16" | "u32" => "smithy.api#Integer".to_string(), "i64" | "u64" | "isize" | "usize" => "smithy.api#Long".to_string(), "f32" => "smithy.api#Float".to_string(), "f64" => "smithy.api#Double".to_string(), "bool" => "smithy.api#Boolean".to_string(), "PrimitiveDateTime" | "time::PrimitiveDateTime" => "smithy.api#Timestamp".to_string(), "Amount" | "MinorUnit" => "smithy.api#Long".to_string(), "serde_json::Value" | "Value" | "Object" => "smithy.api#Document".to_string(), "Url" | "url::Url" => "smithy.api#String".to_string(), vt if vt.starts_with("Option<") && vt.ends_with('>') => { let inner_type = extract_generic_inner_type(vt, "Option") .map_err(|e| syn::Error::new(value_type_span, e))?; let (resolved_type, new_shapes) = resolve_type_and_generate_shapes(inner_type, shapes)?; generated_shapes.extend(new_shapes); resolved_type } vt if vt.starts_with("Vec<") && vt.ends_with('>') => { let inner_type = extract_generic_inner_type(vt, "Vec") .map_err(|e| syn::Error::new(value_type_span, e))?; let (inner_smithy_type, new_shapes) = resolve_type_and_generate_shapes(inner_type, shapes)?; generated_shapes.extend(new_shapes); let list_shape_name = format!( "{}List", inner_smithy_type .split("::") .last() .unwrap_or(&inner_smithy_type) .split('#') .next_back() .unwrap_or(&inner_smithy_type) ); if !shapes.contains_key(&list_shape_name) && !generated_shapes.contains_key(&list_shape_name) { let list_shape = SmithyShape::List { member: Box::new(SmithyMember { target: inner_smithy_type, documentation: None, traits: vec![], }), traits: vec![], }; generated_shapes.insert(list_shape_name.clone(), list_shape); } list_shape_name } vt if vt.starts_with("Box<") && vt.ends_with('>') => { let inner_type = extract_generic_inner_type(vt, "Box") .map_err(|e| syn::Error::new(value_type_span, e))?; let (resolved_type, new_shapes) = resolve_type_and_generate_shapes(inner_type, shapes)?; generated_shapes.extend(new_shapes); resolved_type } vt if vt.starts_with("Secret<") && vt.ends_with('>') => { let inner_type = extract_generic_inner_type(vt, "Secret") .map_err(|e| syn::Error::new(value_type_span, e))?; let (resolved_type, new_shapes) = resolve_type_and_generate_shapes(inner_type, shapes)?; generated_shapes.extend(new_shapes); resolved_type } vt if vt.starts_with("HashMap<") && vt.ends_with('>') => { let inner_types = extract_generic_inner_type(vt, "HashMap") .map_err(|e| syn::Error::new(value_type_span, e))?; let (key_type, value_type) = parse_map_types(inner_types).map_err(|e| syn::Error::new(value_type_span, e))?; let (key_smithy_type, key_shapes) = resolve_type_and_generate_shapes(key_type, shapes)?; generated_shapes.extend(key_shapes); let (value_smithy_type, value_shapes) = resolve_type_and_generate_shapes(value_type, shapes)?; generated_shapes.extend(value_shapes); format!( "smithy.api#Map<key: {}, value: {}>", key_smithy_type, value_smithy_type ) } vt if vt.starts_with("BTreeMap<") && vt.ends_with('>') => { let inner_types = extract_generic_inner_type(vt, "BTreeMap") .map_err(|e| syn::Error::new(value_type_span, e))?; let (key_type, value_type) = parse_map_types(inner_types).map_err(|e| syn::Error::new(value_type_span, e))?; let (key_smithy_type, key_shapes) = resolve_type_and_generate_shapes(key_type, shapes)?; generated_shapes.extend(key_shapes); let (value_smithy_type, value_shapes) = resolve_type_and_generate_shapes(value_type, shapes)?; generated_shapes.extend(value_shapes); format!( "smithy.api#Map<key: {}, value: {}>", key_smithy_type, value_smithy_type ) } _ => { if value_type.contains("::") { value_type.replace("::", ".") } else { value_type.to_string() } } }; Ok((target_type, generated_shapes)) } fn extract_generic_inner_type<'a>(full_type: &'a str, wrapper: &str) -> Result<&'a str, String> { let expected_start = format!("{}<", wrapper); if !full_type.starts_with(&expected_start) || !full_type.ends_with('>') { return Err(format!("Invalid {} type format: {}", wrapper, full_type)); } let start_idx = expected_start.len(); let end_idx = full_type.len() - 1; if start_idx >= end_idx { return Err(format!("Empty {} type: {}", wrapper, full_type)); } if start_idx >= full_type.len() || end_idx > full_type.len() { return Err(format!( "Invalid index bounds for {} type: {}", wrapper, full_type )); } Ok(full_type .get(start_idx..end_idx) .ok_or_else(|| { format!( "Failed to extract inner type from {}: {}", wrapper, full_type ) })? .trim()) } fn parse_map_types(inner_types: &str) -> Result<(&str, &str), String> { // Handle nested generics by counting angle brackets let mut bracket_count = 0; let mut comma_pos = None; for (i, ch) in inner_types.char_indices() { match ch { '<' => bracket_count += 1, '>' => bracket_count -= 1, ',' if bracket_count == 0 => { comma_pos = Some(i); break; } _ => {} } } if let Some(pos) = comma_pos { let key_type = inner_types .get(..pos) .ok_or_else(|| format!("Invalid key type bounds in map: {}", inner_types))? .trim(); let value_type = inner_types .get(pos + 1..) .ok_or_else(|| format!("Invalid value type bounds in map: {}", inner_types))? .trim(); if key_type.is_empty() || value_type.is_empty() { return Err(format!("Invalid map type format: {}", inner_types)); } Ok((key_type, value_type)) } else { Err(format!( "Invalid map type format, missing comma: {}", inner_types )) } }
crates/smithy-core/src/types.rs
smithy-core::src::types
2,741
true
// File: crates/smithy-core/src/lib.rs // Module: smithy-core::src::lib // // crates/smithy-core/lib.rs pub mod generator; pub mod types; pub use generator::SmithyGenerator; pub use types::*;
crates/smithy-core/src/lib.rs
smithy-core::src::lib
53
true
// File: crates/smithy-core/src/generator.rs // Module: smithy-core::src::generator // crates/smithy-core/generator.rs use std::{collections::HashMap, fs, path::Path}; use crate::types::{self as types, SmithyModel}; /// Generator for creating Smithy IDL files from models pub struct SmithyGenerator { models: Vec<SmithyModel>, } impl SmithyGenerator { pub fn new() -> Self { Self { models: Vec::new() } } pub fn add_model(&mut self, model: SmithyModel) { self.models.push(model); } pub fn generate_idl(&self, output_dir: &Path) -> Result<(), Box<dyn std::error::Error>> { fs::create_dir_all(output_dir)?; let mut namespace_models: HashMap<String, Vec<&SmithyModel>> = HashMap::new(); let mut shape_to_namespace: HashMap<String, String> = HashMap::new(); // First, build a map of all shape names to their namespaces for model in &self.models { for shape_name in model.shapes.keys() { shape_to_namespace.insert(shape_name.clone(), model.namespace.clone()); } } // Group models by namespace for file generation for model in &self.models { namespace_models .entry(model.namespace.clone()) .or_default() .push(model); } for (namespace, models) in namespace_models { let filename = format!("{}.smithy", namespace.replace('.', "_")); let filepath = output_dir.join(filename); let mut content = String::new(); content.push_str("$version: \"2\"\n\n"); content.push_str(&format!("namespace {}\n\n", namespace)); // Collect all unique shape definitions for the current namespace let mut shapes_in_namespace = HashMap::new(); for model in models { for (shape_name, shape) in &model.shapes { shapes_in_namespace.insert(shape_name.clone(), shape.clone()); } } // Generate definitions for each shape in the namespace for (shape_name, shape) in &shapes_in_namespace { content.push_str(&self.generate_shape_definition( shape_name, shape, &namespace, &shape_to_namespace, )); content.push_str("\n\n"); } fs::write(filepath, content)?; } Ok(()) } fn generate_shape_definition( &self, name: &str, shape: &types::SmithyShape, current_namespace: &str, shape_to_namespace: &HashMap<String, String>, ) -> String { let resolve_target = |target: &str| self.resolve_type(target, current_namespace, shape_to_namespace); match shape { types::SmithyShape::Structure { members, documentation, traits, } => { let mut def = String::new(); if let Some(doc) = documentation { def.push_str(&format!("/// {}\n", doc)); } for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("structure {} {{\n", name)); for (member_name, member) in members { if let Some(doc) = &member.documentation { def.push_str(&format!(" /// {}\n", doc)); } for smithy_trait in &member.traits { def.push_str(&format!(" @{}\n", self.trait_to_string(smithy_trait))); } let resolved_target = resolve_target(&member.target); def.push_str(&format!(" {}: {}\n", member_name, resolved_target)); } def.push('}'); def } types::SmithyShape::Union { members, documentation, traits, } => { let mut def = String::new(); if let Some(doc) = documentation { def.push_str(&format!("/// {}\n", doc)); } for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("union {} {{\n", name)); for (member_name, member) in members { if let Some(doc) = &member.documentation { def.push_str(&format!(" /// {}\n", doc)); } for smithy_trait in &member.traits { def.push_str(&format!(" @{}\n", self.trait_to_string(smithy_trait))); } let resolved_target = resolve_target(&member.target); def.push_str(&format!(" {}: {}\n", member_name, resolved_target)); } def.push('}'); def } types::SmithyShape::Enum { values, documentation, traits, } => { let mut def = String::new(); if let Some(doc) = documentation { def.push_str(&format!("/// {}\n", doc)); } for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("enum {} {{\n", name)); for (value_name, enum_value) in values { if let Some(doc) = &enum_value.documentation { def.push_str(&format!(" /// {}\n", doc)); } def.push_str(&format!(" {}\n", value_name)); } def.push('}'); def } types::SmithyShape::String { traits } => { let mut def = String::new(); for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("string {}", name)); def } types::SmithyShape::Integer { traits } => { let mut def = String::new(); for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("integer {}", name)); def } types::SmithyShape::Long { traits } => { let mut def = String::new(); for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("long {}", name)); def } types::SmithyShape::Boolean { traits } => { let mut def = String::new(); for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("boolean {}", name)); def } types::SmithyShape::List { member, traits } => { let mut def = String::new(); for smithy_trait in traits { def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait))); } def.push_str(&format!("list {} {{\n", name)); let resolved_target = resolve_target(&member.target); def.push_str(&format!(" member: {}\n", resolved_target)); def.push('}'); def } } } fn resolve_type( &self, target: &str, current_namespace: &str, shape_to_namespace: &HashMap<String, String>, ) -> String { // If the target is a primitive or a fully qualified Smithy type, return it as is if target.starts_with("smithy.api#") { return target.to_string(); } // If the target is a custom type, resolve its namespace if let Some(target_namespace) = shape_to_namespace.get(target) { if target_namespace == current_namespace { // The type is in the same namespace, so no qualification is needed target.to_string() } else { // The type is in a different namespace, so it needs to be fully qualified format!("{}#{}", target_namespace, target) } } else { // If the type is not found in the shape map, it might be a primitive // or an unresolved type. For now, return it as is. target.to_string() } } fn trait_to_string(&self, smithy_trait: &types::SmithyTrait) -> String { match smithy_trait { types::SmithyTrait::Pattern { pattern } => { format!("pattern(\"{}\")", pattern) } types::SmithyTrait::Range { min, max } => match (min, max) { (Some(min), Some(max)) => format!("range(min: {}, max: {})", min, max), (Some(min), None) => format!("range(min: {})", min), (None, Some(max)) => format!("range(max: {})", max), (None, None) => "range".to_string(), }, types::SmithyTrait::Required => "required".to_string(), types::SmithyTrait::Documentation { documentation } => { format!("documentation(\"{}\")", documentation) } types::SmithyTrait::Length { min, max } => match (min, max) { (Some(min), Some(max)) => format!("length(min: {}, max: {})", min, max), (Some(min), None) => format!("length(min: {})", min), (None, Some(max)) => format!("length(max: {})", max), (None, None) => "length".to_string(), }, types::SmithyTrait::HttpLabel => "httpLabel".to_string(), types::SmithyTrait::HttpQuery { name } => { format!("httpQuery(\"{}\")", name) } types::SmithyTrait::Mixin => "mixin".to_string(), } } } impl Default for SmithyGenerator { fn default() -> Self { Self::new() } }
crates/smithy-core/src/generator.rs
smithy-core::src::generator
2,156
true
// File: crates/config_importer/src/main.rs // Module: config_importer::src::main mod cli; use std::io::{BufWriter, Write}; use anyhow::Context; /// The separator used in environment variable names. const ENV_VAR_SEPARATOR: &str = "__"; #[cfg(not(feature = "preserve_order"))] type EnvironmentVariableMap = std::collections::HashMap<String, String>; #[cfg(feature = "preserve_order")] type EnvironmentVariableMap = indexmap::IndexMap<String, String>; fn main() -> anyhow::Result<()> { let args = <cli::Args as clap::Parser>::parse(); // Read input TOML file let toml_contents = std::fs::read_to_string(args.input_file).context("Failed to read input file")?; let table = toml_contents .parse::<toml::Table>() .context("Failed to parse TOML file contents")?; // Parse TOML file contents to a `HashMap` of environment variable name and value pairs let env_vars = table .iter() .flat_map(|(key, value)| process_toml_value(&args.prefix, key, value)) .collect::<EnvironmentVariableMap>(); let writer: BufWriter<Box<dyn Write>> = match args.output_file { // Write to file if output file is specified Some(file) => BufWriter::new(Box::new( std::fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(file) .context("Failed to open output file")?, )), // Write to stdout otherwise None => BufWriter::new(Box::new(std::io::stdout().lock())), }; // Write environment variables in specified format match args.output_format { cli::OutputFormat::KubernetesJson => { let k8s_env_vars = env_vars .into_iter() .map(|(name, value)| KubernetesEnvironmentVariable { name, value }) .collect::<Vec<_>>(); serde_json::to_writer_pretty(writer, &k8s_env_vars) .context("Failed to serialize environment variables as JSON")? } } Ok(()) } fn process_toml_value( prefix: impl std::fmt::Display + Clone, key: impl std::fmt::Display + Clone, value: &toml::Value, ) -> Vec<(String, String)> { let key_with_prefix = format!("{prefix}{ENV_VAR_SEPARATOR}{key}").to_ascii_uppercase(); match value { toml::Value::String(s) => vec![(key_with_prefix, s.to_owned())], toml::Value::Integer(i) => vec![(key_with_prefix, i.to_string())], toml::Value::Float(f) => vec![(key_with_prefix, f.to_string())], toml::Value::Boolean(b) => vec![(key_with_prefix, b.to_string())], toml::Value::Datetime(dt) => vec![(key_with_prefix, dt.to_string())], toml::Value::Array(values) => { if values.is_empty() { return vec![(key_with_prefix, String::new())]; } // This logic does not support / account for arrays of tables or arrays of arrays. let (_processed_keys, processed_values) = values .iter() .flat_map(|v| process_toml_value(prefix.clone(), key.clone(), v)) .unzip::<_, _, Vec<String>, Vec<String>>(); vec![(key_with_prefix, processed_values.join(","))] } toml::Value::Table(map) => map .into_iter() .flat_map(|(k, v)| process_toml_value(key_with_prefix.clone(), k, v)) .collect(), } } /// The Kubernetes environment variable structure containing a name and a value. #[derive(Debug, serde::Serialize, serde::Deserialize)] pub(crate) struct KubernetesEnvironmentVariable { name: String, value: String, }
crates/config_importer/src/main.rs
config_importer::src::main
863
true
// File: crates/config_importer/src/cli.rs // Module: config_importer::src::cli use std::path::PathBuf; /// Utility to import a hyperswitch TOML configuration file, convert it into environment variable /// key-value pairs, and export it in the specified format. #[derive(clap::Parser, Debug)] #[command(arg_required_else_help = true)] pub(crate) struct Args { /// Input TOML configuration file. #[arg(short, long, value_name = "FILE")] pub(crate) input_file: PathBuf, /// The format to convert the environment variables to. #[arg( value_enum, short = 'f', long, value_name = "FORMAT", default_value = "kubernetes-json" )] pub(crate) output_format: OutputFormat, /// Output file. Output will be written to stdout if not specified. #[arg(short, long, value_name = "FILE")] pub(crate) output_file: Option<PathBuf>, /// Prefix to be used for each environment variable in the generated output. #[arg(short, long, default_value = "ROUTER")] pub(crate) prefix: String, } /// The output format to convert environment variables to. #[derive(clap::ValueEnum, Clone, Copy, Debug)] pub(crate) enum OutputFormat { /// Converts each environment variable to an object containing `name` and `value` fields. /// /// ```json /// { /// "name": "ENVIRONMENT", /// "value": "PRODUCTION" /// } /// ``` KubernetesJson, }
crates/config_importer/src/cli.rs
config_importer::src::cli
341
true
// File: crates/cards/src/lib.rs // Module: cards::src::lib pub mod validate; use std::ops::Deref; use common_utils::{date_time, errors}; use error_stack::report; use masking::{PeekInterface, StrongSecret}; use serde::{de, Deserialize, Serialize}; use time::{Date, Duration, PrimitiveDateTime, Time}; pub use crate::validate::{CardNumber, CardNumberStrategy, CardNumberValidationErr, NetworkToken}; #[derive(Serialize)] pub struct CardSecurityCode(StrongSecret<u16>); impl TryFrom<u16> for CardSecurityCode { type Error = error_stack::Report<errors::ValidationError>; fn try_from(csc: u16) -> Result<Self, Self::Error> { if (0..=9999).contains(&csc) { Ok(Self(StrongSecret::new(csc))) } else { Err(report!(errors::ValidationError::InvalidValue { message: "invalid card security code".to_string() })) } } } impl<'de> Deserialize<'de> for CardSecurityCode { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let csc = u16::deserialize(deserializer)?; csc.try_into().map_err(de::Error::custom) } } #[derive(Clone, Debug, Serialize)] pub struct CardExpirationMonth(StrongSecret<u8>); impl CardExpirationMonth { pub fn two_digits(&self) -> String { format!("{:02}", self.peek()) } } impl TryFrom<u8> for CardExpirationMonth { type Error = error_stack::Report<errors::ValidationError>; fn try_from(month: u8) -> Result<Self, Self::Error> { if (1..=12).contains(&month) { Ok(Self(StrongSecret::new(month))) } else { Err(report!(errors::ValidationError::InvalidValue { message: "invalid card expiration month".to_string() })) } } } impl<'de> Deserialize<'de> for CardExpirationMonth { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let month = u8::deserialize(deserializer)?; month.try_into().map_err(de::Error::custom) } } #[derive(Clone, Debug, Serialize)] pub struct CardExpirationYear(StrongSecret<u16>); impl CardExpirationYear { pub fn four_digits(&self) -> String { self.peek().to_string() } pub fn two_digits(&self) -> String { let year = self.peek() % 100; year.to_string() } } impl TryFrom<u16> for CardExpirationYear { type Error = error_stack::Report<errors::ValidationError>; fn try_from(year: u16) -> Result<Self, Self::Error> { let curr_year = u16::try_from(date_time::now().year()).map_err(|_| { report!(errors::ValidationError::InvalidValue { message: "invalid year".to_string() }) })?; if year >= curr_year { Ok(Self(StrongSecret::<u16>::new(year))) } else { Err(report!(errors::ValidationError::InvalidValue { message: "invalid card expiration year".to_string() })) } } } impl<'de> Deserialize<'de> for CardExpirationYear { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let year = u16::deserialize(deserializer)?; year.try_into().map_err(de::Error::custom) } } #[derive(Serialize, Deserialize)] pub struct CardExpiration { pub month: CardExpirationMonth, pub year: CardExpirationYear, } impl CardExpiration { pub fn is_expired(&self) -> Result<bool, error_stack::Report<errors::ValidationError>> { let current_datetime_utc = date_time::now(); let expiration_month = time::Month::try_from(*self.month.peek()).map_err(|_| { report!(errors::ValidationError::InvalidValue { message: "invalid month".to_string() }) })?; let expiration_year = *self.year.peek(); let expiration_day = expiration_month.length(i32::from(expiration_year)); let expiration_date = Date::from_calendar_date(i32::from(expiration_year), expiration_month, expiration_day) .map_err(|_| { report!(errors::ValidationError::InvalidValue { message: "error while constructing calendar date".to_string() }) })?; let expiration_time = Time::MIDNIGHT; // actual expiry date specified on card w.r.t. local timezone // max diff b/w utc and other timezones is 14 hours let mut expiration_datetime_utc = PrimitiveDateTime::new(expiration_date, expiration_time); // compensating time difference b/w local and utc timezone by adding a day expiration_datetime_utc = expiration_datetime_utc.saturating_add(Duration::days(1)); Ok(current_datetime_utc > expiration_datetime_utc) } pub fn get_month(&self) -> &CardExpirationMonth { &self.month } pub fn get_year(&self) -> &CardExpirationYear { &self.year } } impl TryFrom<(u8, u16)> for CardExpiration { type Error = error_stack::Report<errors::ValidationError>; fn try_from(items: (u8, u16)) -> errors::CustomResult<Self, errors::ValidationError> { let month = CardExpirationMonth::try_from(items.0)?; let year = CardExpirationYear::try_from(items.1)?; Ok(Self { month, year }) } } impl Deref for CardSecurityCode { type Target = StrongSecret<u16>; fn deref(&self) -> &Self::Target { &self.0 } } impl Deref for CardExpirationMonth { type Target = StrongSecret<u8>; fn deref(&self) -> &Self::Target { &self.0 } } impl Deref for CardExpirationYear { type Target = StrongSecret<u16>; fn deref(&self) -> &Self::Target { &self.0 } }
crates/cards/src/lib.rs
cards::src::lib
1,380
true
// File: crates/cards/src/validate.rs // Module: cards::src::validate use std::{collections::HashMap, fmt, ops::Deref, str::FromStr, sync::LazyLock}; use common_utils::errors::ValidationError; use error_stack::report; use masking::{PeekInterface, Strategy, StrongSecret, WithType}; use regex::Regex; #[cfg(not(target_arch = "wasm32"))] use router_env::{logger, which as router_env_which, Env}; use serde::{Deserialize, Deserializer, Serialize}; use thiserror::Error; /// Minimum limit of a card number will not be less than 8 by ISO standards pub const MIN_CARD_NUMBER_LENGTH: usize = 8; /// Maximum limit of a card number will not exceed 19 by ISO standards pub const MAX_CARD_NUMBER_LENGTH: usize = 19; #[derive(Debug, Deserialize, Serialize, Error)] #[error("{0}")] pub struct CardNumberValidationErr(&'static str); /// Card number #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)] pub struct CardNumber(StrongSecret<String, CardNumberStrategy>); //Network Token #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)] pub struct NetworkToken(StrongSecret<String, CardNumberStrategy>); impl CardNumber { pub fn get_card_isin(&self) -> String { self.0.peek().chars().take(6).collect::<String>() } pub fn get_extended_card_bin(&self) -> String { self.0.peek().chars().take(8).collect::<String>() } pub fn get_card_no(&self) -> String { self.0.peek().chars().collect::<String>() } pub fn get_last4(&self) -> String { self.0 .peek() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>() } pub fn is_cobadged_card(&self) -> Result<bool, error_stack::Report<ValidationError>> { /// Regex to identify card networks static CARD_NETWORK_REGEX: LazyLock<HashMap<&str, Result<Regex, regex::Error>>> = LazyLock::new(|| { let mut map = HashMap::new(); map.insert( "Mastercard", Regex::new(r"^(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[0-1][0-9]|2720|5[1-5])"), ); map.insert("American Express", Regex::new(r"^3[47]")); map.insert("Visa", Regex::new(r"^4")); map.insert( "Discover", Regex::new( r"^(6011|64[4-9]|65|622126|622[1-9][0-9][0-9]|6229[0-1][0-9]|622925)", ), ); map.insert( "Maestro", Regex::new(r"^(5018|5081|5044|504681|504993|5020|502260|5038|5893|603845|603123|6304|6759|676[1-3]|6220|504834|504817|504645|504775|600206|627741)"), ); map.insert( "RuPay", Regex::new(r"^(508227|508[5-9]|603741|60698[5-9]|60699|607[0-8]|6079[0-7]|60798[0-4]|60800[1-9]|6080[1-9]|608[1-4]|608500|6521[5-9]|652[2-9]|6530|6531[0-4]|817290|817368|817378|353800|82)"), ); map.insert("Diners Club", Regex::new(r"^(36|38|39|30[0-5])")); map.insert("JCB", Regex::new(r"^35(2[89]|[3-8][0-9])")); map.insert("CarteBlanche", Regex::new(r"^389[0-9]{11}$")); map.insert("Sodex", Regex::new(r"^(637513)")); map.insert("BAJAJ", Regex::new(r"^(203040)")); map.insert("CartesBancaires", Regex::new(r"^(401(005|006|581)|4021(01|02)|403550|405936|406572|41(3849|4819|50(56|59|62|71|74)|6286|65(37|79)|71[7])|420110|423460|43(47(21|22)|50(48|49|50|51|52)|7875|95(09|11|15|39|98)|96(03|18|19|20|22|72))|4424(48|49|50|51|52|57)|448412|4505(19|60)|45(33|56[6-8]|61|62[^3]|6955|7452|7717|93[02379])|46(099|54(76|77)|6258|6575|98[023])|47(4107|71(73|74|86)|72(65|93)|9619)|48(1091|3622|6519)|49(7|83[5-9]|90(0[1-6]|1[0-6]|2[0-3]|3[0-3]|4[0-3]|5[0-2]|68|9[256789]))|5075(89|90|93|94|97)|51(0726|3([0-7]|8[56]|9(00|38))|5214|62(07|36)|72(22|43)|73(65|66)|7502|7647|8101|9920)|52(0993|1662|3718|7429|9227|93(13|14|31)|94(14|21|30|40|47|55|56|[6-9])|9542)|53(0901|10(28|30)|1195|23(4[4-7])|2459|25(09|34|54|56)|3801|41(02|05|11)|50(29|66)|5324|61(07|15)|71(06|12)|8011)|54(2848|5157|9538|98(5[89]))|55(39(79|93)|42(05|60)|4965|7008|88(67|82)|89(29|4[23])|9618|98(09|10))|56(0408|12(0[2-6]|4[134]|5[04678]))|58(17(0[0-7]|15|2[14]|3[16789]|4[0-9]|5[016]|6[269]|7[3789]|8[0-7]|9[017])|55(0[2-5]|7[7-9]|8[0-2])))")); map }); let mut no_of_supported_card_networks = 0; let card_number_str = self.get_card_no(); for (_, regex) in CARD_NETWORK_REGEX.iter() { let card_regex = match regex.as_ref() { Ok(regex) => Ok(regex), Err(_) => Err(report!(ValidationError::InvalidValue { message: "Invalid regex expression".into(), })), }?; if card_regex.is_match(&card_number_str) { no_of_supported_card_networks += 1; if no_of_supported_card_networks > 1 { break; } } } Ok(no_of_supported_card_networks > 1) } } impl NetworkToken { pub fn get_card_isin(&self) -> String { self.0.peek().chars().take(6).collect::<String>() } pub fn get_extended_card_bin(&self) -> String { self.0.peek().chars().take(8).collect::<String>() } pub fn get_card_no(&self) -> String { self.0.peek().chars().collect::<String>() } pub fn get_last4(&self) -> String { self.0 .peek() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>() } } impl FromStr for CardNumber { type Err = CardNumberValidationErr; fn from_str(card_number: &str) -> Result<Self, Self::Err> { // Valid test cards for threedsecureio let valid_test_cards = vec![ "4000100511112003", "6000100611111203", "3000100811111072", "9000100111111111", ]; #[cfg(not(target_arch = "wasm32"))] let valid_test_cards = match router_env_which() { Env::Development | Env::Sandbox => valid_test_cards, Env::Production => vec![], }; let card_number = card_number.split_whitespace().collect::<String>(); let is_card_valid = sanitize_card_number(&card_number)?; if valid_test_cards.contains(&card_number.as_str()) || is_card_valid { Ok(Self(StrongSecret::new(card_number))) } else { Err(CardNumberValidationErr("card number invalid")) } } } impl FromStr for NetworkToken { type Err = CardNumberValidationErr; fn from_str(network_token: &str) -> Result<Self, Self::Err> { // Valid test cards for threedsecureio let valid_test_network_tokens = vec![ "4000100511112003", "6000100611111203", "3000100811111072", "9000100111111111", ]; #[cfg(not(target_arch = "wasm32"))] let valid_test_network_tokens = match router_env_which() { Env::Development | Env::Sandbox => valid_test_network_tokens, Env::Production => vec![], }; let network_token = network_token.split_whitespace().collect::<String>(); let is_network_token_valid = sanitize_card_number(&network_token)?; if valid_test_network_tokens.contains(&network_token.as_str()) || is_network_token_valid { Ok(Self(StrongSecret::new(network_token))) } else { Err(CardNumberValidationErr("network token invalid")) } } } pub fn sanitize_card_number(card_number: &str) -> Result<bool, CardNumberValidationErr> { let is_card_number_valid = Ok(card_number) .and_then(validate_card_number_chars) .and_then(validate_card_number_length) .map(|number| luhn(&number))?; Ok(is_card_number_valid) } /// # Panics /// /// Never, as a single character will never be greater than 10, or `u8` pub fn validate_card_number_chars(number: &str) -> Result<Vec<u8>, CardNumberValidationErr> { let data = number.chars().try_fold( Vec::with_capacity(MAX_CARD_NUMBER_LENGTH), |mut data, character| { data.push( #[allow(clippy::expect_used)] character .to_digit(10) .ok_or(CardNumberValidationErr( "invalid character found in card number", ))? .try_into() .expect("error while converting a single character to u8"), // safety, a single character will never be greater `u8` ); Ok::<Vec<u8>, CardNumberValidationErr>(data) }, )?; Ok(data) } pub fn validate_card_number_length(number: Vec<u8>) -> Result<Vec<u8>, CardNumberValidationErr> { if number.len() >= MIN_CARD_NUMBER_LENGTH && number.len() <= MAX_CARD_NUMBER_LENGTH { Ok(number) } else { Err(CardNumberValidationErr("invalid card number length")) } } #[allow(clippy::as_conversions)] pub fn luhn(number: &[u8]) -> bool { number .iter() .rev() .enumerate() .map(|(idx, element)| { ((*element * 2) / 10 + (*element * 2) % 10) * ((idx as u8) % 2) + (*element) * (((idx + 1) as u8) % 2) }) .sum::<u8>() % 10 == 0 } impl TryFrom<String> for CardNumber { type Error = CardNumberValidationErr; fn try_from(value: String) -> Result<Self, Self::Error> { Self::from_str(&value) } } impl TryFrom<String> for NetworkToken { type Error = CardNumberValidationErr; fn try_from(value: String) -> Result<Self, Self::Error> { Self::from_str(&value) } } impl Deref for CardNumber { type Target = StrongSecret<String, CardNumberStrategy>; fn deref(&self) -> &StrongSecret<String, CardNumberStrategy> { &self.0 } } impl Deref for NetworkToken { type Target = StrongSecret<String, CardNumberStrategy>; fn deref(&self) -> &StrongSecret<String, CardNumberStrategy> { &self.0 } } impl<'de> Deserialize<'de> for CardNumber { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { let s = String::deserialize(d)?; Self::from_str(&s).map_err(serde::de::Error::custom) } } impl<'de> Deserialize<'de> for NetworkToken { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { let s = String::deserialize(d)?; Self::from_str(&s).map_err(serde::de::Error::custom) } } pub enum CardNumberStrategy {} impl<T> Strategy<T> for CardNumberStrategy where T: AsRef<str>, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); if val_str.len() < 15 || val_str.len() > 19 { return WithType::fmt(val, f); } if let Some(value) = val_str.get(..6) { write!(f, "{}{}", value, "*".repeat(val_str.len() - 6)) } else { #[cfg(not(target_arch = "wasm32"))] logger::error!("Invalid card number {val_str}"); WithType::fmt(val, f) } } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use masking::Secret; use super::*; #[test] fn valid_card_number() { let s = "371449635398431"; assert_eq!( CardNumber::from_str(s).unwrap(), CardNumber(StrongSecret::from_str(s).unwrap()) ); } #[test] fn invalid_card_number_length() { let s = "371446"; assert_eq!( CardNumber::from_str(s).unwrap_err().to_string(), "invalid card number length".to_string() ); } #[test] fn card_number_with_non_digit_character() { let s = "371446431 A"; assert_eq!( CardNumber::from_str(s).unwrap_err().to_string(), "invalid character found in card number".to_string() ); } #[test] fn invalid_card_number() { let s = "371446431"; assert_eq!( CardNumber::from_str(s).unwrap_err().to_string(), "card number invalid".to_string() ); } #[test] fn card_number_no_whitespace() { let s = "3714 4963 5398 431"; assert_eq!( CardNumber::from_str(s).unwrap().to_string(), "371449*********" ); } #[test] fn test_valid_card_number_masking() { let secret: Secret<String, CardNumberStrategy> = Secret::new("1234567890987654".to_string()); assert_eq!("123456**********", format!("{secret:?}")); } #[test] fn test_invalid_card_number_masking() { let secret: Secret<String, CardNumberStrategy> = Secret::new("9123456789".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } #[test] fn test_valid_card_number_strong_secret_masking() { let card_number = CardNumber::from_str("3714 4963 5398 431").unwrap(); let secret = &(*card_number); assert_eq!("371449*********", format!("{secret:?}")); } #[test] fn test_valid_card_number_deserialization() { let card_number = serde_json::from_str::<CardNumber>(r#""3714 4963 5398 431""#).unwrap(); let secret = card_number.to_string(); assert_eq!(r#""371449*********""#, format!("{secret:?}")); } #[test] fn test_invalid_card_number_deserialization() { let card_number = serde_json::from_str::<CardNumber>(r#""1234 5678""#); let error_msg = card_number.unwrap_err().to_string(); assert_eq!(error_msg, "card number invalid".to_string()); } }
crates/cards/src/validate.rs
cards::src::validate
4,527
true
// File: crates/currency_conversion/src/types.rs // Module: currency_conversion::src::types use std::collections::HashMap; use common_enums::Currency; use rust_decimal::Decimal; use rusty_money::iso; use crate::error::CurrencyConversionError; /// Cached currency store of base currency #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ExchangeRates { pub base_currency: Currency, pub conversion: HashMap<Currency, CurrencyFactors>, } /// Stores the multiplicative factor for conversion between currency to base and vice versa #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CurrencyFactors { /// The factor that will be multiplied to provide Currency output pub to_factor: Decimal, /// The factor that will be multiplied to provide for the base output pub from_factor: Decimal, } impl CurrencyFactors { pub fn new(to_factor: Decimal, from_factor: Decimal) -> Self { Self { to_factor, from_factor, } } } impl ExchangeRates { pub fn new(base_currency: Currency, conversion: HashMap<Currency, CurrencyFactors>) -> Self { Self { base_currency, conversion, } } /// The flow here is from_currency -> base_currency -> to_currency /// from to_currency -> base currency pub fn forward_conversion( &self, amt: Decimal, from_currency: Currency, ) -> Result<Decimal, CurrencyConversionError> { let from_factor = self .conversion .get(&from_currency) .ok_or_else(|| { CurrencyConversionError::ConversionNotSupported(from_currency.to_string()) })? .from_factor; amt.checked_mul(from_factor) .ok_or(CurrencyConversionError::DecimalMultiplicationFailed) } /// from base_currency -> to_currency pub fn backward_conversion( &self, amt: Decimal, to_currency: Currency, ) -> Result<Decimal, CurrencyConversionError> { let to_factor = self .conversion .get(&to_currency) .ok_or_else(|| { CurrencyConversionError::ConversionNotSupported(to_currency.to_string()) })? .to_factor; amt.checked_mul(to_factor) .ok_or(CurrencyConversionError::DecimalMultiplicationFailed) } } pub fn currency_match(currency: Currency) -> &'static iso::Currency { match currency { Currency::AED => iso::AED, Currency::AFN => iso::AFN, Currency::ALL => iso::ALL, Currency::AMD => iso::AMD, Currency::ANG => iso::ANG, Currency::AOA => iso::AOA, Currency::ARS => iso::ARS, Currency::AUD => iso::AUD, Currency::AWG => iso::AWG, Currency::AZN => iso::AZN, Currency::BAM => iso::BAM, Currency::BBD => iso::BBD, Currency::BDT => iso::BDT, Currency::BGN => iso::BGN, Currency::BHD => iso::BHD, Currency::BIF => iso::BIF, Currency::BMD => iso::BMD, Currency::BND => iso::BND, Currency::BOB => iso::BOB, Currency::BRL => iso::BRL, Currency::BSD => iso::BSD, Currency::BTN => iso::BTN, Currency::BWP => iso::BWP, Currency::BYN => iso::BYN, Currency::BZD => iso::BZD, Currency::CAD => iso::CAD, Currency::CDF => iso::CDF, Currency::CHF => iso::CHF, Currency::CLF => iso::CLF, Currency::CLP => iso::CLP, Currency::CNY => iso::CNY, Currency::COP => iso::COP, Currency::CRC => iso::CRC, Currency::CUC => iso::CUC, Currency::CUP => iso::CUP, Currency::CVE => iso::CVE, Currency::CZK => iso::CZK, Currency::DJF => iso::DJF, Currency::DKK => iso::DKK, Currency::DOP => iso::DOP, Currency::DZD => iso::DZD, Currency::EGP => iso::EGP, Currency::ERN => iso::ERN, Currency::ETB => iso::ETB, Currency::EUR => iso::EUR, Currency::FJD => iso::FJD, Currency::FKP => iso::FKP, Currency::GBP => iso::GBP, Currency::GEL => iso::GEL, Currency::GHS => iso::GHS, Currency::GIP => iso::GIP, Currency::GMD => iso::GMD, Currency::GNF => iso::GNF, Currency::GTQ => iso::GTQ, Currency::GYD => iso::GYD, Currency::HKD => iso::HKD, Currency::HNL => iso::HNL, Currency::HRK => iso::HRK, Currency::HTG => iso::HTG, Currency::HUF => iso::HUF, Currency::IDR => iso::IDR, Currency::ILS => iso::ILS, Currency::INR => iso::INR, Currency::IQD => iso::IQD, Currency::IRR => iso::IRR, Currency::ISK => iso::ISK, Currency::JMD => iso::JMD, Currency::JOD => iso::JOD, Currency::JPY => iso::JPY, Currency::KES => iso::KES, Currency::KGS => iso::KGS, Currency::KHR => iso::KHR, Currency::KMF => iso::KMF, Currency::KPW => iso::KPW, Currency::KRW => iso::KRW, Currency::KWD => iso::KWD, Currency::KYD => iso::KYD, Currency::KZT => iso::KZT, Currency::LAK => iso::LAK, Currency::LBP => iso::LBP, Currency::LKR => iso::LKR, Currency::LRD => iso::LRD, Currency::LSL => iso::LSL, Currency::LYD => iso::LYD, Currency::MAD => iso::MAD, Currency::MDL => iso::MDL, Currency::MGA => iso::MGA, Currency::MKD => iso::MKD, Currency::MMK => iso::MMK, Currency::MNT => iso::MNT, Currency::MOP => iso::MOP, Currency::MRU => iso::MRU, Currency::MUR => iso::MUR, Currency::MVR => iso::MVR, Currency::MWK => iso::MWK, Currency::MXN => iso::MXN, Currency::MYR => iso::MYR, Currency::MZN => iso::MZN, Currency::NAD => iso::NAD, Currency::NGN => iso::NGN, Currency::NIO => iso::NIO, Currency::NOK => iso::NOK, Currency::NPR => iso::NPR, Currency::NZD => iso::NZD, Currency::OMR => iso::OMR, Currency::PAB => iso::PAB, Currency::PEN => iso::PEN, Currency::PGK => iso::PGK, Currency::PHP => iso::PHP, Currency::PKR => iso::PKR, Currency::PLN => iso::PLN, Currency::PYG => iso::PYG, Currency::QAR => iso::QAR, Currency::RON => iso::RON, Currency::RSD => iso::RSD, Currency::RUB => iso::RUB, Currency::RWF => iso::RWF, Currency::SAR => iso::SAR, Currency::SBD => iso::SBD, Currency::SCR => iso::SCR, Currency::SDG => iso::SDG, Currency::SEK => iso::SEK, Currency::SGD => iso::SGD, Currency::SHP => iso::SHP, Currency::SLE => iso::SLE, Currency::SLL => iso::SLL, Currency::SOS => iso::SOS, Currency::SRD => iso::SRD, Currency::SSP => iso::SSP, Currency::STD => iso::STD, Currency::STN => iso::STN, Currency::SVC => iso::SVC, Currency::SYP => iso::SYP, Currency::SZL => iso::SZL, Currency::THB => iso::THB, Currency::TJS => iso::TJS, Currency::TND => iso::TND, Currency::TMT => iso::TMT, Currency::TOP => iso::TOP, Currency::TTD => iso::TTD, Currency::TRY => iso::TRY, Currency::TWD => iso::TWD, Currency::TZS => iso::TZS, Currency::UAH => iso::UAH, Currency::UGX => iso::UGX, Currency::USD => iso::USD, Currency::UYU => iso::UYU, Currency::UZS => iso::UZS, Currency::VES => iso::VES, Currency::VND => iso::VND, Currency::VUV => iso::VUV, Currency::WST => iso::WST, Currency::XAF => iso::XAF, Currency::XCD => iso::XCD, Currency::XOF => iso::XOF, Currency::XPF => iso::XPF, Currency::YER => iso::YER, Currency::ZAR => iso::ZAR, Currency::ZMW => iso::ZMW, Currency::ZWL => iso::ZWL, } }
crates/currency_conversion/src/types.rs
currency_conversion::src::types
2,237
true
// File: crates/currency_conversion/src/conversion.rs // Module: currency_conversion::src::conversion use common_enums::Currency; use rust_decimal::Decimal; use rusty_money::Money; use crate::{ error::CurrencyConversionError, types::{currency_match, ExchangeRates}, }; pub fn convert( ex_rates: &ExchangeRates, from_currency: Currency, to_currency: Currency, amount: i64, ) -> Result<Decimal, CurrencyConversionError> { let money_minor = Money::from_minor(amount, currency_match(from_currency)); let base_currency = ex_rates.base_currency; if to_currency == base_currency { ex_rates.forward_conversion(*money_minor.amount(), from_currency) } else if from_currency == base_currency { ex_rates.backward_conversion(*money_minor.amount(), to_currency) } else { let base_conversion_amt = ex_rates.forward_conversion(*money_minor.amount(), from_currency)?; ex_rates.backward_conversion(base_conversion_amt, to_currency) } } #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::print_stdout)] use std::collections::HashMap; use crate::types::CurrencyFactors; #[test] fn currency_to_currency_conversion() { use super::*; let mut conversion: HashMap<Currency, CurrencyFactors> = HashMap::new(); let inr_conversion_rates = CurrencyFactors::new(Decimal::new(823173, 4), Decimal::new(1214, 5)); let szl_conversion_rates = CurrencyFactors::new(Decimal::new(194423, 4), Decimal::new(514, 4)); let convert_from = Currency::SZL; let convert_to = Currency::INR; let amount = 2000; let base_currency = Currency::USD; conversion.insert(convert_from, inr_conversion_rates); conversion.insert(convert_to, szl_conversion_rates); let sample_rate = ExchangeRates::new(base_currency, conversion); let res = convert(&sample_rate, convert_from, convert_to, amount).expect("converted_currency"); println!("The conversion from {amount} {convert_from} to {convert_to} is {res:?}"); } #[test] fn currency_to_base_conversion() { use super::*; let mut conversion: HashMap<Currency, CurrencyFactors> = HashMap::new(); let inr_conversion_rates = CurrencyFactors::new(Decimal::new(823173, 4), Decimal::new(1214, 5)); let usd_conversion_rates = CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0)); let convert_from = Currency::INR; let convert_to = Currency::USD; let amount = 2000; let base_currency = Currency::USD; conversion.insert(convert_from, inr_conversion_rates); conversion.insert(convert_to, usd_conversion_rates); let sample_rate = ExchangeRates::new(base_currency, conversion); let res = convert(&sample_rate, convert_from, convert_to, amount).expect("converted_currency"); println!("The conversion from {amount} {convert_from} to {convert_to} is {res:?}"); } #[test] fn base_to_currency_conversion() { use super::*; let mut conversion: HashMap<Currency, CurrencyFactors> = HashMap::new(); let inr_conversion_rates = CurrencyFactors::new(Decimal::new(823173, 4), Decimal::new(1214, 5)); let usd_conversion_rates = CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0)); let convert_from = Currency::USD; let convert_to = Currency::INR; let amount = 2000; let base_currency = Currency::USD; conversion.insert(convert_from, usd_conversion_rates); conversion.insert(convert_to, inr_conversion_rates); let sample_rate = ExchangeRates::new(base_currency, conversion); let res = convert(&sample_rate, convert_from, convert_to, amount).expect("converted_currency"); println!("The conversion from {amount} {convert_from} to {convert_to} is {res:?}"); } }
crates/currency_conversion/src/conversion.rs
currency_conversion::src::conversion
933
true
// File: crates/currency_conversion/src/error.rs // Module: currency_conversion::src::error #[derive(Debug, thiserror::Error, serde::Serialize)] #[serde(tag = "type", content = "info", rename_all = "snake_case")] pub enum CurrencyConversionError { #[error("Currency Conversion isn't possible")] DecimalMultiplicationFailed, #[error("Currency not supported: '{0}'")] ConversionNotSupported(String), }
crates/currency_conversion/src/error.rs
currency_conversion::src::error
94
true
// File: crates/currency_conversion/src/lib.rs // Module: currency_conversion::src::lib pub mod conversion; pub mod error; pub mod types;
crates/currency_conversion/src/lib.rs
currency_conversion::src::lib
33
true
// File: crates/diesel_models/src/dynamic_routing_stats.rs // Module: diesel_models::src::dynamic_routing_stats use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::schema::dynamic_routing_stats; #[derive(Clone, Debug, Eq, Insertable, PartialEq)] #[diesel(table_name = dynamic_routing_stats)] pub struct DynamicRoutingStatsNew { pub payment_id: common_utils::id_type::PaymentId, pub attempt_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub profile_id: common_utils::id_type::ProfileId, pub amount: common_utils::types::MinorUnit, pub success_based_routing_connector: String, pub payment_connector: String, pub currency: Option<common_enums::Currency>, pub payment_method: Option<common_enums::PaymentMethod>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub payment_status: common_enums::AttemptStatus, pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, pub created_at: time::PrimitiveDateTime, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub global_success_based_connector: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)] #[diesel(table_name = dynamic_routing_stats, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct DynamicRoutingStats { pub payment_id: common_utils::id_type::PaymentId, pub attempt_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub profile_id: common_utils::id_type::ProfileId, pub amount: common_utils::types::MinorUnit, pub success_based_routing_connector: String, pub payment_connector: String, pub currency: Option<common_enums::Currency>, pub payment_method: Option<common_enums::PaymentMethod>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub payment_status: common_enums::AttemptStatus, pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, pub created_at: time::PrimitiveDateTime, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub global_success_based_connector: Option<String>, } #[derive( Clone, Debug, Eq, PartialEq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, )] #[diesel(table_name = dynamic_routing_stats)] pub struct DynamicRoutingStatsUpdate { pub amount: common_utils::types::MinorUnit, pub success_based_routing_connector: String, pub payment_connector: String, pub currency: Option<common_enums::Currency>, pub payment_method: Option<common_enums::PaymentMethod>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub payment_status: common_enums::AttemptStatus, pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub global_success_based_connector: Option<String>, }
crates/diesel_models/src/dynamic_routing_stats.rs
diesel_models::src::dynamic_routing_stats
716
true
// File: crates/diesel_models/src/schema_v2.rs // Module: diesel_models::src::schema_v2 // @generated automatically by Diesel CLI. diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; address (address_id) { #[max_length = 64] address_id -> Varchar, #[max_length = 128] city -> Nullable<Varchar>, country -> Nullable<CountryAlpha2>, line1 -> Nullable<Bytea>, line2 -> Nullable<Bytea>, line3 -> Nullable<Bytea>, state -> Nullable<Bytea>, zip -> Nullable<Bytea>, first_name -> Nullable<Bytea>, last_name -> Nullable<Bytea>, phone_number -> Nullable<Bytea>, #[max_length = 8] country_code -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, email -> Nullable<Bytea>, origin_zip -> Nullable<Bytea>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; api_keys (key_id) { #[max_length = 64] key_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, #[max_length = 128] hashed_api_key -> Varchar, #[max_length = 16] prefix -> Varchar, created_at -> Timestamp, expires_at -> Nullable<Timestamp>, last_used -> Nullable<Timestamp>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; authentication (authentication_id) { #[max_length = 64] authentication_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] authentication_connector -> Nullable<Varchar>, #[max_length = 64] connector_authentication_id -> Nullable<Varchar>, authentication_data -> Nullable<Jsonb>, #[max_length = 64] payment_method_id -> Varchar, #[max_length = 64] authentication_type -> Nullable<Varchar>, #[max_length = 64] authentication_status -> Varchar, #[max_length = 64] authentication_lifecycle_status -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, maximum_supported_version -> Nullable<Jsonb>, #[max_length = 64] threeds_server_transaction_id -> Nullable<Varchar>, #[max_length = 64] cavv -> Nullable<Varchar>, #[max_length = 64] authentication_flow_type -> Nullable<Varchar>, message_version -> Nullable<Jsonb>, #[max_length = 64] eci -> Nullable<Varchar>, #[max_length = 64] trans_status -> Nullable<Varchar>, #[max_length = 64] acquirer_bin -> Nullable<Varchar>, #[max_length = 64] acquirer_merchant_id -> Nullable<Varchar>, three_ds_method_data -> Nullable<Varchar>, three_ds_method_url -> Nullable<Varchar>, acs_url -> Nullable<Varchar>, challenge_request -> Nullable<Varchar>, acs_reference_number -> Nullable<Varchar>, acs_trans_id -> Nullable<Varchar>, acs_signed_content -> Nullable<Varchar>, #[max_length = 64] profile_id -> Varchar, #[max_length = 255] payment_id -> Nullable<Varchar>, #[max_length = 128] merchant_connector_id -> Nullable<Varchar>, #[max_length = 64] ds_trans_id -> Nullable<Varchar>, #[max_length = 128] directory_server_id -> Nullable<Varchar>, #[max_length = 64] acquirer_country_code -> Nullable<Varchar>, service_details -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, #[max_length = 128] authentication_client_secret -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, #[max_length = 2048] return_url -> Nullable<Varchar>, amount -> Nullable<Int8>, currency -> Nullable<Currency>, billing_address -> Nullable<Bytea>, shipping_address -> Nullable<Bytea>, browser_info -> Nullable<Jsonb>, email -> Nullable<Bytea>, #[max_length = 128] profile_acquirer_id -> Nullable<Varchar>, challenge_code -> Nullable<Varchar>, challenge_cancel -> Nullable<Varchar>, challenge_code_reason -> Nullable<Varchar>, message_extension -> Nullable<Jsonb>, #[max_length = 255] challenge_request_key -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist (merchant_id, fingerprint_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, metadata -> Nullable<Jsonb>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_fingerprint (id) { id -> Int4, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, encrypted_fingerprint -> Text, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_lookup (id) { id -> Int4, #[max_length = 64] merchant_id -> Varchar, fingerprint -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; business_profile (id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_name -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, return_url -> Nullable<Text>, enable_payment_response_hash -> Bool, #[max_length = 255] payment_response_hash_key -> Nullable<Varchar>, redirect_to_merchant_with_http_post -> Bool, webhook_details -> Nullable<Json>, metadata -> Nullable<Json>, is_recon_enabled -> Bool, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, payment_link_config -> Nullable<Jsonb>, session_expiry -> Nullable<Int8>, authentication_connector_details -> Nullable<Jsonb>, payout_link_config -> Nullable<Jsonb>, is_extended_card_info_enabled -> Nullable<Bool>, extended_card_info_config -> Nullable<Jsonb>, is_connector_agnostic_mit_enabled -> Nullable<Bool>, use_billing_as_payment_method_billing -> Nullable<Bool>, collect_shipping_details_from_wallet_connector -> Nullable<Bool>, collect_billing_details_from_wallet_connector -> Nullable<Bool>, outgoing_webhook_custom_http_headers -> Nullable<Bytea>, always_collect_billing_details_from_wallet_connector -> Nullable<Bool>, always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>, #[max_length = 64] tax_connector_id -> Nullable<Varchar>, is_tax_connector_enabled -> Nullable<Bool>, version -> ApiVersion, dynamic_routing_algorithm -> Nullable<Json>, is_network_tokenization_enabled -> Bool, is_auto_retries_enabled -> Nullable<Bool>, max_auto_retries_enabled -> Nullable<Int2>, always_request_extended_authorization -> Nullable<Bool>, is_click_to_pay_enabled -> Bool, authentication_product_ids -> Nullable<Jsonb>, card_testing_guard_config -> Nullable<Jsonb>, card_testing_secret_key -> Nullable<Bytea>, is_clear_pan_retries_enabled -> Bool, force_3ds_challenge -> Nullable<Bool>, is_debit_routing_enabled -> Bool, merchant_business_country -> Nullable<CountryAlpha2>, #[max_length = 64] id -> Varchar, is_iframe_redirection_enabled -> Nullable<Bool>, three_ds_decision_rule_algorithm -> Nullable<Jsonb>, acquirer_config_map -> Nullable<Jsonb>, #[max_length = 16] merchant_category_code -> Nullable<Varchar>, #[max_length = 32] merchant_country_code -> Nullable<Varchar>, dispute_polling_interval -> Nullable<Int4>, is_manual_retry_enabled -> Nullable<Bool>, always_enable_overcapture -> Nullable<Bool>, #[max_length = 64] billing_processor_id -> Nullable<Varchar>, is_external_vault_enabled -> Nullable<Bool>, external_vault_connector_details -> Nullable<Jsonb>, is_l2_l3_enabled -> Nullable<Bool>, #[max_length = 64] routing_algorithm_id -> Nullable<Varchar>, order_fulfillment_time -> Nullable<Int8>, order_fulfillment_time_origin -> Nullable<OrderFulfillmentTimeOrigin>, #[max_length = 64] frm_routing_algorithm_id -> Nullable<Varchar>, #[max_length = 64] payout_routing_algorithm_id -> Nullable<Varchar>, default_fallback_routing -> Nullable<Jsonb>, three_ds_decision_manager_config -> Nullable<Jsonb>, should_collect_cvv_during_payment -> Nullable<Bool>, revenue_recovery_retry_algorithm_type -> Nullable<RevenueRecoveryAlgorithmType>, revenue_recovery_retry_algorithm_data -> Nullable<Jsonb>, #[max_length = 16] split_txns_enabled -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; callback_mapper (id, type_) { #[max_length = 128] id -> Varchar, #[sql_name = "type"] #[max_length = 64] type_ -> Varchar, data -> Jsonb, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; captures (capture_id) { #[max_length = 64] capture_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> CaptureStatus, amount -> Int8, currency -> Nullable<Currency>, #[max_length = 255] connector -> Varchar, #[max_length = 255] error_message -> Nullable<Varchar>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 255] error_reason -> Nullable<Varchar>, tax_amount -> Nullable<Int8>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] authorized_attempt_id -> Varchar, #[max_length = 128] connector_capture_id -> Nullable<Varchar>, capture_sequence -> Int2, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, processor_capture_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; cards_info (card_iin) { #[max_length = 16] card_iin -> Varchar, card_issuer -> Nullable<Text>, card_network -> Nullable<Text>, card_type -> Nullable<Text>, card_subtype -> Nullable<Text>, card_issuing_country -> Nullable<Text>, #[max_length = 32] bank_code_id -> Nullable<Varchar>, #[max_length = 32] bank_code -> Nullable<Varchar>, #[max_length = 32] country_code -> Nullable<Varchar>, date_created -> Timestamp, last_updated -> Nullable<Timestamp>, last_updated_provider -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; configs (key) { id -> Int4, #[max_length = 255] key -> Varchar, config -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; customers (id) { #[max_length = 64] merchant_id -> Varchar, name -> Nullable<Bytea>, email -> Nullable<Bytea>, phone -> Nullable<Bytea>, #[max_length = 8] phone_country_code -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, created_at -> Timestamp, metadata -> Nullable<Json>, connector_customer -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] default_payment_method_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, tax_registration_id -> Nullable<Bytea>, #[max_length = 64] merchant_reference_id -> Nullable<Varchar>, default_billing_address -> Nullable<Bytea>, default_shipping_address -> Nullable<Bytea>, status -> Nullable<DeleteStatus>, #[max_length = 64] id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dashboard_metadata (id) { id -> Int4, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] org_id -> Varchar, data_key -> DashboardMetadata, data_value -> Json, #[max_length = 64] created_by -> Varchar, created_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dispute (dispute_id) { #[max_length = 64] dispute_id -> Varchar, #[max_length = 255] amount -> Varchar, #[max_length = 255] currency -> Varchar, dispute_stage -> DisputeStage, dispute_status -> DisputeStatus, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] connector_status -> Varchar, #[max_length = 255] connector_dispute_id -> Varchar, #[max_length = 255] connector_reason -> Nullable<Varchar>, #[max_length = 255] connector_reason_code -> Nullable<Varchar>, challenge_required_by -> Nullable<Timestamp>, connector_created_at -> Nullable<Timestamp>, connector_updated_at -> Nullable<Timestamp>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] connector -> Varchar, evidence -> Jsonb, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, dispute_amount -> Int8, #[max_length = 32] organization_id -> Varchar, dispute_currency -> Nullable<Currency>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dynamic_routing_stats (attempt_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_id -> Varchar, amount -> Int8, #[max_length = 64] success_based_routing_connector -> Varchar, #[max_length = 64] payment_connector -> Varchar, currency -> Nullable<Currency>, #[max_length = 64] payment_method -> Nullable<Varchar>, capture_method -> Nullable<CaptureMethod>, authentication_type -> Nullable<AuthenticationType>, payment_status -> AttemptStatus, conclusive_classification -> SuccessBasedRoutingConclusiveState, created_at -> Timestamp, #[max_length = 64] payment_method_type -> Nullable<Varchar>, #[max_length = 64] global_success_based_connector -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; events (event_id) { #[max_length = 64] event_id -> Varchar, event_type -> EventType, event_class -> EventClass, is_webhook_notified -> Bool, #[max_length = 64] primary_object_id -> Varchar, primary_object_type -> EventObjectType, created_at -> Timestamp, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] business_profile_id -> Nullable<Varchar>, primary_object_created_at -> Nullable<Timestamp>, #[max_length = 64] idempotent_event_id -> Nullable<Varchar>, #[max_length = 64] initial_attempt_id -> Nullable<Varchar>, request -> Nullable<Bytea>, response -> Nullable<Bytea>, delivery_attempt -> Nullable<WebhookDeliveryAttempt>, metadata -> Nullable<Jsonb>, is_overall_delivery_successful -> Nullable<Bool>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; file_metadata (file_id, merchant_id) { #[max_length = 64] file_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] file_name -> Nullable<Varchar>, file_size -> Int4, #[max_length = 255] file_type -> Varchar, #[max_length = 255] provider_file_id -> Nullable<Varchar>, #[max_length = 255] file_upload_provider -> Nullable<Varchar>, available -> Bool, created_at -> Timestamp, #[max_length = 255] connector_label -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; fraud_check (frm_id, attempt_id, payment_id, merchant_id) { #[max_length = 64] frm_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, created_at -> Timestamp, #[max_length = 255] frm_name -> Varchar, #[max_length = 255] frm_transaction_id -> Nullable<Varchar>, frm_transaction_type -> FraudCheckType, frm_status -> FraudCheckStatus, frm_score -> Nullable<Int4>, frm_reason -> Nullable<Jsonb>, #[max_length = 255] frm_error -> Nullable<Varchar>, payment_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] last_step -> Varchar, payment_capture_method -> Nullable<CaptureMethod>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; gateway_status_map (connector, flow, sub_flow, code, message) { #[max_length = 64] connector -> Varchar, #[max_length = 64] flow -> Varchar, #[max_length = 64] sub_flow -> Varchar, #[max_length = 255] code -> Varchar, #[max_length = 1024] message -> Varchar, #[max_length = 64] status -> Varchar, #[max_length = 64] router_error -> Nullable<Varchar>, #[max_length = 64] decision -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, step_up_possible -> Bool, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, #[max_length = 64] error_category -> Nullable<Varchar>, clear_pan_possible -> Bool, feature_data -> Nullable<Jsonb>, #[max_length = 64] feature -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; generic_link (link_id) { #[max_length = 64] link_id -> Varchar, #[max_length = 64] primary_reference -> Varchar, #[max_length = 64] merchant_id -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, expiry -> Timestamp, link_data -> Jsonb, link_status -> Jsonb, link_type -> GenericLinkType, url -> Text, return_url -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; hyperswitch_ai_interaction (id, created_at) { #[max_length = 64] id -> Varchar, #[max_length = 64] session_id -> Nullable<Varchar>, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Nullable<Varchar>, user_query -> Nullable<Bytea>, response -> Nullable<Bytea>, database_query -> Nullable<Text>, #[max_length = 64] interaction_status -> Nullable<Varchar>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; hyperswitch_ai_interaction_default (id, created_at) { #[max_length = 64] id -> Varchar, #[max_length = 64] session_id -> Nullable<Varchar>, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Nullable<Varchar>, user_query -> Nullable<Bytea>, response -> Nullable<Bytea>, database_query -> Nullable<Text>, #[max_length = 64] interaction_status -> Nullable<Varchar>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; incremental_authorization (authorization_id, merchant_id) { #[max_length = 64] authorization_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Varchar, amount -> Int8, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] status -> Varchar, #[max_length = 255] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, #[max_length = 64] connector_authorization_id -> Nullable<Varchar>, previously_authorized_amount -> Int8, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; invoice (id) { #[max_length = 64] id -> Varchar, #[max_length = 128] subscription_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 128] merchant_connector_id -> Varchar, #[max_length = 64] payment_intent_id -> Nullable<Varchar>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, #[max_length = 64] customer_id -> Varchar, amount -> Int8, #[max_length = 3] currency -> Varchar, #[max_length = 64] status -> Varchar, #[max_length = 128] provider_name -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] connector_invoice_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; locker_mock_up (id) { id -> Int4, #[max_length = 255] card_id -> Varchar, #[max_length = 255] external_id -> Varchar, #[max_length = 255] card_fingerprint -> Varchar, #[max_length = 255] card_global_fingerprint -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] card_number -> Varchar, #[max_length = 255] card_exp_year -> Varchar, #[max_length = 255] card_exp_month -> Varchar, #[max_length = 255] name_on_card -> Nullable<Varchar>, #[max_length = 255] nickname -> Nullable<Varchar>, #[max_length = 255] customer_id -> Nullable<Varchar>, duplicate -> Nullable<Bool>, #[max_length = 8] card_cvc -> Nullable<Varchar>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, enc_card_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; mandate (mandate_id) { #[max_length = 64] mandate_id -> Varchar, #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_method_id -> Varchar, mandate_status -> MandateStatus, mandate_type -> MandateType, customer_accepted_at -> Nullable<Timestamp>, #[max_length = 64] customer_ip_address -> Nullable<Varchar>, #[max_length = 255] customer_user_agent -> Nullable<Varchar>, #[max_length = 128] network_transaction_id -> Nullable<Varchar>, #[max_length = 64] previous_attempt_id -> Nullable<Varchar>, created_at -> Timestamp, mandate_amount -> Nullable<Int8>, mandate_currency -> Nullable<Currency>, amount_captured -> Nullable<Int8>, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_mandate_id -> Nullable<Varchar>, start_date -> Nullable<Timestamp>, end_date -> Nullable<Timestamp>, metadata -> Nullable<Jsonb>, connector_mandate_ids -> Nullable<Jsonb>, #[max_length = 64] original_payment_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, #[max_length = 2048] customer_user_agent_extended -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_account (id) { merchant_name -> Nullable<Bytea>, merchant_details -> Nullable<Bytea>, #[max_length = 128] publishable_key -> Nullable<Varchar>, storage_scheme -> MerchantStorageScheme, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 32] organization_id -> Varchar, recon_status -> ReconStatus, version -> ApiVersion, is_platform_account -> Bool, #[max_length = 64] id -> Varchar, #[max_length = 64] product_type -> Nullable<Varchar>, #[max_length = 64] merchant_account_type -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_connector_account (id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] connector_name -> Varchar, connector_account_details -> Bytea, disabled -> Nullable<Bool>, payment_methods_enabled -> Nullable<Array<Nullable<Json>>>, connector_type -> ConnectorType, metadata -> Nullable<Jsonb>, #[max_length = 255] connector_label -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, connector_webhook_details -> Nullable<Jsonb>, frm_config -> Nullable<Array<Nullable<Jsonb>>>, #[max_length = 64] profile_id -> Nullable<Varchar>, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, pm_auth_config -> Nullable<Jsonb>, status -> ConnectorStatus, additional_merchant_data -> Nullable<Bytea>, connector_wallets_details -> Nullable<Bytea>, version -> ApiVersion, #[max_length = 64] id -> Varchar, feature_metadata -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_key_store (merchant_id) { #[max_length = 64] merchant_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; organization (id) { organization_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 32] id -> Varchar, organization_name -> Nullable<Text>, version -> ApiVersion, #[max_length = 64] organization_type -> Nullable<Varchar>, #[max_length = 64] platform_merchant_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_attempt (id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> AttemptStatus, #[max_length = 64] connector -> Nullable<Varchar>, error_message -> Nullable<Text>, surcharge_amount -> Nullable<Int8>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, authentication_type -> Nullable<AuthenticationType>, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, #[max_length = 255] cancellation_reason -> Nullable<Varchar>, amount_to_capture -> Nullable<Int8>, browser_info -> Nullable<Jsonb>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 128] payment_token -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, #[max_length = 50] payment_experience -> Nullable<Varchar>, payment_method_data -> Nullable<Jsonb>, preprocessing_step_id -> Nullable<Varchar>, error_reason -> Nullable<Text>, multiple_capture_count -> Nullable<Int2>, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, amount_capturable -> Int8, #[max_length = 32] updated_by -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, encoded_data -> Nullable<Text>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, net_amount -> Nullable<Int8>, external_three_ds_authentication_attempted -> Nullable<Bool>, #[max_length = 64] authentication_connector -> Nullable<Varchar>, #[max_length = 64] authentication_id -> Nullable<Varchar>, #[max_length = 64] fingerprint_id -> Nullable<Varchar>, #[max_length = 64] client_source -> Nullable<Varchar>, #[max_length = 64] client_version -> Nullable<Varchar>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] organization_id -> Varchar, #[max_length = 32] card_network -> Nullable<Varchar>, shipping_cost -> Nullable<Int8>, order_tax_amount -> Nullable<Int8>, request_extended_authorization -> Nullable<Bool>, extended_authorization_applied -> Nullable<Bool>, capture_before -> Nullable<Timestamp>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, #[max_length = 64] processor_merchant_id -> Nullable<Varchar>, #[max_length = 255] created_by -> Nullable<Varchar>, #[max_length = 255] connector_request_reference_id -> Nullable<Varchar>, #[max_length = 255] network_transaction_id -> Nullable<Varchar>, is_overcapture_enabled -> Nullable<Bool>, network_details -> Nullable<Jsonb>, is_stored_credential -> Nullable<Bool>, authorized_amount -> Nullable<Int8>, payment_method_type_v2 -> Nullable<Varchar>, #[max_length = 128] connector_payment_id -> Nullable<Varchar>, #[max_length = 64] payment_method_subtype -> Varchar, routing_result -> Nullable<Jsonb>, authentication_applied -> Nullable<AuthenticationType>, #[max_length = 128] external_reference_id -> Nullable<Varchar>, tax_on_surcharge -> Nullable<Int8>, payment_method_billing_address -> Nullable<Bytea>, redirection_data -> Nullable<Jsonb>, connector_payment_data -> Nullable<Text>, connector_token_details -> Nullable<Jsonb>, #[max_length = 64] id -> Varchar, feature_metadata -> Nullable<Jsonb>, #[max_length = 32] network_advice_code -> Nullable<Varchar>, #[max_length = 32] network_decline_code -> Nullable<Varchar>, network_error_message -> Nullable<Text>, #[max_length = 64] attempts_group_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_intent (id) { #[max_length = 64] merchant_id -> Varchar, status -> IntentStatus, amount -> Int8, currency -> Nullable<Currency>, amount_captured -> Nullable<Int8>, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 255] return_url -> Nullable<Varchar>, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, setup_future_usage -> Nullable<FutureUsage>, #[max_length = 64] active_attempt_id -> Nullable<Varchar>, order_details -> Nullable<Array<Nullable<Jsonb>>>, allowed_payment_method_types -> Nullable<Json>, connector_metadata -> Nullable<Json>, feature_metadata -> Nullable<Json>, attempt_count -> Int2, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 255] payment_link_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, surcharge_applicable -> Nullable<Bool>, request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>, authorization_count -> Nullable<Int4>, session_expiry -> Nullable<Timestamp>, request_external_three_ds_authentication -> Nullable<Bool>, frm_metadata -> Nullable<Jsonb>, customer_details -> Nullable<Bytea>, shipping_cost -> Nullable<Int8>, #[max_length = 32] organization_id -> Varchar, tax_details -> Nullable<Jsonb>, skip_external_tax_calculation -> Nullable<Bool>, request_extended_authorization -> Nullable<Bool>, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, split_payments -> Nullable<Jsonb>, #[max_length = 64] platform_merchant_id -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, force_3ds_challenge_trigger -> Nullable<Bool>, #[max_length = 64] processor_merchant_id -> Nullable<Varchar>, #[max_length = 255] created_by -> Nullable<Varchar>, is_iframe_redirection_enabled -> Nullable<Bool>, is_payment_id_from_merchant -> Nullable<Bool>, #[max_length = 64] payment_channel -> Nullable<Varchar>, tax_status -> Nullable<Varchar>, discount_amount -> Nullable<Int8>, shipping_amount_tax -> Nullable<Int8>, duty_amount -> Nullable<Int8>, order_date -> Nullable<Timestamp>, enable_partial_authorization -> Nullable<Bool>, enable_overcapture -> Nullable<Bool>, #[max_length = 64] mit_category -> Nullable<Varchar>, #[max_length = 64] merchant_reference_id -> Nullable<Varchar>, billing_address -> Nullable<Bytea>, shipping_address -> Nullable<Bytea>, capture_method -> Nullable<CaptureMethod>, authentication_type -> Nullable<AuthenticationType>, prerouting_algorithm -> Nullable<Jsonb>, surcharge_amount -> Nullable<Int8>, tax_on_surcharge -> Nullable<Int8>, #[max_length = 64] frm_merchant_decision -> Nullable<Varchar>, #[max_length = 255] statement_descriptor -> Nullable<Varchar>, enable_payment_link -> Nullable<Bool>, apply_mit_exemption -> Nullable<Bool>, customer_present -> Nullable<Bool>, #[max_length = 64] routing_algorithm_id -> Nullable<Varchar>, payment_link_config -> Nullable<Jsonb>, #[max_length = 64] id -> Varchar, #[max_length = 16] split_txns_enabled -> Nullable<Varchar>, #[max_length = 64] active_attempts_group_id -> Nullable<Varchar>, #[max_length = 16] active_attempt_id_type -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_link (payment_link_id) { #[max_length = 255] payment_link_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 255] link_to_pay -> Varchar, #[max_length = 64] merchant_id -> Varchar, amount -> Int8, currency -> Nullable<Currency>, created_at -> Timestamp, last_modified_at -> Timestamp, fulfilment_time -> Nullable<Timestamp>, #[max_length = 64] custom_merchant_name -> Nullable<Varchar>, payment_link_config -> Nullable<Jsonb>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 255] secure_link -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_methods (id) { #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, payment_method_data -> Nullable<Bytea>, #[max_length = 64] locker_id -> Nullable<Varchar>, last_used_at -> Timestamp, connector_mandate_details -> Nullable<Jsonb>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] status -> Varchar, #[max_length = 255] network_transaction_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, payment_method_billing_address -> Nullable<Bytea>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, #[max_length = 128] network_token_requestor_reference_id -> Nullable<Varchar>, #[max_length = 64] network_token_locker_id -> Nullable<Varchar>, network_token_payment_method_data -> Nullable<Bytea>, #[max_length = 64] external_vault_source -> Nullable<Varchar>, #[max_length = 64] vault_type -> Nullable<Varchar>, #[max_length = 64] locker_fingerprint_id -> Nullable<Varchar>, #[max_length = 64] payment_method_type_v2 -> Nullable<Varchar>, #[max_length = 64] payment_method_subtype -> Nullable<Varchar>, #[max_length = 64] id -> Varchar, external_vault_token_data -> Nullable<Bytea>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payout_attempt (merchant_id, payout_attempt_id) { #[max_length = 64] payout_attempt_id -> Varchar, #[max_length = 64] payout_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] address_id -> Nullable<Varchar>, #[max_length = 64] connector -> Nullable<Varchar>, #[max_length = 128] connector_payout_id -> Nullable<Varchar>, #[max_length = 64] payout_token -> Nullable<Varchar>, status -> PayoutStatus, is_eligible -> Nullable<Bool>, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, business_country -> Nullable<CountryAlpha2>, #[max_length = 64] business_label -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, routing_info -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, additional_payout_method_data -> Nullable<Jsonb>, #[max_length = 255] merchant_order_reference_id -> Nullable<Varchar>, payout_connector_metadata -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payouts (merchant_id, payout_id) { #[max_length = 64] payout_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] address_id -> Nullable<Varchar>, payout_type -> Nullable<PayoutType>, #[max_length = 64] payout_method_id -> Nullable<Varchar>, amount -> Int8, destination_currency -> Currency, source_currency -> Currency, #[max_length = 255] description -> Nullable<Varchar>, recurring -> Bool, auto_fulfill -> Bool, #[max_length = 255] return_url -> Nullable<Varchar>, #[max_length = 64] entity_type -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, last_modified_at -> Timestamp, attempt_count -> Int2, #[max_length = 64] profile_id -> Varchar, status -> PayoutStatus, confirm -> Nullable<Bool>, #[max_length = 255] payout_link_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 32] priority -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; process_tracker (id) { #[max_length = 127] id -> Varchar, #[max_length = 64] name -> Nullable<Varchar>, tag -> Array<Nullable<Text>>, #[max_length = 64] runner -> Nullable<Varchar>, retry_count -> Int4, schedule_time -> Nullable<Timestamp>, #[max_length = 255] rule -> Varchar, tracking_data -> Json, #[max_length = 255] business_status -> Varchar, status -> ProcessTrackerStatus, event -> Array<Nullable<Text>>, created_at -> Timestamp, updated_at -> Timestamp, version -> ApiVersion, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; refund (id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 128] connector_transaction_id -> Varchar, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_refund_id -> Nullable<Varchar>, #[max_length = 64] external_reference_id -> Nullable<Varchar>, refund_type -> RefundType, total_amount -> Int8, currency -> Currency, refund_amount -> Int8, refund_status -> RefundStatus, sent_to_gateway -> Bool, refund_error_message -> Nullable<Text>, metadata -> Nullable<Json>, #[max_length = 128] refund_arn -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] refund_reason -> Nullable<Varchar>, refund_error_code -> Nullable<Text>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, charges -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, split_refunds -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, processor_refund_data -> Nullable<Text>, processor_transaction_data -> Nullable<Text>, #[max_length = 64] id -> Varchar, #[max_length = 64] merchant_reference_id -> Nullable<Varchar>, #[max_length = 64] connector_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; relay (id) { #[max_length = 64] id -> Varchar, #[max_length = 128] connector_resource_id -> Varchar, #[max_length = 64] connector_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, relay_type -> RelayType, request_data -> Nullable<Jsonb>, status -> RelayStatus, #[max_length = 128] connector_reference_id -> Nullable<Varchar>, #[max_length = 64] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, created_at -> Timestamp, modified_at -> Timestamp, response_data -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; reverse_lookup (lookup_id) { #[max_length = 128] lookup_id -> Varchar, #[max_length = 128] sk_id -> Varchar, #[max_length = 128] pk_id -> Varchar, #[max_length = 128] source -> Varchar, #[max_length = 32] updated_by -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; roles (role_id) { #[max_length = 64] role_name -> Varchar, #[max_length = 64] role_id -> Varchar, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Varchar, groups -> Array<Nullable<Text>>, scope -> RoleScope, created_at -> Timestamp, #[max_length = 64] created_by -> Varchar, last_modified_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; routing_algorithm (algorithm_id) { #[max_length = 64] algorithm_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, kind -> RoutingAlgorithmKind, algorithm_data -> Jsonb, created_at -> Timestamp, modified_at -> Timestamp, algorithm_for -> TransactionType, #[max_length = 64] decision_engine_routing_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; subscription (id) { #[max_length = 128] id -> Varchar, #[max_length = 128] status -> Varchar, #[max_length = 128] billing_processor -> Nullable<Varchar>, #[max_length = 128] payment_method_id -> Nullable<Varchar>, #[max_length = 128] merchant_connector_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 128] connector_subscription_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] customer_id -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, #[max_length = 128] merchant_reference_id -> Nullable<Varchar>, #[max_length = 128] plan_id -> Nullable<Varchar>, #[max_length = 128] item_price_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; themes (theme_id) { #[max_length = 64] theme_id -> Varchar, #[max_length = 64] tenant_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] theme_name -> Varchar, #[max_length = 64] email_primary_color -> Varchar, #[max_length = 64] email_foreground_color -> Varchar, #[max_length = 64] email_background_color -> Varchar, #[max_length = 64] email_entity_name -> Varchar, email_entity_logo_url -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; tokenization (id) { #[max_length = 64] id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 64] customer_id -> Varchar, created_at -> Timestamp, updated_at -> Timestamp, #[max_length = 255] locker_id -> Varchar, flag -> TokenizationFlag, version -> ApiVersion, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; unified_translations (unified_code, unified_message, locale) { #[max_length = 255] unified_code -> Varchar, #[max_length = 1024] unified_message -> Varchar, #[max_length = 255] locale -> Varchar, #[max_length = 1024] translation -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_authentication_methods (id) { #[max_length = 64] id -> Varchar, #[max_length = 64] auth_id -> Varchar, #[max_length = 64] owner_id -> Varchar, #[max_length = 64] owner_type -> Varchar, #[max_length = 64] auth_type -> Varchar, private_config -> Nullable<Bytea>, public_config -> Nullable<Jsonb>, allow_signup -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] email_domain -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_key_store (user_id) { #[max_length = 64] user_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_roles (id) { id -> Int4, #[max_length = 64] user_id -> Varchar, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, status -> UserStatus, #[max_length = 64] created_by -> Varchar, #[max_length = 64] last_modified_by -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] entity_id -> Nullable<Varchar>, #[max_length = 64] entity_type -> Nullable<Varchar>, version -> UserRoleVersion, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; users (user_id) { #[max_length = 64] user_id -> Varchar, #[max_length = 255] email -> Varchar, #[max_length = 255] name -> Varchar, #[max_length = 255] password -> Nullable<Varchar>, is_verified -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, totp_status -> TotpStatus, totp_secret -> Nullable<Bytea>, totp_recovery_codes -> Nullable<Array<Nullable<Text>>>, last_password_modified_at -> Nullable<Timestamp>, lineage_context -> Nullable<Jsonb>, } } diesel::allow_tables_to_appear_in_same_query!( address, api_keys, authentication, blocklist, blocklist_fingerprint, blocklist_lookup, business_profile, callback_mapper, captures, cards_info, configs, customers, dashboard_metadata, dispute, dynamic_routing_stats, events, file_metadata, fraud_check, gateway_status_map, generic_link, hyperswitch_ai_interaction, hyperswitch_ai_interaction_default, incremental_authorization, invoice, locker_mock_up, mandate, merchant_account, merchant_connector_account, merchant_key_store, organization, payment_attempt, payment_intent, payment_link, payment_methods, payout_attempt, payouts, process_tracker, refund, relay, reverse_lookup, roles, routing_algorithm, subscription, themes, tokenization, unified_translations, user_authentication_methods, user_key_store, user_roles, users, );
crates/diesel_models/src/schema_v2.rs
diesel_models::src::schema_v2
13,554
true
// File: crates/diesel_models/src/tokenization.rs // Module: diesel_models::src::tokenization #[cfg(feature = "v2")] use common_enums; #[cfg(feature = "v2")] use common_utils::id_type; #[cfg(feature = "v2")] use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; #[cfg(feature = "v2")] use serde::{Deserialize, Serialize}; #[cfg(feature = "v2")] use time::PrimitiveDateTime; #[cfg(feature = "v2")] use crate::schema_v2::tokenization; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, Identifiable, Insertable, Queryable)] #[diesel(table_name = tokenization)] pub struct Tokenization { pub id: id_type::GlobalTokenId, pub merchant_id: id_type::MerchantId, pub customer_id: id_type::GlobalCustomerId, pub created_at: PrimitiveDateTime, pub updated_at: PrimitiveDateTime, pub locker_id: String, pub flag: common_enums::enums::TokenizationFlag, pub version: common_enums::enums::ApiVersion, } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, Insertable)] #[diesel(table_name = tokenization)] pub struct TokenizationNew { pub id: id_type::GlobalTokenId, pub merchant_id: id_type::MerchantId, pub customer_id: id_type::GlobalCustomerId, pub locker_id: String, pub created_at: PrimitiveDateTime, pub updated_at: PrimitiveDateTime, pub version: common_enums::enums::ApiVersion, pub flag: common_enums::enums::TokenizationFlag, } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, AsChangeset)] #[diesel(table_name = tokenization)] pub struct TokenizationUpdateInternal { pub updated_at: PrimitiveDateTime, pub flag: Option<common_enums::enums::TokenizationFlag>, }
crates/diesel_models/src/tokenization.rs
diesel_models::src::tokenization
448
true
// File: crates/diesel_models/src/dispute.rs // Module: diesel_models::src::dispute use common_utils::{ custom_serde, types::{MinorUnit, StringMinorUnit}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use serde::Serialize; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::dispute}; #[derive(Clone, Debug, Insertable, Serialize, router_derive::DebugAsDisplay)] #[diesel(table_name = dispute)] #[serde(deny_unknown_fields)] pub struct DisputeNew { pub dispute_id: String, pub amount: StringMinorUnit, pub currency: String, pub dispute_stage: storage_enums::DisputeStage, pub dispute_status: storage_enums::DisputeStatus, pub payment_id: common_utils::id_type::PaymentId, pub attempt_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub connector_status: String, pub connector_dispute_id: String, pub connector_reason: Option<String>, pub connector_reason_code: Option<String>, pub challenge_required_by: Option<PrimitiveDateTime>, pub connector_created_at: Option<PrimitiveDateTime>, pub connector_updated_at: Option<PrimitiveDateTime>, pub connector: String, pub evidence: Option<Secret<serde_json::Value>>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub dispute_amount: MinorUnit, pub organization_id: common_utils::id_type::OrganizationId, pub dispute_currency: Option<storage_enums::Currency>, } #[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable, Selectable)] #[diesel(table_name = dispute, primary_key(dispute_id), check_for_backend(diesel::pg::Pg))] pub struct Dispute { pub dispute_id: String, pub amount: StringMinorUnit, pub currency: String, pub dispute_stage: storage_enums::DisputeStage, pub dispute_status: storage_enums::DisputeStatus, pub payment_id: common_utils::id_type::PaymentId, pub attempt_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub connector_status: String, pub connector_dispute_id: String, pub connector_reason: Option<String>, pub connector_reason_code: Option<String>, pub challenge_required_by: Option<PrimitiveDateTime>, pub connector_created_at: Option<PrimitiveDateTime>, pub connector_updated_at: Option<PrimitiveDateTime>, #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub connector: String, pub evidence: Secret<serde_json::Value>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub dispute_amount: MinorUnit, pub organization_id: common_utils::id_type::OrganizationId, pub dispute_currency: Option<storage_enums::Currency>, } #[derive(Debug)] pub enum DisputeUpdate { Update { dispute_stage: storage_enums::DisputeStage, dispute_status: storage_enums::DisputeStatus, connector_status: String, connector_reason: Option<String>, connector_reason_code: Option<String>, challenge_required_by: Option<PrimitiveDateTime>, connector_updated_at: Option<PrimitiveDateTime>, }, StatusUpdate { dispute_status: storage_enums::DisputeStatus, connector_status: Option<String>, }, EvidenceUpdate { evidence: Secret<serde_json::Value>, }, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = dispute)] pub struct DisputeUpdateInternal { dispute_stage: Option<storage_enums::DisputeStage>, dispute_status: Option<storage_enums::DisputeStatus>, connector_status: Option<String>, connector_reason: Option<String>, connector_reason_code: Option<String>, challenge_required_by: Option<PrimitiveDateTime>, connector_updated_at: Option<PrimitiveDateTime>, modified_at: PrimitiveDateTime, evidence: Option<Secret<serde_json::Value>>, } impl From<DisputeUpdate> for DisputeUpdateInternal { fn from(merchant_account_update: DisputeUpdate) -> Self { match merchant_account_update { DisputeUpdate::Update { dispute_stage, dispute_status, connector_status, connector_reason, connector_reason_code, challenge_required_by, connector_updated_at, } => Self { dispute_stage: Some(dispute_stage), dispute_status: Some(dispute_status), connector_status: Some(connector_status), connector_reason, connector_reason_code, challenge_required_by, connector_updated_at, modified_at: common_utils::date_time::now(), evidence: None, }, DisputeUpdate::StatusUpdate { dispute_status, connector_status, } => Self { dispute_status: Some(dispute_status), connector_status, modified_at: common_utils::date_time::now(), dispute_stage: None, connector_reason: None, connector_reason_code: None, challenge_required_by: None, connector_updated_at: None, evidence: None, }, DisputeUpdate::EvidenceUpdate { evidence } => Self { evidence: Some(evidence), dispute_stage: None, dispute_status: None, connector_status: None, connector_reason: None, connector_reason_code: None, challenge_required_by: None, connector_updated_at: None, modified_at: common_utils::date_time::now(), }, } } }
crates/diesel_models/src/dispute.rs
diesel_models::src::dispute
1,257
true
// File: crates/diesel_models/src/kv.rs // Module: diesel_models::src::kv use error_stack::ResultExt; use serde::{Deserialize, Serialize}; #[cfg(feature = "v2")] use crate::payment_attempt::PaymentAttemptUpdateInternal; #[cfg(feature = "v1")] use crate::payment_intent::PaymentIntentUpdate; #[cfg(feature = "v2")] use crate::payment_intent::PaymentIntentUpdateInternal; use crate::{ address::{Address, AddressNew, AddressUpdateInternal}, customers::{Customer, CustomerNew, CustomerUpdateInternal}, errors, payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate}, payment_intent::PaymentIntentNew, payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate}, payouts::{Payouts, PayoutsNew, PayoutsUpdate}, refund::{Refund, RefundNew, RefundUpdate}, reverse_lookup::{ReverseLookup, ReverseLookupNew}, Mandate, MandateNew, MandateUpdateInternal, PaymentIntent, PaymentMethod, PaymentMethodNew, PaymentMethodUpdateInternal, PgPooledConn, }; #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "db_op", content = "data")] pub enum DBOperation { Insert { insertable: Box<Insertable> }, Update { updatable: Box<Updateable> }, } impl DBOperation { pub fn operation<'a>(&self) -> &'a str { match self { Self::Insert { .. } => "insert", Self::Update { .. } => "update", } } pub fn table<'a>(&self) -> &'a str { match self { Self::Insert { insertable } => match **insertable { Insertable::PaymentIntent(_) => "payment_intent", Insertable::PaymentAttempt(_) => "payment_attempt", Insertable::Refund(_) => "refund", Insertable::Address(_) => "address", Insertable::Payouts(_) => "payouts", Insertable::PayoutAttempt(_) => "payout_attempt", Insertable::Customer(_) => "customer", Insertable::ReverseLookUp(_) => "reverse_lookup", Insertable::PaymentMethod(_) => "payment_method", Insertable::Mandate(_) => "mandate", }, Self::Update { updatable } => match **updatable { Updateable::PaymentIntentUpdate(_) => "payment_intent", Updateable::PaymentAttemptUpdate(_) => "payment_attempt", Updateable::RefundUpdate(_) => "refund", Updateable::CustomerUpdate(_) => "customer", Updateable::AddressUpdate(_) => "address", Updateable::PayoutsUpdate(_) => "payouts", Updateable::PayoutAttemptUpdate(_) => "payout_attempt", Updateable::PaymentMethodUpdate(_) => "payment_method", Updateable::MandateUpdate(_) => " mandate", }, } } } #[derive(Debug)] pub enum DBResult { PaymentIntent(Box<PaymentIntent>), PaymentAttempt(Box<PaymentAttempt>), Refund(Box<Refund>), Address(Box<Address>), Customer(Box<Customer>), ReverseLookUp(Box<ReverseLookup>), Payouts(Box<Payouts>), PayoutAttempt(Box<PayoutAttempt>), PaymentMethod(Box<PaymentMethod>), Mandate(Box<Mandate>), } #[derive(Debug, Serialize, Deserialize)] pub struct TypedSql { #[serde(flatten)] pub op: DBOperation, } impl DBOperation { pub async fn execute(self, conn: &PgPooledConn) -> crate::StorageResult<DBResult> { Ok(match self { Self::Insert { insertable } => match *insertable { Insertable::PaymentIntent(a) => { DBResult::PaymentIntent(Box::new(a.insert(conn).await?)) } Insertable::PaymentAttempt(a) => { DBResult::PaymentAttempt(Box::new(a.insert(conn).await?)) } Insertable::Refund(a) => DBResult::Refund(Box::new(a.insert(conn).await?)), Insertable::Address(addr) => DBResult::Address(Box::new(addr.insert(conn).await?)), Insertable::Customer(cust) => { DBResult::Customer(Box::new(cust.insert(conn).await?)) } Insertable::ReverseLookUp(rev) => { DBResult::ReverseLookUp(Box::new(rev.insert(conn).await?)) } Insertable::Payouts(rev) => DBResult::Payouts(Box::new(rev.insert(conn).await?)), Insertable::PayoutAttempt(rev) => { DBResult::PayoutAttempt(Box::new(rev.insert(conn).await?)) } Insertable::PaymentMethod(rev) => { DBResult::PaymentMethod(Box::new(rev.insert(conn).await?)) } Insertable::Mandate(m) => DBResult::Mandate(Box::new(m.insert(conn).await?)), }, Self::Update { updatable } => match *updatable { #[cfg(feature = "v1")] Updateable::PaymentIntentUpdate(a) => { DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?)) } #[cfg(feature = "v2")] Updateable::PaymentIntentUpdate(a) => { DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?)) } #[cfg(feature = "v1")] Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( a.orig.update_with_attempt_id(conn, a.update_data).await?, )), #[cfg(feature = "v2")] Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( a.orig.update_with_attempt_id(conn, a.update_data).await?, )), #[cfg(feature = "v1")] Updateable::RefundUpdate(a) => { DBResult::Refund(Box::new(a.orig.update(conn, a.update_data).await?)) } #[cfg(feature = "v2")] Updateable::RefundUpdate(a) => { DBResult::Refund(Box::new(a.orig.update_with_id(conn, a.update_data).await?)) } Updateable::AddressUpdate(a) => { DBResult::Address(Box::new(a.orig.update(conn, a.update_data).await?)) } Updateable::PayoutsUpdate(a) => { DBResult::Payouts(Box::new(a.orig.update(conn, a.update_data).await?)) } Updateable::PayoutAttemptUpdate(a) => DBResult::PayoutAttempt(Box::new( a.orig.update_with_attempt_id(conn, a.update_data).await?, )), #[cfg(feature = "v1")] Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new( v.orig .update_with_payment_method_id(conn, v.update_data) .await?, )), #[cfg(feature = "v2")] Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new( v.orig.update_with_id(conn, v.update_data).await?, )), Updateable::MandateUpdate(m) => DBResult::Mandate(Box::new( Mandate::update_by_merchant_id_mandate_id( conn, &m.orig.merchant_id, &m.orig.mandate_id, m.update_data, ) .await?, )), #[cfg(feature = "v1")] Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new( Customer::update_by_customer_id_merchant_id( conn, cust.orig.customer_id.clone(), cust.orig.merchant_id.clone(), cust.update_data, ) .await?, )), #[cfg(feature = "v2")] Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new( Customer::update_by_id(conn, cust.orig.id, cust.update_data).await?, )), }, }) } } impl TypedSql { pub fn to_field_value_pairs( &self, request_id: String, global_id: String, ) -> crate::StorageResult<Vec<(&str, String)>> { let pushed_at = common_utils::date_time::now_unix_timestamp(); Ok(vec![ ( "typed_sql", serde_json::to_string(self) .change_context(errors::DatabaseError::QueryGenerationFailed)?, ), ("global_id", global_id), ("request_id", request_id), ("pushed_at", pushed_at.to_string()), ]) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "table", content = "data")] pub enum Insertable { PaymentIntent(Box<PaymentIntentNew>), PaymentAttempt(Box<PaymentAttemptNew>), Refund(RefundNew), Address(Box<AddressNew>), Customer(CustomerNew), ReverseLookUp(ReverseLookupNew), Payouts(PayoutsNew), PayoutAttempt(PayoutAttemptNew), PaymentMethod(PaymentMethodNew), Mandate(MandateNew), } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "table", content = "data")] pub enum Updateable { PaymentIntentUpdate(Box<PaymentIntentUpdateMems>), PaymentAttemptUpdate(Box<PaymentAttemptUpdateMems>), RefundUpdate(Box<RefundUpdateMems>), CustomerUpdate(CustomerUpdateMems), AddressUpdate(Box<AddressUpdateMems>), PayoutsUpdate(PayoutsUpdateMems), PayoutAttemptUpdate(PayoutAttemptUpdateMems), PaymentMethodUpdate(Box<PaymentMethodUpdateMems>), MandateUpdate(MandateUpdateMems), } #[derive(Debug, Serialize, Deserialize)] pub struct CustomerUpdateMems { pub orig: Customer, pub update_data: CustomerUpdateInternal, } #[derive(Debug, Serialize, Deserialize)] pub struct AddressUpdateMems { pub orig: Address, pub update_data: AddressUpdateInternal, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentIntentUpdateMems { pub orig: PaymentIntent, pub update_data: PaymentIntentUpdate, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentIntentUpdateMems { pub orig: PaymentIntent, pub update_data: PaymentIntentUpdateInternal, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentAttemptUpdateMems { pub orig: PaymentAttempt, pub update_data: PaymentAttemptUpdate, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentAttemptUpdateMems { pub orig: PaymentAttempt, pub update_data: PaymentAttemptUpdateInternal, } #[derive(Debug, Serialize, Deserialize)] pub struct RefundUpdateMems { pub orig: Refund, pub update_data: RefundUpdate, } #[derive(Debug, Serialize, Deserialize)] pub struct PayoutsUpdateMems { pub orig: Payouts, pub update_data: PayoutsUpdate, } #[derive(Debug, Serialize, Deserialize)] pub struct PayoutAttemptUpdateMems { pub orig: PayoutAttempt, pub update_data: PayoutAttemptUpdate, } #[derive(Debug, Serialize, Deserialize)] pub struct PaymentMethodUpdateMems { pub orig: PaymentMethod, pub update_data: PaymentMethodUpdateInternal, } #[derive(Debug, Serialize, Deserialize)] pub struct MandateUpdateMems { pub orig: Mandate, pub update_data: MandateUpdateInternal, }
crates/diesel_models/src/kv.rs
diesel_models::src::kv
2,544
true
// File: crates/diesel_models/src/callback_mapper.rs // Module: diesel_models::src::callback_mapper use common_enums::enums as common_enums; use common_types::callback_mapper::CallbackMapperData; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::callback_mapper; #[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)] #[diesel(table_name = callback_mapper, primary_key(id, type_), check_for_backend(diesel::pg::Pg))] pub struct CallbackMapper { pub id: String, pub type_: common_enums::CallbackMapperIdType, pub data: CallbackMapperData, pub created_at: time::PrimitiveDateTime, pub last_modified_at: time::PrimitiveDateTime, }
crates/diesel_models/src/callback_mapper.rs
diesel_models::src::callback_mapper
170
true
// File: crates/diesel_models/src/role.rs // Module: diesel_models::src::role use common_utils::id_type; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::roles}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = roles, primary_key(role_id), check_for_backend(diesel::pg::Pg))] pub struct Role { pub role_name: String, pub role_id: String, pub merchant_id: Option<id_type::MerchantId>, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, pub scope: enums::RoleScope, pub created_at: PrimitiveDateTime, pub created_by: String, pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, pub profile_id: Option<id_type::ProfileId>, pub tenant_id: id_type::TenantId, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = roles)] pub struct RoleNew { pub role_name: String, pub role_id: String, pub merchant_id: Option<id_type::MerchantId>, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, pub scope: enums::RoleScope, pub created_at: PrimitiveDateTime, pub created_by: String, pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, pub profile_id: Option<id_type::ProfileId>, pub tenant_id: id_type::TenantId, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = roles)] pub struct RoleUpdateInternal { groups: Option<Vec<enums::PermissionGroup>>, role_name: Option<String>, last_modified_by: String, last_modified_at: PrimitiveDateTime, } pub enum RoleUpdate { UpdateDetails { groups: Option<Vec<enums::PermissionGroup>>, role_name: Option<String>, last_modified_at: PrimitiveDateTime, last_modified_by: String, }, } impl From<RoleUpdate> for RoleUpdateInternal { fn from(value: RoleUpdate) -> Self { match value { RoleUpdate::UpdateDetails { groups, role_name, last_modified_by, last_modified_at, } => Self { groups, role_name, last_modified_at, last_modified_by, }, } } } #[derive(Clone, Debug)] pub enum ListRolesByEntityPayload { Profile(id_type::MerchantId, id_type::ProfileId), Merchant(id_type::MerchantId), Organization, }
crates/diesel_models/src/role.rs
diesel_models::src::role
658
true
// File: crates/diesel_models/src/types.rs // Module: diesel_models::src::types #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; #[cfg(feature = "v2")] use common_utils::id_type; use common_utils::{hashing::HashedString, pii, types::MinorUnit}; use diesel::{ sql_types::{Json, Jsonb}, AsExpression, FromSqlRow, }; use masking::{Secret, WithType}; use serde::{self, Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, FromSqlRow, AsExpression)] #[diesel(sql_type = Jsonb)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased pub product_name: String, /// The quantity of the product to be purchased pub quantity: u16, /// the amount per quantity of product pub amount: 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<common_enums::ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product pub total_tax_amount: Option<MinorUnit>, /// description of the product pub description: Option<String>, /// stock keeping unit of the product pub sku: Option<String>, /// universal product code of the product pub upc: Option<String>, /// commodity code of the product pub commodity_code: Option<String>, /// unit of measure of the product pub unit_of_measure: Option<String>, /// total amount of the product pub total_amount: Option<MinorUnit>, /// discount amount on the unit pub unit_discount_amount: Option<MinorUnit>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} common_utils::impl_to_sql_from_sql_json!(OrderDetailsWithAmount); #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)] #[diesel(sql_type = Json)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search 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 payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> { self.payment_revenue_recovery_metadata .as_ref() .map(|rrm| rrm.payment_method_subtype) } pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> { self.payment_revenue_recovery_metadata .as_ref() .map(|recovery_metadata| recovery_metadata.payment_method_type) } pub fn get_billing_merchant_connector_account_id( &self, ) -> Option<id_type::MerchantConnectorAccountId> { self.payment_revenue_recovery_metadata .as_ref() .map(|recovery_metadata| recovery_metadata.billing_connector_id.clone()) } // TODO: Check search_tags for relevant payment method type // TODO: Check redirect_response metadata if applicable // TODO: Check apple_pay_recurring_details metadata if applicable } #[cfg(feature = "v1")] #[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)] #[diesel(sql_type = Json)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// The system that the gateway is integrated with, e.g., `Direct`(through hyperswitch), `UnifiedConnectorService`(through ucs), etc. pub gateway_system: Option<common_enums::GatewaySystem>, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)] #[diesel(sql_type = Json)] 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 pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)] #[diesel(sql_type = Json)] 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 #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<time::PrimitiveDateTime>, /// The date of the final payment #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<time::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, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)] #[diesel(sql_type = Json)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } common_utils::impl_to_sql_from_sql_json!(ApplePayRecurringDetails); common_utils::impl_to_sql_from_sql_json!(ApplePayRegularBillingDetails); common_utils::impl_to_sql_from_sql_json!(RecurringPaymentIntervalUnit); common_utils::impl_to_sql_from_sql_json!(FeatureMetadata); #[derive(Default, Debug, Eq, PartialEq, Deserialize, Serialize, Clone)] pub struct RedirectResponse { pub param: Option<Secret<String>>, pub json_payload: Option<pii::SecretSerdeValue>, } impl masking::SerializableSecret for RedirectResponse {} common_utils::impl_to_sql_from_sql_json!(RedirectResponse); #[cfg(feature = "v2")] #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details pub billing_connector_payment_details: BillingConnectorPaymentDetails, ///Payment Method Type pub payment_method_type: common_enums::enums::PaymentMethod, /// PaymentMethod Subtype pub payment_method_subtype: common_enums::enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. pub connector: common_enums::connector_enums::Connector, /// Time at which next invoice will be created pub invoice_next_billing_time: Option<time::PrimitiveDateTime>, /// Time at which invoice started pub invoice_billing_started_at_time: Option<time::PrimitiveDateTime>, /// Extra Payment Method Details that are needed to be stored pub billing_connector_payment_method_details: Option<BillingConnectorPaymentMethodDetails>, /// First Payment Attempt Payment Gateway Error Code pub first_payment_attempt_pg_error_code: Option<String>, /// First Payment Attempt Network Error Code pub first_payment_attempt_network_decline_code: Option<String>, /// First Payment Attempt Network Advice Code pub first_payment_attempt_network_advice_code: Option<String>, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[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, } #[cfg(feature = "v2")] #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum BillingConnectorPaymentMethodDetails { Card(BillingConnectorAdditionalCardInfo), } #[cfg(feature = "v2")] #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct BillingConnectorAdditionalCardInfo { /// Card Network pub card_network: Option<common_enums::enums::CardNetwork>, /// Card Issuer pub card_issuer: Option<String>, }
crates/diesel_models/src/types.rs
diesel_models::src::types
2,186
true
// File: crates/diesel_models/src/payment_attempt.rs // Module: diesel_models::src::payment_attempt #[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()); } }
crates/diesel_models/src/payment_attempt.rs
diesel_models::src::payment_attempt
34,579
true
// File: crates/diesel_models/src/events.rs // Module: diesel_models::src::events 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);
crates/diesel_models/src/events.rs
diesel_models::src::events
951
true
// File: crates/diesel_models/src/organization.rs // Module: diesel_models::src::organization 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); } }
crates/diesel_models/src/organization.rs
diesel_models::src::organization
2,133
true
// File: crates/diesel_models/src/merchant_account.rs // Module: diesel_models::src::merchant_account 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, } } }
crates/diesel_models/src/merchant_account.rs
diesel_models::src::merchant_account
4,089
true
// File: crates/diesel_models/src/payouts.rs // Module: diesel_models::src::payouts 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 } } }
crates/diesel_models/src/payouts.rs
diesel_models::src::payouts
2,019
true
// File: crates/diesel_models/src/fraud_check.rs // Module: diesel_models::src::fraud_check 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() }, } } }
crates/diesel_models/src/fraud_check.rs
diesel_models::src::fraud_check
993
true
// File: crates/diesel_models/src/cards_info.rs // Module: diesel_models::src::cards_info 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>, }
crates/diesel_models/src/cards_info.rs
diesel_models::src::cards_info
378
true
// File: crates/diesel_models/src/payment_method.rs // Module: diesel_models::src::payment_method 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, } } }
crates/diesel_models/src/payment_method.rs
diesel_models::src::payment_method
10,193
true
// File: crates/diesel_models/src/merchant_connector_account.rs // Module: diesel_models::src::merchant_connector_account #[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>);
crates/diesel_models/src/merchant_connector_account.rs
diesel_models::src::merchant_connector_account
3,065
true
// File: crates/diesel_models/src/configs.rs // Module: diesel_models::src::configs 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, } } }
crates/diesel_models/src/configs.rs
diesel_models::src::configs
332
true
// File: crates/diesel_models/src/blocklist_fingerprint.rs // Module: diesel_models::src::blocklist_fingerprint 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, }
crates/diesel_models/src/blocklist_fingerprint.rs
diesel_models::src::blocklist_fingerprint
266
true
// File: crates/diesel_models/src/lib.rs // Module: diesel_models::src::lib pub mod address; pub mod api_keys; pub mod blocklist_lookup; pub mod business_profile; pub mod capture; pub mod cards_info; pub mod configs; pub mod authentication; pub mod authorization; pub mod blocklist; pub mod blocklist_fingerprint; pub mod callback_mapper; pub mod customers; pub mod dispute; pub mod dynamic_routing_stats; pub mod enums; pub mod ephemeral_key; pub mod errors; pub mod events; pub mod file; #[allow(unused)] pub mod fraud_check; pub mod generic_link; pub mod gsm; pub mod hyperswitch_ai_interaction; pub mod invoice; #[cfg(feature = "kv_store")] pub mod kv; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; pub mod organization; pub mod payment_attempt; pub mod payment_intent; pub mod payment_link; pub mod payment_method; pub mod payout_attempt; pub mod payouts; pub mod process_tracker; pub mod query; pub mod refund; pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; pub mod subscription; pub mod types; pub mod unified_translations; #[cfg(feature = "v2")] pub mod payment_methods_session; #[allow(unused_qualifications)] pub mod schema; #[allow(unused_qualifications)] pub mod schema_v2; pub mod user; pub mod user_authentication_method; pub mod user_key_store; pub mod user_role; use diesel_impl::{DieselArray, OptionalDieselArray}; #[cfg(feature = "v2")] use diesel_impl::{RequiredFromNullable, RequiredFromNullableWithDefault}; pub type StorageResult<T> = error_stack::Result<T, errors::DatabaseError>; pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>; pub use self::{ address::*, api_keys::*, callback_mapper::*, cards_info::*, configs::*, customers::*, dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*, hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, payment_attempt::*, payment_intent::*, payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, refund::*, reverse_lookup::*, user_authentication_method::*, }; /// The types and implementations provided by this module are required for the schema generated by /// `diesel_cli` 2.0 to work with the types defined in Rust code. This is because /// [`diesel`][diesel] 2.0 [changed the nullability of array elements][diesel-2.0-array-nullability], /// which causes [`diesel`][diesel] to deserialize arrays as `Vec<Option<T>>`. To prevent declaring /// array elements as `Option<T>`, this module provides types and implementations to deserialize /// arrays as `Vec<T>`, considering only non-null values (`Some(T)`) among the deserialized /// `Option<T>` values. /// /// [diesel-2.0-array-nullability]: https://diesel.rs/guides/migration_guide.html#2-0-0-nullability-of-array-elements #[doc(hidden)] pub(crate) mod diesel_impl { #[cfg(feature = "v2")] use common_utils::{id_type, types}; use diesel::{ deserialize::FromSql, pg::Pg, sql_types::{Array, Nullable}, Queryable, }; #[cfg(feature = "v2")] use crate::enums; pub struct DieselArray<T>(Vec<Option<T>>); impl<T> From<DieselArray<T>> for Vec<T> { fn from(array: DieselArray<T>) -> Self { array.0.into_iter().flatten().collect() } } impl<T, U> Queryable<Array<Nullable<U>>, Pg> for DieselArray<T> where T: FromSql<U, Pg>, Vec<Option<T>>: FromSql<Array<Nullable<U>>, Pg>, { type Row = Vec<Option<T>>; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { Ok(Self(row)) } } pub struct OptionalDieselArray<T>(Option<Vec<Option<T>>>); impl<T> From<OptionalDieselArray<T>> for Option<Vec<T>> { fn from(option_array: OptionalDieselArray<T>) -> Self { option_array .0 .map(|array| array.into_iter().flatten().collect()) } } impl<T, U> Queryable<Nullable<Array<Nullable<U>>>, Pg> for OptionalDieselArray<T> where Option<Vec<Option<T>>>: FromSql<Nullable<Array<Nullable<U>>>, Pg>, { type Row = Option<Vec<Option<T>>>; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { Ok(Self(row)) } } #[cfg(feature = "v2")] /// If the DB value is null, this wrapper will return an error when deserializing. /// /// This is useful when you want to ensure that a field is always present, even if the database /// value is NULL. If the database column contains a NULL value, an error will be returned. pub struct RequiredFromNullable<T>(T); #[cfg(feature = "v2")] impl<T> RequiredFromNullable<T> { /// Extracts the inner value from the wrapper pub fn into_inner(self) -> T { self.0 } } #[cfg(feature = "v2")] impl<T, ST, DB> Queryable<Nullable<ST>, DB> for RequiredFromNullable<T> where DB: diesel::backend::Backend, T: Queryable<ST, DB>, Option<T::Row>: FromSql<Nullable<ST>, DB>, ST: diesel::sql_types::SingleValue, { type Row = Option<T::Row>; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { match row { Some(inner_row) => { let value = T::build(inner_row)?; Ok(Self(value)) } None => Err("Cannot deserialize NULL value for required field. Check if the database column that should not be NULL contains a NULL value.".into()), } } } #[cfg(feature = "v2")] /// If the DB value is null, this wrapper will provide a default value for the type `T`. /// /// This is useful when you want to ensure that a field is always present, even if the database /// value is NULL. The default value is provided by the `Default` trait implementation of `T`. pub struct RequiredFromNullableWithDefault<T>(T); #[cfg(feature = "v2")] impl<T> RequiredFromNullableWithDefault<T> { /// Extracts the inner value from the wrapper pub fn into_inner(self) -> T { self.0 } } #[cfg(feature = "v2")] impl<T, ST, DB> Queryable<Nullable<ST>, DB> for RequiredFromNullableWithDefault<T> where DB: diesel::backend::Backend, T: Queryable<ST, DB>, T: Default, Option<T::Row>: FromSql<Nullable<ST>, DB>, ST: diesel::sql_types::SingleValue, { type Row = Option<T::Row>; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { match row { Some(inner_row) => { let value = T::build(inner_row)?; Ok(Self(value)) } None => Ok(Self(T::default())), } } } #[cfg(feature = "v2")] /// Macro to implement From trait for types wrapped in RequiredFromNullable #[macro_export] macro_rules! impl_from_required_from_nullable { ($($type:ty),* $(,)?) => { $( impl From<$crate::RequiredFromNullable<$type>> for $type { fn from(wrapper: $crate::RequiredFromNullable<$type>) -> Self { wrapper.into_inner() } } )* }; } #[cfg(feature = "v2")] /// Macro to implement From trait for types wrapped in RequiredFromNullableWithDefault #[macro_export] macro_rules! impl_from_required_from_nullable_with_default { ($($type:ty),* $(,)?) => { $( impl From<$crate::RequiredFromNullableWithDefault<$type>> for $type { fn from(wrapper: $crate::RequiredFromNullableWithDefault<$type>) -> Self { wrapper.into_inner() } } )* }; } #[cfg(feature = "v2")] crate::impl_from_required_from_nullable_with_default!(enums::DeleteStatus); #[cfg(feature = "v2")] crate::impl_from_required_from_nullable!( enums::AuthenticationType, types::MinorUnit, enums::PaymentMethod, enums::Currency, id_type::ProfileId, time::PrimitiveDateTime, id_type::RefundReferenceId, ); } pub(crate) mod metrics { use router_env::{counter_metric, global_meter, histogram_metric_f64}; global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(DATABASE_CALLS_COUNT, GLOBAL_METER); histogram_metric_f64!(DATABASE_CALL_TIME, GLOBAL_METER); } #[cfg(feature = "tokenization_v2")] pub mod tokenization;
crates/diesel_models/src/lib.rs
diesel_models::src::lib
2,051
true
// File: crates/diesel_models/src/routing_algorithm.rs // Module: diesel_models::src::routing_algorithm 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) } }
crates/diesel_models/src/routing_algorithm.rs
diesel_models::src::routing_algorithm
437
true
// File: crates/diesel_models/src/query.rs // Module: diesel_models::src::query pub mod address; pub mod api_keys; pub mod blocklist_lookup; pub mod business_profile; mod capture; pub mod cards_info; pub mod configs; pub mod authentication; pub mod authorization; pub mod blocklist; pub mod blocklist_fingerprint; pub mod callback_mapper; pub mod customers; pub mod dashboard_metadata; pub mod dispute; pub mod dynamic_routing_stats; pub mod events; pub mod file; pub mod fraud_check; pub mod generic_link; pub mod generics; pub mod gsm; pub mod hyperswitch_ai_interaction; pub mod invoice; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; pub mod organization; pub mod payment_attempt; pub mod payment_intent; pub mod payment_link; pub mod payment_method; pub mod payout_attempt; pub mod payouts; pub mod process_tracker; pub mod refund; pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; pub mod subscription; #[cfg(feature = "tokenization_v2")] pub mod tokenization; pub mod unified_translations; pub mod user; pub mod user_authentication_method; pub mod user_key_store; pub mod user_role; mod utils;
crates/diesel_models/src/query.rs
diesel_models::src::query
271
true
// File: crates/diesel_models/src/subscription.rs // Module: diesel_models::src::subscription 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, } } }
crates/diesel_models/src/subscription.rs
diesel_models::src::subscription
994
true
// File: crates/diesel_models/src/address.rs // Module: diesel_models::src::address 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 } } }
crates/diesel_models/src/address.rs
diesel_models::src::address
979
true
// File: crates/diesel_models/src/blocklist_lookup.rs // Module: diesel_models::src::blocklist_lookup 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, }
crates/diesel_models/src/blocklist_lookup.rs
diesel_models::src::blocklist_lookup
205
true
// File: crates/diesel_models/src/enums.rs // Module: diesel_models::src::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, }
crates/diesel_models/src/enums.rs
diesel_models::src::enums
1,893
true
// File: crates/diesel_models/src/blocklist.rs // Module: diesel_models::src::blocklist 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, }
crates/diesel_models/src/blocklist.rs
diesel_models::src::blocklist
258
true
// File: crates/diesel_models/src/user.rs // Module: diesel_models::src::user 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), }, } } }
crates/diesel_models/src/user.rs
diesel_models::src::user
1,069
true
// File: crates/diesel_models/src/user_role.rs // Module: diesel_models::src::user_role 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, }, } } }
crates/diesel_models/src/user_role.rs
diesel_models::src::user_role
1,061
true
// File: crates/diesel_models/src/locker_mock_up.rs // Module: diesel_models::src::locker_mock_up 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>, }
crates/diesel_models/src/locker_mock_up.rs
diesel_models::src::locker_mock_up
397
true
// File: crates/diesel_models/src/refund.rs // Module: diesel_models::src::refund 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()); } }
crates/diesel_models/src/refund.rs
diesel_models::src::refund
6,722
true
// File: crates/diesel_models/src/process_tracker.rs // Module: diesel_models::src::process_tracker 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"; }
crates/diesel_models/src/process_tracker.rs
diesel_models::src::process_tracker
2,433
true
// File: crates/diesel_models/src/mod.rs // Module: diesel_models::src::mod #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub mod tokenization;
crates/diesel_models/src/mod.rs
diesel_models::src::mod
45
true
// File: crates/diesel_models/src/business_profile.rs // Module: diesel_models::src::business_profile 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);
crates/diesel_models/src/business_profile.rs
diesel_models::src::business_profile
9,806
true
// File: crates/diesel_models/src/payment_link.rs // Module: diesel_models::src::payment_link 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>, }
crates/diesel_models/src/payment_link.rs
diesel_models::src::payment_link
597
true
// File: crates/diesel_models/src/invoice.rs // Module: diesel_models::src::invoice 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, } } }
crates/diesel_models/src/invoice.rs
diesel_models::src::invoice
1,053
true
// File: crates/diesel_models/src/schema.rs // Module: diesel_models::src::schema // @generated automatically by Diesel CLI. diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; address (address_id) { #[max_length = 64] address_id -> Varchar, #[max_length = 128] city -> Nullable<Varchar>, country -> Nullable<CountryAlpha2>, line1 -> Nullable<Bytea>, line2 -> Nullable<Bytea>, line3 -> Nullable<Bytea>, state -> Nullable<Bytea>, zip -> Nullable<Bytea>, first_name -> Nullable<Bytea>, last_name -> Nullable<Bytea>, phone_number -> Nullable<Bytea>, #[max_length = 8] country_code -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, email -> Nullable<Bytea>, origin_zip -> Nullable<Bytea>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; api_keys (key_id) { #[max_length = 64] key_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, #[max_length = 128] hashed_api_key -> Varchar, #[max_length = 16] prefix -> Varchar, created_at -> Timestamp, expires_at -> Nullable<Timestamp>, last_used -> Nullable<Timestamp>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; authentication (authentication_id) { #[max_length = 64] authentication_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] authentication_connector -> Nullable<Varchar>, #[max_length = 64] connector_authentication_id -> Nullable<Varchar>, authentication_data -> Nullable<Jsonb>, #[max_length = 64] payment_method_id -> Varchar, #[max_length = 64] authentication_type -> Nullable<Varchar>, #[max_length = 64] authentication_status -> Varchar, #[max_length = 64] authentication_lifecycle_status -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, maximum_supported_version -> Nullable<Jsonb>, #[max_length = 64] threeds_server_transaction_id -> Nullable<Varchar>, #[max_length = 64] cavv -> Nullable<Varchar>, #[max_length = 64] authentication_flow_type -> Nullable<Varchar>, message_version -> Nullable<Jsonb>, #[max_length = 64] eci -> Nullable<Varchar>, #[max_length = 64] trans_status -> Nullable<Varchar>, #[max_length = 64] acquirer_bin -> Nullable<Varchar>, #[max_length = 64] acquirer_merchant_id -> Nullable<Varchar>, three_ds_method_data -> Nullable<Varchar>, three_ds_method_url -> Nullable<Varchar>, acs_url -> Nullable<Varchar>, challenge_request -> Nullable<Varchar>, acs_reference_number -> Nullable<Varchar>, acs_trans_id -> Nullable<Varchar>, acs_signed_content -> Nullable<Varchar>, #[max_length = 64] profile_id -> Varchar, #[max_length = 255] payment_id -> Nullable<Varchar>, #[max_length = 128] merchant_connector_id -> Nullable<Varchar>, #[max_length = 64] ds_trans_id -> Nullable<Varchar>, #[max_length = 128] directory_server_id -> Nullable<Varchar>, #[max_length = 64] acquirer_country_code -> Nullable<Varchar>, service_details -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, #[max_length = 128] authentication_client_secret -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, #[max_length = 2048] return_url -> Nullable<Varchar>, amount -> Nullable<Int8>, currency -> Nullable<Currency>, billing_address -> Nullable<Bytea>, shipping_address -> Nullable<Bytea>, browser_info -> Nullable<Jsonb>, email -> Nullable<Bytea>, #[max_length = 128] profile_acquirer_id -> Nullable<Varchar>, challenge_code -> Nullable<Varchar>, challenge_cancel -> Nullable<Varchar>, challenge_code_reason -> Nullable<Varchar>, message_extension -> Nullable<Jsonb>, #[max_length = 255] challenge_request_key -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist (merchant_id, fingerprint_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, metadata -> Nullable<Jsonb>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_fingerprint (merchant_id, fingerprint_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, encrypted_fingerprint -> Text, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_lookup (merchant_id, fingerprint) { #[max_length = 64] merchant_id -> Varchar, fingerprint -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; business_profile (profile_id) { #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_name -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, return_url -> Nullable<Text>, enable_payment_response_hash -> Bool, #[max_length = 255] payment_response_hash_key -> Nullable<Varchar>, redirect_to_merchant_with_http_post -> Bool, webhook_details -> Nullable<Json>, metadata -> Nullable<Json>, routing_algorithm -> Nullable<Json>, intent_fulfillment_time -> Nullable<Int8>, frm_routing_algorithm -> Nullable<Jsonb>, payout_routing_algorithm -> Nullable<Jsonb>, is_recon_enabled -> Bool, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, payment_link_config -> Nullable<Jsonb>, session_expiry -> Nullable<Int8>, authentication_connector_details -> Nullable<Jsonb>, payout_link_config -> Nullable<Jsonb>, is_extended_card_info_enabled -> Nullable<Bool>, extended_card_info_config -> Nullable<Jsonb>, is_connector_agnostic_mit_enabled -> Nullable<Bool>, use_billing_as_payment_method_billing -> Nullable<Bool>, collect_shipping_details_from_wallet_connector -> Nullable<Bool>, collect_billing_details_from_wallet_connector -> Nullable<Bool>, outgoing_webhook_custom_http_headers -> Nullable<Bytea>, always_collect_billing_details_from_wallet_connector -> Nullable<Bool>, always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>, #[max_length = 64] tax_connector_id -> Nullable<Varchar>, is_tax_connector_enabled -> Nullable<Bool>, version -> ApiVersion, dynamic_routing_algorithm -> Nullable<Json>, is_network_tokenization_enabled -> Bool, is_auto_retries_enabled -> Nullable<Bool>, max_auto_retries_enabled -> Nullable<Int2>, always_request_extended_authorization -> Nullable<Bool>, is_click_to_pay_enabled -> Bool, authentication_product_ids -> Nullable<Jsonb>, card_testing_guard_config -> Nullable<Jsonb>, card_testing_secret_key -> Nullable<Bytea>, is_clear_pan_retries_enabled -> Bool, force_3ds_challenge -> Nullable<Bool>, is_debit_routing_enabled -> Bool, merchant_business_country -> Nullable<CountryAlpha2>, #[max_length = 64] id -> Nullable<Varchar>, is_iframe_redirection_enabled -> Nullable<Bool>, is_pre_network_tokenization_enabled -> Nullable<Bool>, three_ds_decision_rule_algorithm -> Nullable<Jsonb>, acquirer_config_map -> Nullable<Jsonb>, #[max_length = 16] merchant_category_code -> Nullable<Varchar>, #[max_length = 32] merchant_country_code -> Nullable<Varchar>, dispute_polling_interval -> Nullable<Int4>, is_manual_retry_enabled -> Nullable<Bool>, always_enable_overcapture -> Nullable<Bool>, #[max_length = 64] billing_processor_id -> Nullable<Varchar>, is_external_vault_enabled -> Nullable<Bool>, external_vault_connector_details -> Nullable<Jsonb>, is_l2_l3_enabled -> Nullable<Bool>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; callback_mapper (id, type_) { #[max_length = 128] id -> Varchar, #[sql_name = "type"] #[max_length = 64] type_ -> Varchar, data -> Jsonb, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; captures (capture_id) { #[max_length = 64] capture_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> CaptureStatus, amount -> Int8, currency -> Nullable<Currency>, #[max_length = 255] connector -> Varchar, #[max_length = 255] error_message -> Nullable<Varchar>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 255] error_reason -> Nullable<Varchar>, tax_amount -> Nullable<Int8>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] authorized_attempt_id -> Varchar, #[max_length = 128] connector_capture_id -> Nullable<Varchar>, capture_sequence -> Int2, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, #[max_length = 512] connector_capture_data -> Nullable<Varchar>, processor_capture_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; cards_info (card_iin) { #[max_length = 16] card_iin -> Varchar, card_issuer -> Nullable<Text>, card_network -> Nullable<Text>, card_type -> Nullable<Text>, card_subtype -> Nullable<Text>, card_issuing_country -> Nullable<Text>, #[max_length = 32] bank_code_id -> Nullable<Varchar>, #[max_length = 32] bank_code -> Nullable<Varchar>, #[max_length = 32] country_code -> Nullable<Varchar>, date_created -> Timestamp, last_updated -> Nullable<Timestamp>, last_updated_provider -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; configs (key) { #[max_length = 255] key -> Varchar, config -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; customers (customer_id, merchant_id) { #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, name -> Nullable<Bytea>, email -> Nullable<Bytea>, phone -> Nullable<Bytea>, #[max_length = 8] phone_country_code -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, created_at -> Timestamp, metadata -> Nullable<Json>, connector_customer -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] address_id -> Nullable<Varchar>, #[max_length = 64] default_payment_method_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, tax_registration_id -> Nullable<Bytea>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dashboard_metadata (id) { id -> Int4, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] org_id -> Varchar, data_key -> DashboardMetadata, data_value -> Json, #[max_length = 64] created_by -> Varchar, created_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dispute (dispute_id) { #[max_length = 64] dispute_id -> Varchar, #[max_length = 255] amount -> Varchar, #[max_length = 255] currency -> Varchar, dispute_stage -> DisputeStage, dispute_status -> DisputeStatus, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] connector_status -> Varchar, #[max_length = 255] connector_dispute_id -> Varchar, #[max_length = 255] connector_reason -> Nullable<Varchar>, #[max_length = 255] connector_reason_code -> Nullable<Varchar>, challenge_required_by -> Nullable<Timestamp>, connector_created_at -> Nullable<Timestamp>, connector_updated_at -> Nullable<Timestamp>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] connector -> Varchar, evidence -> Jsonb, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, dispute_amount -> Int8, #[max_length = 32] organization_id -> Varchar, dispute_currency -> Nullable<Currency>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dynamic_routing_stats (attempt_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_id -> Varchar, amount -> Int8, #[max_length = 64] success_based_routing_connector -> Varchar, #[max_length = 64] payment_connector -> Varchar, currency -> Nullable<Currency>, #[max_length = 64] payment_method -> Nullable<Varchar>, capture_method -> Nullable<CaptureMethod>, authentication_type -> Nullable<AuthenticationType>, payment_status -> AttemptStatus, conclusive_classification -> SuccessBasedRoutingConclusiveState, created_at -> Timestamp, #[max_length = 64] payment_method_type -> Nullable<Varchar>, #[max_length = 64] global_success_based_connector -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; events (event_id) { #[max_length = 64] event_id -> Varchar, event_type -> EventType, event_class -> EventClass, is_webhook_notified -> Bool, #[max_length = 64] primary_object_id -> Varchar, primary_object_type -> EventObjectType, created_at -> Timestamp, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] business_profile_id -> Nullable<Varchar>, primary_object_created_at -> Nullable<Timestamp>, #[max_length = 64] idempotent_event_id -> Nullable<Varchar>, #[max_length = 64] initial_attempt_id -> Nullable<Varchar>, request -> Nullable<Bytea>, response -> Nullable<Bytea>, delivery_attempt -> Nullable<WebhookDeliveryAttempt>, metadata -> Nullable<Jsonb>, is_overall_delivery_successful -> Nullable<Bool>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; file_metadata (file_id, merchant_id) { #[max_length = 64] file_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] file_name -> Nullable<Varchar>, file_size -> Int4, #[max_length = 255] file_type -> Varchar, #[max_length = 255] provider_file_id -> Nullable<Varchar>, #[max_length = 255] file_upload_provider -> Nullable<Varchar>, available -> Bool, created_at -> Timestamp, #[max_length = 255] connector_label -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; fraud_check (frm_id, attempt_id, payment_id, merchant_id) { #[max_length = 64] frm_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, created_at -> Timestamp, #[max_length = 255] frm_name -> Varchar, #[max_length = 255] frm_transaction_id -> Nullable<Varchar>, frm_transaction_type -> FraudCheckType, frm_status -> FraudCheckStatus, frm_score -> Nullable<Int4>, frm_reason -> Nullable<Jsonb>, #[max_length = 255] frm_error -> Nullable<Varchar>, payment_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] last_step -> Varchar, payment_capture_method -> Nullable<CaptureMethod>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; gateway_status_map (connector, flow, sub_flow, code, message) { #[max_length = 64] connector -> Varchar, #[max_length = 64] flow -> Varchar, #[max_length = 64] sub_flow -> Varchar, #[max_length = 255] code -> Varchar, #[max_length = 1024] message -> Varchar, #[max_length = 64] status -> Varchar, #[max_length = 64] router_error -> Nullable<Varchar>, #[max_length = 64] decision -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, step_up_possible -> Bool, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, #[max_length = 64] error_category -> Nullable<Varchar>, clear_pan_possible -> Bool, feature_data -> Nullable<Jsonb>, #[max_length = 64] feature -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; generic_link (link_id) { #[max_length = 64] link_id -> Varchar, #[max_length = 64] primary_reference -> Varchar, #[max_length = 64] merchant_id -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, expiry -> Timestamp, link_data -> Jsonb, link_status -> Jsonb, link_type -> GenericLinkType, url -> Text, return_url -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; hyperswitch_ai_interaction (id, created_at) { #[max_length = 64] id -> Varchar, #[max_length = 64] session_id -> Nullable<Varchar>, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Nullable<Varchar>, user_query -> Nullable<Bytea>, response -> Nullable<Bytea>, database_query -> Nullable<Text>, #[max_length = 64] interaction_status -> Nullable<Varchar>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; hyperswitch_ai_interaction_default (id, created_at) { #[max_length = 64] id -> Varchar, #[max_length = 64] session_id -> Nullable<Varchar>, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Nullable<Varchar>, user_query -> Nullable<Bytea>, response -> Nullable<Bytea>, database_query -> Nullable<Text>, #[max_length = 64] interaction_status -> Nullable<Varchar>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; incremental_authorization (authorization_id, merchant_id) { #[max_length = 64] authorization_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Varchar, amount -> Int8, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] status -> Varchar, #[max_length = 255] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, #[max_length = 64] connector_authorization_id -> Nullable<Varchar>, previously_authorized_amount -> Int8, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; invoice (id) { #[max_length = 64] id -> Varchar, #[max_length = 128] subscription_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 128] merchant_connector_id -> Varchar, #[max_length = 64] payment_intent_id -> Nullable<Varchar>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, #[max_length = 64] customer_id -> Varchar, amount -> Int8, #[max_length = 3] currency -> Varchar, #[max_length = 64] status -> Varchar, #[max_length = 128] provider_name -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] connector_invoice_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; locker_mock_up (card_id) { #[max_length = 255] card_id -> Varchar, #[max_length = 255] external_id -> Varchar, #[max_length = 255] card_fingerprint -> Varchar, #[max_length = 255] card_global_fingerprint -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] card_number -> Varchar, #[max_length = 255] card_exp_year -> Varchar, #[max_length = 255] card_exp_month -> Varchar, #[max_length = 255] name_on_card -> Nullable<Varchar>, #[max_length = 255] nickname -> Nullable<Varchar>, #[max_length = 255] customer_id -> Nullable<Varchar>, duplicate -> Nullable<Bool>, #[max_length = 8] card_cvc -> Nullable<Varchar>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, enc_card_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; mandate (mandate_id) { #[max_length = 64] mandate_id -> Varchar, #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_method_id -> Varchar, mandate_status -> MandateStatus, mandate_type -> MandateType, customer_accepted_at -> Nullable<Timestamp>, #[max_length = 64] customer_ip_address -> Nullable<Varchar>, #[max_length = 255] customer_user_agent -> Nullable<Varchar>, #[max_length = 128] network_transaction_id -> Nullable<Varchar>, #[max_length = 64] previous_attempt_id -> Nullable<Varchar>, created_at -> Timestamp, mandate_amount -> Nullable<Int8>, mandate_currency -> Nullable<Currency>, amount_captured -> Nullable<Int8>, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_mandate_id -> Nullable<Varchar>, start_date -> Nullable<Timestamp>, end_date -> Nullable<Timestamp>, metadata -> Nullable<Jsonb>, connector_mandate_ids -> Nullable<Jsonb>, #[max_length = 64] original_payment_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, #[max_length = 2048] customer_user_agent_extended -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_account (merchant_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 255] return_url -> Nullable<Varchar>, enable_payment_response_hash -> Bool, #[max_length = 255] payment_response_hash_key -> Nullable<Varchar>, redirect_to_merchant_with_http_post -> Bool, merchant_name -> Nullable<Bytea>, merchant_details -> Nullable<Bytea>, webhook_details -> Nullable<Json>, sub_merchants_enabled -> Nullable<Bool>, #[max_length = 64] parent_merchant_id -> Nullable<Varchar>, #[max_length = 128] publishable_key -> Nullable<Varchar>, storage_scheme -> MerchantStorageScheme, #[max_length = 64] locker_id -> Nullable<Varchar>, metadata -> Nullable<Jsonb>, routing_algorithm -> Nullable<Json>, primary_business_details -> Json, intent_fulfillment_time -> Nullable<Int8>, created_at -> Timestamp, modified_at -> Timestamp, frm_routing_algorithm -> Nullable<Jsonb>, payout_routing_algorithm -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, is_recon_enabled -> Bool, #[max_length = 64] default_profile -> Nullable<Varchar>, recon_status -> ReconStatus, payment_link_config -> Nullable<Jsonb>, pm_collect_link_config -> Nullable<Jsonb>, version -> ApiVersion, is_platform_account -> Bool, #[max_length = 64] id -> Nullable<Varchar>, #[max_length = 64] product_type -> Nullable<Varchar>, #[max_length = 64] merchant_account_type -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_connector_account (merchant_connector_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] connector_name -> Varchar, connector_account_details -> Bytea, test_mode -> Nullable<Bool>, disabled -> Nullable<Bool>, #[max_length = 128] merchant_connector_id -> Varchar, payment_methods_enabled -> Nullable<Array<Nullable<Json>>>, connector_type -> ConnectorType, metadata -> Nullable<Jsonb>, #[max_length = 255] connector_label -> Nullable<Varchar>, business_country -> Nullable<CountryAlpha2>, #[max_length = 255] business_label -> Nullable<Varchar>, #[max_length = 64] business_sub_label -> Nullable<Varchar>, frm_configs -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, connector_webhook_details -> Nullable<Jsonb>, frm_config -> Nullable<Array<Nullable<Jsonb>>>, #[max_length = 64] profile_id -> Nullable<Varchar>, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, pm_auth_config -> Nullable<Jsonb>, status -> ConnectorStatus, additional_merchant_data -> Nullable<Bytea>, connector_wallets_details -> Nullable<Bytea>, version -> ApiVersion, #[max_length = 64] id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_key_store (merchant_id) { #[max_length = 64] merchant_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; organization (org_id) { #[max_length = 32] org_id -> Varchar, org_name -> Nullable<Text>, organization_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 32] id -> Nullable<Varchar>, organization_name -> Nullable<Text>, version -> ApiVersion, #[max_length = 64] organization_type -> Nullable<Varchar>, #[max_length = 64] platform_merchant_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_attempt (attempt_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, status -> AttemptStatus, amount -> Int8, currency -> Nullable<Currency>, save_to_locker -> Nullable<Bool>, #[max_length = 64] connector -> Nullable<Varchar>, error_message -> Nullable<Text>, offer_amount -> Nullable<Int8>, surcharge_amount -> Nullable<Int8>, tax_amount -> Nullable<Int8>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, payment_method -> Nullable<Varchar>, #[max_length = 128] connector_transaction_id -> Nullable<Varchar>, capture_method -> Nullable<CaptureMethod>, capture_on -> Nullable<Timestamp>, confirm -> Bool, authentication_type -> Nullable<AuthenticationType>, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, #[max_length = 255] cancellation_reason -> Nullable<Varchar>, amount_to_capture -> Nullable<Int8>, #[max_length = 64] mandate_id -> Nullable<Varchar>, browser_info -> Nullable<Jsonb>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 128] payment_token -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, #[max_length = 50] payment_experience -> Nullable<Varchar>, #[max_length = 64] payment_method_type -> Nullable<Varchar>, payment_method_data -> Nullable<Jsonb>, #[max_length = 64] business_sub_label -> Nullable<Varchar>, straight_through_algorithm -> Nullable<Jsonb>, preprocessing_step_id -> Nullable<Varchar>, mandate_details -> Nullable<Jsonb>, error_reason -> Nullable<Text>, multiple_capture_count -> Nullable<Int2>, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, amount_capturable -> Int8, #[max_length = 32] updated_by -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, authentication_data -> Nullable<Json>, encoded_data -> Nullable<Text>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, net_amount -> Nullable<Int8>, external_three_ds_authentication_attempted -> Nullable<Bool>, #[max_length = 64] authentication_connector -> Nullable<Varchar>, #[max_length = 64] authentication_id -> Nullable<Varchar>, mandate_data -> Nullable<Jsonb>, #[max_length = 64] fingerprint_id -> Nullable<Varchar>, #[max_length = 64] payment_method_billing_address_id -> Nullable<Varchar>, #[max_length = 64] charge_id -> Nullable<Varchar>, #[max_length = 64] client_source -> Nullable<Varchar>, #[max_length = 64] client_version -> Nullable<Varchar>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] organization_id -> Varchar, #[max_length = 32] card_network -> Nullable<Varchar>, shipping_cost -> Nullable<Int8>, order_tax_amount -> Nullable<Int8>, #[max_length = 512] connector_transaction_data -> Nullable<Varchar>, connector_mandate_detail -> Nullable<Jsonb>, request_extended_authorization -> Nullable<Bool>, extended_authorization_applied -> Nullable<Bool>, capture_before -> Nullable<Timestamp>, processor_transaction_data -> Nullable<Text>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, #[max_length = 64] issuer_error_code -> Nullable<Varchar>, issuer_error_message -> Nullable<Text>, #[max_length = 64] processor_merchant_id -> Nullable<Varchar>, #[max_length = 255] created_by -> Nullable<Varchar>, setup_future_usage_applied -> Nullable<FutureUsage>, routing_approach -> Nullable<RoutingApproach>, #[max_length = 255] connector_request_reference_id -> Nullable<Varchar>, #[max_length = 255] network_transaction_id -> Nullable<Varchar>, is_overcapture_enabled -> Nullable<Bool>, network_details -> Nullable<Jsonb>, is_stored_credential -> Nullable<Bool>, authorized_amount -> Nullable<Int8>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_intent (payment_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> IntentStatus, amount -> Int8, currency -> Nullable<Currency>, amount_captured -> Nullable<Int8>, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 255] return_url -> Nullable<Varchar>, metadata -> Nullable<Jsonb>, #[max_length = 64] connector_id -> Nullable<Varchar>, #[max_length = 64] shipping_address_id -> Nullable<Varchar>, #[max_length = 64] billing_address_id -> Nullable<Varchar>, #[max_length = 255] statement_descriptor_name -> Nullable<Varchar>, #[max_length = 255] statement_descriptor_suffix -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, setup_future_usage -> Nullable<FutureUsage>, off_session -> Nullable<Bool>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 64] active_attempt_id -> Varchar, business_country -> Nullable<CountryAlpha2>, #[max_length = 64] business_label -> Nullable<Varchar>, order_details -> Nullable<Array<Nullable<Jsonb>>>, allowed_payment_method_types -> Nullable<Json>, connector_metadata -> Nullable<Json>, feature_metadata -> Nullable<Json>, attempt_count -> Int2, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] merchant_decision -> Nullable<Varchar>, #[max_length = 255] payment_link_id -> Nullable<Varchar>, payment_confirm_source -> Nullable<PaymentSource>, #[max_length = 32] updated_by -> Varchar, surcharge_applicable -> Nullable<Bool>, request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>, incremental_authorization_allowed -> Nullable<Bool>, authorization_count -> Nullable<Int4>, session_expiry -> Nullable<Timestamp>, #[max_length = 64] fingerprint_id -> Nullable<Varchar>, request_external_three_ds_authentication -> Nullable<Bool>, charges -> Nullable<Jsonb>, frm_metadata -> Nullable<Jsonb>, customer_details -> Nullable<Bytea>, billing_details -> Nullable<Bytea>, #[max_length = 255] merchant_order_reference_id -> Nullable<Varchar>, shipping_details -> Nullable<Bytea>, is_payment_processor_token_flow -> Nullable<Bool>, shipping_cost -> Nullable<Int8>, #[max_length = 32] organization_id -> Varchar, tax_details -> Nullable<Jsonb>, skip_external_tax_calculation -> Nullable<Bool>, request_extended_authorization -> Nullable<Bool>, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, split_payments -> Nullable<Jsonb>, #[max_length = 64] platform_merchant_id -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, force_3ds_challenge_trigger -> Nullable<Bool>, #[max_length = 64] processor_merchant_id -> Nullable<Varchar>, #[max_length = 255] created_by -> Nullable<Varchar>, is_iframe_redirection_enabled -> Nullable<Bool>, #[max_length = 2048] extended_return_url -> Nullable<Varchar>, is_payment_id_from_merchant -> Nullable<Bool>, #[max_length = 64] payment_channel -> Nullable<Varchar>, tax_status -> Nullable<Varchar>, discount_amount -> Nullable<Int8>, shipping_amount_tax -> Nullable<Int8>, duty_amount -> Nullable<Int8>, order_date -> Nullable<Timestamp>, enable_partial_authorization -> Nullable<Bool>, enable_overcapture -> Nullable<Bool>, #[max_length = 64] mit_category -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_link (payment_link_id) { #[max_length = 255] payment_link_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 255] link_to_pay -> Varchar, #[max_length = 64] merchant_id -> Varchar, amount -> Int8, currency -> Nullable<Currency>, created_at -> Timestamp, last_modified_at -> Timestamp, fulfilment_time -> Nullable<Timestamp>, #[max_length = 64] custom_merchant_name -> Nullable<Varchar>, payment_link_config -> Nullable<Jsonb>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 255] secure_link -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_methods (payment_method_id) { #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_method_id -> Varchar, accepted_currency -> Nullable<Array<Nullable<Currency>>>, #[max_length = 32] scheme -> Nullable<Varchar>, #[max_length = 128] token -> Nullable<Varchar>, #[max_length = 255] cardholder_name -> Nullable<Varchar>, #[max_length = 64] issuer_name -> Nullable<Varchar>, #[max_length = 64] issuer_country -> Nullable<Varchar>, payer_country -> Nullable<Array<Nullable<Text>>>, is_stored -> Nullable<Bool>, #[max_length = 32] swift_code -> Nullable<Varchar>, #[max_length = 128] direct_debit_token -> Nullable<Varchar>, created_at -> Timestamp, last_modified -> Timestamp, payment_method -> Nullable<Varchar>, #[max_length = 64] payment_method_type -> Nullable<Varchar>, #[max_length = 128] payment_method_issuer -> Nullable<Varchar>, payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>, metadata -> Nullable<Json>, payment_method_data -> Nullable<Bytea>, #[max_length = 64] locker_id -> Nullable<Varchar>, last_used_at -> Timestamp, connector_mandate_details -> Nullable<Jsonb>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] status -> Varchar, #[max_length = 255] network_transaction_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, payment_method_billing_address -> Nullable<Bytea>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, #[max_length = 128] network_token_requestor_reference_id -> Nullable<Varchar>, #[max_length = 64] network_token_locker_id -> Nullable<Varchar>, network_token_payment_method_data -> Nullable<Bytea>, #[max_length = 64] external_vault_source -> Nullable<Varchar>, #[max_length = 64] vault_type -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payout_attempt (merchant_id, payout_attempt_id) { #[max_length = 64] payout_attempt_id -> Varchar, #[max_length = 64] payout_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] address_id -> Nullable<Varchar>, #[max_length = 64] connector -> Nullable<Varchar>, #[max_length = 128] connector_payout_id -> Nullable<Varchar>, #[max_length = 64] payout_token -> Nullable<Varchar>, status -> PayoutStatus, is_eligible -> Nullable<Bool>, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, business_country -> Nullable<CountryAlpha2>, #[max_length = 64] business_label -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, routing_info -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, additional_payout_method_data -> Nullable<Jsonb>, #[max_length = 255] merchant_order_reference_id -> Nullable<Varchar>, payout_connector_metadata -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payouts (merchant_id, payout_id) { #[max_length = 64] payout_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] address_id -> Nullable<Varchar>, payout_type -> Nullable<PayoutType>, #[max_length = 64] payout_method_id -> Nullable<Varchar>, amount -> Int8, destination_currency -> Currency, source_currency -> Currency, #[max_length = 255] description -> Nullable<Varchar>, recurring -> Bool, auto_fulfill -> Bool, #[max_length = 255] return_url -> Nullable<Varchar>, #[max_length = 64] entity_type -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, last_modified_at -> Timestamp, attempt_count -> Int2, #[max_length = 64] profile_id -> Varchar, status -> PayoutStatus, confirm -> Nullable<Bool>, #[max_length = 255] payout_link_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 32] priority -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; process_tracker (id) { #[max_length = 127] id -> Varchar, #[max_length = 64] name -> Nullable<Varchar>, tag -> Array<Nullable<Text>>, #[max_length = 64] runner -> Nullable<Varchar>, retry_count -> Int4, schedule_time -> Nullable<Timestamp>, #[max_length = 255] rule -> Varchar, tracking_data -> Json, #[max_length = 255] business_status -> Varchar, status -> ProcessTrackerStatus, event -> Array<Nullable<Text>>, created_at -> Timestamp, updated_at -> Timestamp, version -> ApiVersion, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; refund (merchant_id, refund_id) { #[max_length = 64] internal_reference_id -> Varchar, #[max_length = 64] refund_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 128] connector_transaction_id -> Varchar, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_refund_id -> Nullable<Varchar>, #[max_length = 64] external_reference_id -> Nullable<Varchar>, refund_type -> RefundType, total_amount -> Int8, currency -> Currency, refund_amount -> Int8, refund_status -> RefundStatus, sent_to_gateway -> Bool, refund_error_message -> Nullable<Text>, metadata -> Nullable<Json>, #[max_length = 128] refund_arn -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] refund_reason -> Nullable<Varchar>, refund_error_code -> Nullable<Text>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, charges -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, #[max_length = 512] connector_refund_data -> Nullable<Varchar>, #[max_length = 512] connector_transaction_data -> Nullable<Varchar>, split_refunds -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, processor_refund_data -> Nullable<Text>, processor_transaction_data -> Nullable<Text>, #[max_length = 64] issuer_error_code -> Nullable<Varchar>, issuer_error_message -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; relay (id) { #[max_length = 64] id -> Varchar, #[max_length = 128] connector_resource_id -> Varchar, #[max_length = 64] connector_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, relay_type -> RelayType, request_data -> Nullable<Jsonb>, status -> RelayStatus, #[max_length = 128] connector_reference_id -> Nullable<Varchar>, #[max_length = 64] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, created_at -> Timestamp, modified_at -> Timestamp, response_data -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; reverse_lookup (lookup_id) { #[max_length = 128] lookup_id -> Varchar, #[max_length = 128] sk_id -> Varchar, #[max_length = 128] pk_id -> Varchar, #[max_length = 128] source -> Varchar, #[max_length = 32] updated_by -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; roles (role_id) { #[max_length = 64] role_name -> Varchar, #[max_length = 64] role_id -> Varchar, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Varchar, groups -> Array<Nullable<Text>>, scope -> RoleScope, created_at -> Timestamp, #[max_length = 64] created_by -> Varchar, last_modified_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; routing_algorithm (algorithm_id) { #[max_length = 64] algorithm_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, kind -> RoutingAlgorithmKind, algorithm_data -> Jsonb, created_at -> Timestamp, modified_at -> Timestamp, algorithm_for -> TransactionType, #[max_length = 64] decision_engine_routing_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; subscription (id) { #[max_length = 128] id -> Varchar, #[max_length = 128] status -> Varchar, #[max_length = 128] billing_processor -> Nullable<Varchar>, #[max_length = 128] payment_method_id -> Nullable<Varchar>, #[max_length = 128] merchant_connector_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 128] connector_subscription_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] customer_id -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, #[max_length = 128] merchant_reference_id -> Nullable<Varchar>, #[max_length = 128] plan_id -> Nullable<Varchar>, #[max_length = 128] item_price_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; themes (theme_id) { #[max_length = 64] theme_id -> Varchar, #[max_length = 64] tenant_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] theme_name -> Varchar, #[max_length = 64] email_primary_color -> Varchar, #[max_length = 64] email_foreground_color -> Varchar, #[max_length = 64] email_background_color -> Varchar, #[max_length = 64] email_entity_name -> Varchar, email_entity_logo_url -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; unified_translations (unified_code, unified_message, locale) { #[max_length = 255] unified_code -> Varchar, #[max_length = 1024] unified_message -> Varchar, #[max_length = 255] locale -> Varchar, #[max_length = 1024] translation -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_authentication_methods (id) { #[max_length = 64] id -> Varchar, #[max_length = 64] auth_id -> Varchar, #[max_length = 64] owner_id -> Varchar, #[max_length = 64] owner_type -> Varchar, #[max_length = 64] auth_type -> Varchar, private_config -> Nullable<Bytea>, public_config -> Nullable<Jsonb>, allow_signup -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] email_domain -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_key_store (user_id) { #[max_length = 64] user_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_roles (id) { id -> Int4, #[max_length = 64] user_id -> Varchar, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, status -> UserStatus, #[max_length = 64] created_by -> Varchar, #[max_length = 64] last_modified_by -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] entity_id -> Nullable<Varchar>, #[max_length = 64] entity_type -> Nullable<Varchar>, version -> UserRoleVersion, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; users (user_id) { #[max_length = 64] user_id -> Varchar, #[max_length = 255] email -> Varchar, #[max_length = 255] name -> Varchar, #[max_length = 255] password -> Nullable<Varchar>, is_verified -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, totp_status -> TotpStatus, totp_secret -> Nullable<Bytea>, totp_recovery_codes -> Nullable<Array<Nullable<Text>>>, last_password_modified_at -> Nullable<Timestamp>, lineage_context -> Nullable<Jsonb>, } } diesel::allow_tables_to_appear_in_same_query!( address, api_keys, authentication, blocklist, blocklist_fingerprint, blocklist_lookup, business_profile, callback_mapper, captures, cards_info, configs, customers, dashboard_metadata, dispute, dynamic_routing_stats, events, file_metadata, fraud_check, gateway_status_map, generic_link, hyperswitch_ai_interaction, hyperswitch_ai_interaction_default, incremental_authorization, invoice, locker_mock_up, mandate, merchant_account, merchant_connector_account, merchant_key_store, organization, payment_attempt, payment_intent, payment_link, payment_methods, payout_attempt, payouts, process_tracker, refund, relay, reverse_lookup, roles, routing_algorithm, subscription, themes, unified_translations, user_authentication_methods, user_key_store, user_roles, users, );
crates/diesel_models/src/schema.rs
diesel_models::src::schema
14,022
true
// File: crates/diesel_models/src/generic_link.rs // Module: diesel_models::src::generic_link 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)), }, } } }
crates/diesel_models/src/generic_link.rs
diesel_models::src::generic_link
1,663
true
// File: crates/diesel_models/src/unified_translations.rs // Module: diesel_models::src::unified_translations //! 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, } } }
crates/diesel_models/src/unified_translations.rs
diesel_models::src::unified_translations
358
true
// File: crates/diesel_models/src/api_keys.rs // Module: diesel_models::src::api_keys 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>, }
crates/diesel_models/src/api_keys.rs
diesel_models::src::api_keys
1,029
true
// File: crates/diesel_models/src/errors.rs // Module: diesel_models::src::errors #[derive(Copy, Clone, Debug, thiserror::Error)] pub enum DatabaseError { #[error("An error occurred when obtaining database connection")] DatabaseConnectionError, #[error("The requested resource was not found in the database")] NotFound, #[error("A unique constraint violation occurred")] UniqueViolation, #[error("No fields were provided to be updated")] NoFieldsToUpdate, #[error("An error occurred when generating typed SQL query")] QueryGenerationFailed, // InsertFailed, #[error("An unknown error occurred")] Others, } impl From<diesel::result::Error> for DatabaseError { fn from(error: diesel::result::Error) -> Self { match error { diesel::result::Error::DatabaseError( diesel::result::DatabaseErrorKind::UniqueViolation, _, ) => Self::UniqueViolation, diesel::result::Error::NotFound => Self::NotFound, diesel::result::Error::QueryBuilderError(_) => Self::QueryGenerationFailed, _ => Self::Others, } } }
crates/diesel_models/src/errors.rs
diesel_models::src::errors
247
true
// File: crates/diesel_models/src/customers.rs // Module: diesel_models::src::customers 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 } } }
crates/diesel_models/src/customers.rs
diesel_models::src::customers
2,424
true
// File: crates/diesel_models/src/gsm.rs // Module: diesel_models::src::gsm //! 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) } }
crates/diesel_models/src/gsm.rs
diesel_models::src::gsm
1,003
true
// File: crates/diesel_models/src/hyperswitch_ai_interaction.rs // Module: diesel_models::src::hyperswitch_ai_interaction 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, }
crates/diesel_models/src/hyperswitch_ai_interaction.rs
diesel_models::src::hyperswitch_ai_interaction
387
true
// File: crates/diesel_models/src/payout_attempt.rs // Module: diesel_models::src::payout_attempt 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 } } }
crates/diesel_models/src/payout_attempt.rs
diesel_models::src::payout_attempt
2,170
true
// File: crates/diesel_models/src/authentication.rs // Module: diesel_models::src::authentication 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() }, } } }
crates/diesel_models/src/authentication.rs
diesel_models::src::authentication
4,779
true
// File: crates/diesel_models/src/merchant_key_store.rs // Module: diesel_models::src::merchant_key_store 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, }
crates/diesel_models/src/merchant_key_store.rs
diesel_models::src::merchant_key_store
332
true
// File: crates/diesel_models/src/user_key_store.rs // Module: diesel_models::src::user_key_store 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, }
crates/diesel_models/src/user_key_store.rs
diesel_models::src::user_key_store
198
true
// File: crates/diesel_models/src/ephemeral_key.rs // Module: diesel_models::src::ephemeral_key #[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) } }
crates/diesel_models/src/ephemeral_key.rs
diesel_models::src::ephemeral_key
425
true
// File: crates/diesel_models/src/reverse_lookup.rs // Module: diesel_models::src::reverse_lookup 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, } } }
crates/diesel_models/src/reverse_lookup.rs
diesel_models::src::reverse_lookup
396
true
// File: crates/diesel_models/src/relay.rs // Module: diesel_models::src::relay 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, }
crates/diesel_models/src/relay.rs
diesel_models::src::relay
651
true
// File: crates/diesel_models/src/mandate.rs // Module: diesel_models::src::mandate 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(), } } }
crates/diesel_models/src/mandate.rs
diesel_models::src::mandate
2,172
true
// File: crates/diesel_models/src/payment_intent.rs // Module: diesel_models::src::payment_intent 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()); } }
crates/diesel_models/src/payment_intent.rs
diesel_models::src::payment_intent
16,282
true
// File: crates/diesel_models/src/capture.rs // Module: diesel_models::src::capture 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() }, } } }
crates/diesel_models/src/capture.rs
diesel_models::src::capture
1,218
true
// File: crates/diesel_models/src/authorization.rs // Module: diesel_models::src::authorization 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, }, } } }
crates/diesel_models/src/authorization.rs
diesel_models::src::authorization
764
true
// File: crates/diesel_models/src/payment_methods_session.rs // Module: diesel_models::src::payment_methods_session 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>>, }
crates/diesel_models/src/payment_methods_session.rs
diesel_models::src::payment_methods_session
518
true
// File: crates/diesel_models/src/user_authentication_method.rs // Module: diesel_models::src::user_authentication_method 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), }, } } }
crates/diesel_models/src/user_authentication_method.rs
diesel_models::src::user_authentication_method
591
true
// File: crates/diesel_models/src/file.rs // Module: diesel_models::src::file 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, }, } } }
crates/diesel_models/src/file.rs
diesel_models::src::file
697
true
// File: crates/diesel_models/src/user/theme.rs // Module: diesel_models::src::user::theme 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), }, } } }
crates/diesel_models/src/user/theme.rs
diesel_models::src::user::theme
897
true
// File: crates/diesel_models/src/user/dashboard_metadata.rs // Module: diesel_models::src::user::dashboard_metadata 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, }, } } }
crates/diesel_models/src/user/dashboard_metadata.rs
diesel_models::src::user::dashboard_metadata
564
true
// File: crates/diesel_models/src/user/sample_data.rs // Module: diesel_models::src::user::sample_data #[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, } } }
crates/diesel_models/src/user/sample_data.rs
diesel_models::src::user::sample_data
3,237
true
// File: crates/diesel_models/src/query/dynamic_routing_stats.rs // Module: diesel_models::src::query::dynamic_routing_stats use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use error_stack::report; use super::generics; use crate::{ dynamic_routing_stats::{ DynamicRoutingStats, DynamicRoutingStatsNew, DynamicRoutingStatsUpdate, }, errors, schema::dynamic_routing_stats::dsl, PgPooledConn, StorageResult, }; impl DynamicRoutingStatsNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<DynamicRoutingStats> { generics::generic_insert(conn, self).await } } impl DynamicRoutingStats { pub async fn find_optional_by_attempt_id_merchant_id( conn: &PgPooledConn, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ) .await } pub async fn update( conn: &PgPooledConn, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, dynamic_routing_stat: DynamicRoutingStatsUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::< <Self as HasTable>::Table, DynamicRoutingStatsUpdate, _, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), dynamic_routing_stat, ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating dynamic_routing_stats entry") }) } }
crates/diesel_models/src/query/dynamic_routing_stats.rs
diesel_models::src::query::dynamic_routing_stats
441
true
// File: crates/diesel_models/src/query/tokenization.rs // Module: diesel_models::src::query::tokenization #[cfg(feature = "v2")] use diesel::associations::HasTable; #[cfg(feature = "v2")] use diesel::ExpressionMethods; #[cfg(feature = "v2")] use crate::{ errors, query::generics, schema_v2::tokenization, tokenization as tokenization_diesel, PgPooledConn, StorageResult, }; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl tokenization_diesel::Tokenization { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn find_by_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalTokenId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, tokenization::dsl::id.eq(id.to_owned()), ) .await } pub async fn update_with_id( self, conn: &PgPooledConn, tokenization_record: tokenization_diesel::TokenizationUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, tokenization::dsl::id.eq(self.id.to_owned()), tokenization_record, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } }
crates/diesel_models/src/query/tokenization.rs
diesel_models::src::query::tokenization
390
true
// File: crates/diesel_models/src/query/dispute.rs // Module: diesel_models::src::query::dispute use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; use crate::{ dispute::{Dispute, DisputeNew, DisputeUpdate, DisputeUpdateInternal}, errors, schema::dispute::dsl, PgPooledConn, StorageResult, }; impl DisputeNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Dispute> { generics::generic_insert(conn, self).await } } impl Dispute { pub async fn find_by_merchant_id_payment_id_connector_dispute_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())) .and(dsl::connector_dispute_id.eq(connector_dispute_id.to_owned())), ) .await } pub async fn find_by_merchant_id_dispute_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::dispute_id.eq(dispute_id.to_owned())), ) .await } pub async fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), None, None, None, ) .await } pub async fn update(self, conn: &PgPooledConn, dispute: DisputeUpdate) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::dispute_id.eq(self.dispute_id.to_owned()), DisputeUpdateInternal::from(dispute), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } }
crates/diesel_models/src/query/dispute.rs
diesel_models::src::query::dispute
686
true
// File: crates/diesel_models/src/query/callback_mapper.rs // Module: diesel_models::src::query::callback_mapper use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ callback_mapper::CallbackMapper, schema::callback_mapper::dsl, PgPooledConn, StorageResult, }; impl CallbackMapper { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } }
crates/diesel_models/src/query/callback_mapper.rs
diesel_models::src::query::callback_mapper
174
true
// File: crates/diesel_models/src/query/role.rs // Module: diesel_models::src::query::role use async_bb8_diesel::AsyncRunQueryDsl; use common_enums::EntityType; use common_utils::id_type; use diesel::{ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; use strum::IntoEnumIterator; use crate::{ enums::RoleScope, errors, query::generics, role::*, schema::roles::dsl, PgPooledConn, StorageResult, }; impl RoleNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Role> { generics::generic_insert(conn, self).await } } impl Role { fn get_entity_list( current_entity: EntityType, is_lineage_data_required: bool, ) -> Vec<EntityType> { is_lineage_data_required .then(|| { EntityType::iter() .filter(|variant| *variant <= current_entity) .collect() }) .unwrap_or(vec![current_entity]) } pub async fn find_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id.eq(role_id.to_owned()), ) .await } pub async fn find_by_role_id_in_lineage( conn: &PgPooledConn, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id .eq(role_id.to_owned()) .and(dsl::tenant_id.eq(tenant_id.to_owned())) .and(dsl::org_id.eq(org_id.to_owned())) .and( dsl::scope .eq(RoleScope::Organization) .or(dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::scope.eq(RoleScope::Merchant))) .or(dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::scope.eq(RoleScope::Profile))), ), ) .await } pub async fn find_by_role_id_org_id_tenant_id( conn: &PgPooledConn, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id .eq(role_id.to_owned()) .and(dsl::tenant_id.eq(tenant_id.to_owned())) .and(dsl::org_id.eq(org_id.to_owned())), ) .await } pub async fn update_by_role_id( conn: &PgPooledConn, role_id: &str, role_update: RoleUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::role_id.eq(role_id.to_owned()), RoleUpdateInternal::from(role_update), ) .await } pub async fn delete_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id.eq(role_id.to_owned()), ) .await } //TODO: Remove once generic_list_roles_by_entity_type is stable pub async fn generic_roles_list_for_org( conn: &PgPooledConn, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .filter(dsl::tenant_id.eq(tenant_id).and(dsl::org_id.eq(org_id))) .into_boxed(); if let Some(merchant_id) = merchant_id { query = query.filter( (dsl::merchant_id .eq(merchant_id) .and(dsl::scope.eq(RoleScope::Merchant))) .or(dsl::scope.eq(RoleScope::Organization)), ); } if let Some(entity_type) = entity_type { query = query.filter(dsl::entity_type.eq(entity_type)) } if let Some(limit) = limit { query = query.limit(limit.into()); } router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => { Err(report!(err)).change_context(errors::DatabaseError::NotFound) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } } pub async fn generic_list_roles_by_entity_type( conn: &PgPooledConn, payload: ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .into_boxed() .filter(dsl::tenant_id.eq(tenant_id)) .filter(dsl::org_id.eq(org_id)); match payload { ListRolesByEntityPayload::Organization => { let entity_in_vec = Self::get_entity_list(EntityType::Organization, is_lineage_data_required); query = query.filter(dsl::entity_type.eq_any(entity_in_vec)) } ListRolesByEntityPayload::Merchant(merchant_id) => { let entity_in_vec = Self::get_entity_list(EntityType::Merchant, is_lineage_data_required); query = query .filter( dsl::scope .eq(RoleScope::Organization) .or(dsl::merchant_id.eq(merchant_id)), ) .filter(dsl::entity_type.eq_any(entity_in_vec)) } ListRolesByEntityPayload::Profile(merchant_id, profile_id) => { let entity_in_vec = Self::get_entity_list(EntityType::Profile, is_lineage_data_required); query = query .filter( dsl::scope .eq(RoleScope::Organization) .or(dsl::scope .eq(RoleScope::Merchant) .and(dsl::merchant_id.eq(merchant_id.clone()))) .or(dsl::profile_id.eq(profile_id)), ) .filter(dsl::entity_type.eq_any(entity_in_vec)) } }; router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => Err(report!(err)).change_context(errors::DatabaseError::Others), } } }
crates/diesel_models/src/query/role.rs
diesel_models::src::query::role
1,715
true
// File: crates/diesel_models/src/query/payment_attempt.rs // Module: diesel_models::src::query::payment_attempt #[cfg(feature = "v1")] use std::collections::HashSet; use async_bb8_diesel::AsyncRunQueryDsl; #[cfg(feature = "v1")] use diesel::Table; use diesel::{ associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; use super::generics; #[cfg(feature = "v1")] use crate::schema::payment_attempt::dsl; #[cfg(feature = "v2")] use crate::schema_v2::payment_attempt::dsl; #[cfg(feature = "v1")] use crate::{enums::IntentStatus, payment_attempt::PaymentAttemptUpdate, PaymentIntent}; use crate::{ enums::{self}, errors::DatabaseError, payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdateInternal}, query::generics::db_metrics, PgPooledConn, StorageResult, }; impl PaymentAttemptNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentAttempt> { generics::generic_insert(conn, self).await } } impl PaymentAttempt { #[cfg(feature = "v1")] pub async fn update_with_attempt_id( self, conn: &PgPooledConn, payment_attempt: PaymentAttemptUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), PaymentAttemptUpdateInternal::from(payment_attempt).populate_derived_fields(&self), ) .await { Err(error) => match error.current_context() { DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } #[cfg(feature = "v2")] pub async fn update_with_attempt_id( self, conn: &PgPooledConn, payment_attempt: PaymentAttemptUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, dsl::id.eq(self.id.to_owned()), payment_attempt) .await { Err(error) => match error.current_context() { DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } #[cfg(feature = "v1")] pub async fn find_optional_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_connector_transaction_id_payment_id_merchant_id( conn: &PgPooledConn, connector_transaction_id: &common_utils::types::ConnectorTransactionId, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::connector_transaction_id .eq(connector_transaction_id.get_id().to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())) .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_last_successful_attempt_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { // perform ordering on the application level instead of database level generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, dsl::payment_id .eq(payment_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::status.eq(enums::AttemptStatus::Charged)), Some(1), None, Some(dsl::modified_at.desc()), ) .await? .into_iter() .nth(0) .ok_or(report!(DatabaseError::NotFound)) } #[cfg(feature = "v1")] pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { // perform ordering on the application level instead of database level generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, dsl::payment_id .eq(payment_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and( dsl::status .eq(enums::AttemptStatus::Charged) .or(dsl::status.eq(enums::AttemptStatus::PartialCharged)), ), Some(1), None, Some(dsl::modified_at.desc()), ) .await? .into_iter() .nth(0) .ok_or(report!(DatabaseError::NotFound)) } #[cfg(feature = "v2")] pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::GlobalPaymentId, ) -> StorageResult<Self> { // perform ordering on the application level instead of database level generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, dsl::payment_id.eq(payment_id.to_owned()).and( dsl::status .eq(enums::AttemptStatus::Charged) .or(dsl::status.eq(enums::AttemptStatus::PartialCharged)), ), Some(1), None, Some(dsl::modified_at.desc()), ) .await? .into_iter() .nth(0) .ok_or(report!(DatabaseError::NotFound)) } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_connector_txn_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_txn_id: &str, ) -> StorageResult<Self> { let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data( connector_txn_id.to_string(), ); let connector_transaction_id = txn_id .get_txn_id(txn_data.as_ref()) .change_context(DatabaseError::Others) .attach_printable_lazy(|| { format!("Failed to retrieve txn_id for ({txn_id:?}, {txn_data:?})") })?; generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())), ) .await } #[cfg(feature = "v2")] pub async fn find_by_profile_id_connector_transaction_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, connector_txn_id: &str, ) -> StorageResult<Self> { let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data( connector_txn_id.to_string(), ); let connector_transaction_id = txn_id .get_txn_id(txn_data.as_ref()) .change_context(DatabaseError::Others) .attach_printable_lazy(|| { format!("Failed to retrieve txn_id for ({txn_id:?}, {txn_data:?})") })?; generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::connector_payment_id.eq(connector_transaction_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ) .await } #[cfg(feature = "v2")] pub async fn find_by_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalAttemptId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } #[cfg(feature = "v2")] pub async fn find_by_payment_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::GlobalPaymentId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::payment_id.eq(payment_id.to_owned()), None, None, Some(dsl::created_at.asc()), ) .await } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_preprocessing_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, preprocessing_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::preprocessing_step_id.eq(preprocessing_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_payment_id_merchant_id_attempt_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_id.eq(payment_id.to_owned()).and( dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ), ) .await } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), None, None, None, ) .await } #[cfg(feature = "v1")] pub async fn get_filters_for_payments( conn: &PgPooledConn, pi: &[PaymentIntent], merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<( Vec<String>, Vec<enums::Currency>, Vec<IntentStatus>, Vec<enums::PaymentMethod>, Vec<enums::PaymentMethodType>, Vec<enums::AuthenticationType>, )> { let active_attempts: Vec<String> = pi .iter() .map(|payment_intent| payment_intent.clone().active_attempt_id) .collect(); let filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::attempt_id.eq_any(active_attempts)); let intent_status: Vec<IntentStatus> = pi .iter() .map(|payment_intent| payment_intent.status) .collect::<HashSet<IntentStatus>>() .into_iter() .collect(); let filter_connector = filter .clone() .select(dsl::connector) .distinct() .get_results_async::<Option<String>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by connector")? .into_iter() .flatten() .collect::<Vec<String>>(); let filter_currency = filter .clone() .select(dsl::currency) .distinct() .get_results_async::<Option<enums::Currency>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by currency")? .into_iter() .flatten() .collect::<Vec<enums::Currency>>(); let filter_payment_method = filter .clone() .select(dsl::payment_method) .distinct() .get_results_async::<Option<enums::PaymentMethod>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by payment method")? .into_iter() .flatten() .collect::<Vec<enums::PaymentMethod>>(); let filter_payment_method_type = filter .clone() .select(dsl::payment_method_type) .distinct() .get_results_async::<Option<enums::PaymentMethodType>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by payment method type")? .into_iter() .flatten() .collect::<Vec<enums::PaymentMethodType>>(); let filter_authentication_type = filter .clone() .select(dsl::authentication_type) .distinct() .get_results_async::<Option<enums::AuthenticationType>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by authentication type")? .into_iter() .flatten() .collect::<Vec<enums::AuthenticationType>>(); Ok(( filter_connector, filter_currency, intent_status, filter_payment_method, filter_payment_method_type, filter_authentication_type, )) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn get_total_count_of_attempts( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<String>>, payment_method_type: Option<Vec<enums::PaymentMethod>>, payment_method_subtype: Option<Vec<enums::PaymentMethodType>>, authentication_type: Option<Vec<enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<enums::CardNetwork>>, ) -> StorageResult<i64> { let mut filter = <Self as HasTable>::table() .count() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::id.eq_any(active_attempt_ids.to_owned())) .into_boxed(); if let Some(connectors) = connector { filter = filter.filter(dsl::connector.eq_any(connectors)); } if let Some(payment_method_types) = payment_method_type { filter = filter.filter(dsl::payment_method_type_v2.eq_any(payment_method_types)); } if let Some(payment_method_subtypes) = payment_method_subtype { filter = filter.filter(dsl::payment_method_subtype.eq_any(payment_method_subtypes)); } if let Some(authentication_types) = authentication_type { filter = filter.filter(dsl::authentication_type.eq_any(authentication_types)); } if let Some(merchant_connector_ids) = merchant_connector_id { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_ids)); } if let Some(card_networks) = card_network { filter = filter.filter(dsl::card_network.eq_any(card_networks)); } router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); // TODO: Remove these logs after debugging the issue for delay in count query let start_time = std::time::Instant::now(); router_env::logger::debug!("Executing count query start_time: {:?}", start_time); let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_result_async::<i64>(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering count of payments"); let duration = start_time.elapsed(); router_env::logger::debug!("Completed count query in {:?}", duration); result } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn get_total_count_of_attempts( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<String>>, payment_method: Option<Vec<enums::PaymentMethod>>, payment_method_type: Option<Vec<enums::PaymentMethodType>>, authentication_type: Option<Vec<enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<enums::CardNetwork>>, card_discovery: Option<Vec<enums::CardDiscovery>>, ) -> StorageResult<i64> { let mut filter = <Self as HasTable>::table() .count() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned())) .into_boxed(); if let Some(connector) = connector { filter = filter.filter(dsl::connector.eq_any(connector)); } if let Some(payment_method) = payment_method { filter = filter.filter(dsl::payment_method.eq_any(payment_method)); } if let Some(payment_method_type) = payment_method_type { filter = filter.filter(dsl::payment_method_type.eq_any(payment_method_type)); } if let Some(authentication_type) = authentication_type { filter = filter.filter(dsl::authentication_type.eq_any(authentication_type)); } if let Some(merchant_connector_id) = merchant_connector_id { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id)) } if let Some(card_network) = card_network { filter = filter.filter(dsl::card_network.eq_any(card_network)) } if let Some(card_discovery) = card_discovery { filter = filter.filter(dsl::card_discovery.eq_any(card_discovery)) } router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); // TODO: Remove these logs after debugging the issue for delay in count query let start_time = std::time::Instant::now(); router_env::logger::debug!("Executing count query start_time: {:?}", start_time); let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_result_async::<i64>(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering count of payments"); let duration = start_time.elapsed(); router_env::logger::debug!("Completed count query in {:?}", duration); result } }
crates/diesel_models/src/query/payment_attempt.rs
diesel_models::src::query::payment_attempt
4,495
true
// File: crates/diesel_models/src/query/events.rs // Module: diesel_models::src::query::events use std::collections::HashSet; use diesel::{ associations::HasTable, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, }; use super::generics; use crate::{ events::{Event, EventNew, EventUpdateInternal}, schema::events::dsl, PgPooledConn, StorageResult, }; impl EventNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Event> { generics::generic_insert(conn, self).await } } impl Event { pub async fn find_by_merchant_id_event_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::event_id.eq(event_id.to_owned())), ) .await } pub async fn find_by_merchant_id_idempotent_event_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, idempotent_event_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::idempotent_event_id.eq(idempotent_event_id.to_owned())), ) .await } pub async fn list_initial_attempts_by_merchant_id_primary_object_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::primary_object_id.eq(primary_object_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } #[allow(clippy::too_many_arguments)] pub async fn list_initial_attempts_by_merchant_id_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> StorageResult<Vec<Self>> { use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{debug_query, pg::Pg, QueryDsl}; use error_stack::ResultExt; use router_env::logger; use super::generics::db_metrics::{track_database_call, DatabaseOperation}; use crate::errors::DatabaseError; let mut query = Self::table() .filter( dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .order(dsl::created_at.desc()) .into_boxed(); query = Self::apply_filters( query, None, (dsl::created_at, created_after, created_before), limit, offset, event_types, is_delivered, ); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter) .await .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found .attach_printable("Error filtering events by constraints") } pub async fn list_by_merchant_id_initial_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } pub async fn list_initial_attempts_by_profile_id_primary_object_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::business_profile_id.eq(profile_id.to_owned())) .and(dsl::primary_object_id.eq(primary_object_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } #[allow(clippy::too_many_arguments)] pub async fn list_initial_attempts_by_profile_id_constraints( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> StorageResult<Vec<Self>> { use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{debug_query, pg::Pg, QueryDsl}; use error_stack::ResultExt; use router_env::logger; use super::generics::db_metrics::{track_database_call, DatabaseOperation}; use crate::errors::DatabaseError; let mut query = Self::table() .filter( dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::business_profile_id.eq(profile_id.to_owned())), ) .order(dsl::created_at.desc()) .into_boxed(); query = Self::apply_filters( query, None, (dsl::created_at, created_after, created_before), limit, offset, event_types, is_delivered, ); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter) .await .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found .attach_printable("Error filtering events by constraints") } pub async fn list_by_profile_id_initial_attempt_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, initial_attempt_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::business_profile_id .eq(profile_id.to_owned()) .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } pub async fn update_by_merchant_id_event_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: EventUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::event_id.eq(event_id.to_owned())), event, ) .await } fn apply_filters<T>( mut query: T, profile_id: Option<common_utils::id_type::ProfileId>, (column, created_after, created_before): ( dsl::created_at, time::PrimitiveDateTime, time::PrimitiveDateTime, ), limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> T where T: diesel::query_dsl::methods::LimitDsl<Output = T> + diesel::query_dsl::methods::OffsetDsl<Output = T>, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::GtEq<dsl::created_at, time::PrimitiveDateTime>, Output = T, >, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::LtEq<dsl::created_at, time::PrimitiveDateTime>, Output = T, >, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::Eq<dsl::business_profile_id, common_utils::id_type::ProfileId>, Output = T, >, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::EqAny<dsl::event_type, HashSet<common_enums::EventType>>, Output = T, >, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::Eq<dsl::is_overall_delivery_successful, bool>, Output = T, >, { if let Some(profile_id) = profile_id { query = query.filter(dsl::business_profile_id.eq(profile_id)); } query = query .filter(column.ge(created_after)) .filter(column.le(created_before)); if let Some(limit) = limit { query = query.limit(limit); } if let Some(offset) = offset { query = query.offset(offset); } if !event_types.is_empty() { query = query.filter(dsl::event_type.eq_any(event_types)); } if let Some(is_delivered) = is_delivered { query = query.filter(dsl::is_overall_delivery_successful.eq(is_delivered)); } query } pub async fn count_initial_attempts_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> StorageResult<i64> { use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{debug_query, pg::Pg, QueryDsl}; use error_stack::ResultExt; use router_env::logger; use super::generics::db_metrics::{track_database_call, DatabaseOperation}; use crate::errors::DatabaseError; let mut query = Self::table() .count() .filter( dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .into_boxed(); query = Self::apply_filters( query, profile_id, (dsl::created_at, created_after, created_before), None, None, event_types, is_delivered, ); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<Self, _, _>( query.get_result_async::<i64>(conn), DatabaseOperation::Count, ) .await .change_context(DatabaseError::Others) .attach_printable("Error counting events by constraints") } }
crates/diesel_models/src/query/events.rs
diesel_models::src::query::events
2,674
true
// File: crates/diesel_models/src/query/organization.rs // Module: diesel_models::src::query::organization use common_utils::id_type; use diesel::{associations::HasTable, ExpressionMethods}; #[cfg(feature = "v1")] use crate::schema::organization::dsl::org_id as dsl_identifier; #[cfg(feature = "v2")] use crate::schema_v2::organization::dsl::id as dsl_identifier; use crate::{organization::*, query::generics, PgPooledConn, StorageResult}; impl OrganizationNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Organization> { generics::generic_insert(conn, self).await } } impl Organization { pub async fn find_by_org_id( conn: &PgPooledConn, org_id: id_type::OrganizationId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl_identifier.eq(org_id), ) .await } pub async fn update_by_org_id( conn: &PgPooledConn, org_id: id_type::OrganizationId, update: OrganizationUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl_identifier.eq(org_id), OrganizationUpdateInternal::from(update), ) .await } }
crates/diesel_models/src/query/organization.rs
diesel_models::src::query::organization
331
true
// File: crates/diesel_models/src/query/merchant_account.rs // Module: diesel_models::src::query::merchant_account #[cfg(feature = "v1")] use common_types::consts::API_VERSION; #[cfg(feature = "v1")] use diesel::BoolExpressionMethods; use diesel::{associations::HasTable, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] use crate::schema::merchant_account::dsl; #[cfg(feature = "v2")] use crate::schema_v2::merchant_account::dsl; use crate::{ errors, merchant_account::{MerchantAccount, MerchantAccountNew, MerchantAccountUpdateInternal}, PgPooledConn, StorageResult, }; impl MerchantAccountNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantAccount> { generics::generic_insert(conn, self).await } } #[cfg(feature = "v1")] impl MerchantAccount { pub async fn update( self, conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.get_id().to_owned(), merchant_account, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn update_with_specific_fields( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id.eq(identifier.to_owned()), merchant_account, ) .await } pub async fn delete_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id.eq(identifier.to_owned()), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id.eq(identifier.to_owned()), ) .await } pub async fn find_by_publishable_key( conn: &PgPooledConn, publishable_key: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::publishable_key.eq(publishable_key.to_owned()), ) .await } pub async fn list_by_organization_id( conn: &PgPooledConn, organization_id: &common_utils::id_type::OrganizationId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::organization_id .eq(organization_id.to_owned()) .and(dsl::version.eq(API_VERSION)), None, None, None, ) .await } pub async fn list_multiple_merchant_accounts( conn: &PgPooledConn, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id.eq_any(merchant_ids.clone()), None, None, None, ) .await } pub async fn list_all_merchant_accounts( conn: &PgPooledConn, limit: u32, offset: Option<u32>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id.ne_all(vec![""]), Some(i64::from(limit)), offset.map(i64::from), None, ) .await } pub async fn update_all_merchant_accounts( conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Vec<Self>> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.ne_all(vec![""]), merchant_account, ) .await } } #[cfg(feature = "v2")] impl MerchantAccount { pub async fn update( self, conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.get_id().to_owned(), merchant_account, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn update_with_specific_fields( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, dsl::id.eq(identifier.to_owned()), merchant_account) .await } pub async fn delete_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::id.eq(identifier.to_owned()), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(identifier.to_owned()), ) .await } pub async fn find_by_publishable_key( conn: &PgPooledConn, publishable_key: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::publishable_key.eq(publishable_key.to_owned()), ) .await } pub async fn list_by_organization_id( conn: &PgPooledConn, organization_id: &common_utils::id_type::OrganizationId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::organization_id.eq(organization_id.to_owned()), None, None, None, ) .await } pub async fn list_multiple_merchant_accounts( conn: &PgPooledConn, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >(conn, dsl::id.eq_any(merchant_ids), None, None, None) .await } pub async fn list_all_merchant_accounts( conn: &PgPooledConn, limit: u32, offset: Option<u32>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::id.ne_all(vec![""]), Some(i64::from(limit)), offset.map(i64::from), None, ) .await } pub async fn update_all_merchant_accounts( conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Vec<Self>> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::id.ne_all(vec![""]), merchant_account, ) .await } }
crates/diesel_models/src/query/merchant_account.rs
diesel_models::src::query::merchant_account
2,008
true
// File: crates/diesel_models/src/query/payouts.rs // Module: diesel_models::src::query::payouts use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, JoinOnDsl, QueryDsl, }; use error_stack::{report, ResultExt}; use super::generics; use crate::{ enums, errors, payouts::{Payouts, PayoutsNew, PayoutsUpdate, PayoutsUpdateInternal}, query::generics::db_metrics, schema::{payout_attempt, payouts::dsl}, PgPooledConn, StorageResult, }; impl PayoutsNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Payouts> { generics::generic_insert(conn, self).await } } impl Payouts { pub async fn update( self, conn: &PgPooledConn, payout_update: PayoutsUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::payout_id .eq(self.payout_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), PayoutsUpdateInternal::from(payout_update), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, Ok(mut payouts) => payouts .pop() .ok_or(error_stack::report!(errors::DatabaseError::NotFound)), } } pub async fn find_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), ) .await } pub async fn update_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, payout: PayoutsUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), PayoutsUpdateInternal::from(payout), ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound).attach_printable("Error while updating payout") }) } pub async fn find_optional_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), ) .await } pub async fn get_total_count_of_payouts( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, active_payout_ids: &[common_utils::id_type::PayoutId], connector: Option<Vec<String>>, currency: Option<Vec<enums::Currency>>, status: Option<Vec<enums::PayoutStatus>>, payout_type: Option<Vec<enums::PayoutType>>, ) -> StorageResult<i64> { let mut filter = <Self as HasTable>::table() .inner_join(payout_attempt::table.on(payout_attempt::dsl::payout_id.eq(dsl::payout_id))) .count() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::payout_id.eq_any(active_payout_ids.to_vec())) .into_boxed(); if let Some(connector) = connector { filter = filter.filter(payout_attempt::dsl::connector.eq_any(connector)); } if let Some(currency) = currency { filter = filter.filter(dsl::destination_currency.eq_any(currency)); } if let Some(status) = status { filter = filter.filter(dsl::status.eq_any(status)); } if let Some(payout_type) = payout_type { filter = filter.filter(dsl::payout_type.eq_any(payout_type)); } router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_result_async::<i64>(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering count of payouts") } }
crates/diesel_models/src/query/payouts.rs
diesel_models::src::query::payouts
1,188
true
// File: crates/diesel_models/src/query/fraud_check.rs // Module: diesel_models::src::query::fraud_check use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use crate::{ errors, fraud_check::*, query::generics, schema::fraud_check::dsl, PgPooledConn, StorageResult, }; impl FraudCheckNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<FraudCheck> { generics::generic_insert(conn, self).await } } impl FraudCheck { pub async fn update_with_attempt_id( self, conn: &PgPooledConn, fraud_check: FraudCheckUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), FraudCheckUpdateInternal::from(fraud_check), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn get_with_payment_id( conn: &PgPooledConn, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_id .eq(payment_id) .and(dsl::merchant_id.eq(merchant_id)), ) .await } pub async fn get_with_payment_id_if_present( conn: &PgPooledConn, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_id .eq(payment_id) .and(dsl::merchant_id.eq(merchant_id)), ) .await } }
crates/diesel_models/src/query/fraud_check.rs
diesel_models::src::query::fraud_check
508
true
// File: crates/diesel_models/src/query/cards_info.rs // Module: diesel_models::src::query::cards_info use diesel::{associations::HasTable, ExpressionMethods}; use error_stack::report; use crate::{ cards_info::{CardInfo, UpdateCardInfo}, errors, query::generics, schema::cards_info::dsl, PgPooledConn, StorageResult, }; impl CardInfo { pub async fn find_by_iin(conn: &PgPooledConn, card_iin: &str) -> StorageResult<Option<Self>> { generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>( conn, card_iin.to_owned(), ) .await } pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn update( conn: &PgPooledConn, card_iin: String, data: UpdateCardInfo, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, UpdateCardInfo, _, _>( conn, dsl::card_iin.eq(card_iin), data, ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating card_info entry") }) } }
crates/diesel_models/src/query/cards_info.rs
diesel_models::src::query::cards_info
319
true
// File: crates/diesel_models/src/query/payment_method.rs // Module: diesel_models::src::query::payment_method use async_bb8_diesel::AsyncRunQueryDsl; #[cfg(feature = "v1")] use diesel::Table; use diesel::{ associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::ResultExt; use super::generics; #[cfg(feature = "v1")] use crate::schema::payment_methods::dsl; #[cfg(feature = "v2")] use crate::schema_v2::payment_methods::dsl::{self, id as pm_id}; use crate::{ enums as storage_enums, errors, payment_method::{self, PaymentMethod, PaymentMethodNew}, PgPooledConn, StorageResult, }; impl PaymentMethodNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentMethod> { generics::generic_insert(conn, self).await } } #[cfg(feature = "v1")] impl PaymentMethod { pub async fn delete_by_payment_method_id( conn: &PgPooledConn, payment_method_id: String, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, Self>( conn, dsl::payment_method_id.eq(payment_method_id), ) .await } pub async fn delete_by_merchant_id_payment_method_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_method_id: &str, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, Self>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_method_id.eq(payment_method_id.to_owned())), ) .await } pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::locker_id.eq(locker_id.to_owned()), ) .await } pub async fn find_by_payment_method_id( conn: &PgPooledConn, payment_method_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_method_id.eq(payment_method_id.to_owned()), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id.eq(merchant_id.to_owned()), None, None, None, ) .await } pub async fn find_by_customer_id_merchant_id( conn: &PgPooledConn, customer_id: &common_utils::id_type::CustomerId, merchant_id: &common_utils::id_type::MerchantId, limit: Option<i64>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::customer_id .eq(customer_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), limit, None, Some(dsl::last_used_at.desc()), ) .await } pub async fn get_count_by_customer_id_merchant_id_status( conn: &PgPooledConn, customer_id: &common_utils::id_type::CustomerId, merchant_id: &common_utils::id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> StorageResult<i64> { let filter = <Self as HasTable>::table() .count() .filter( dsl::customer_id .eq(customer_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::status.eq(status.to_owned())), ) .into_boxed(); router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_result_async::<i64>(conn), generics::db_metrics::DatabaseOperation::Count, ) .await .change_context(errors::DatabaseError::Others) .attach_printable("Failed to get a count of payment methods") } pub async fn get_count_by_merchant_id_status( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> StorageResult<i64> { let query = <Self as HasTable>::table().count().filter( dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::status.eq(status.to_owned())), ); router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( query.get_result_async::<i64>(conn), generics::db_metrics::DatabaseOperation::Count, ) .await .change_context(errors::DatabaseError::Others) .attach_printable("Failed to get a count of payment methods") } pub async fn find_by_customer_id_merchant_id_status( conn: &PgPooledConn, customer_id: &common_utils::id_type::CustomerId, merchant_id: &common_utils::id_type::MerchantId, status: storage_enums::PaymentMethodStatus, limit: Option<i64>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::customer_id .eq(customer_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::status.eq(status)), limit, None, Some(dsl::last_used_at.desc()), ) .await } pub async fn update_with_payment_method_id( self, conn: &PgPooledConn, payment_method: payment_method::PaymentMethodUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::payment_method_id.eq(self.payment_method_id.to_owned()), payment_method, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } } #[cfg(feature = "v2")] impl PaymentMethod { pub async fn find_by_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalPaymentMethodId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, pm_id.eq(id.to_owned())) .await } pub async fn find_by_global_customer_id_merchant_id_status( conn: &PgPooledConn, customer_id: &common_utils::id_type::GlobalCustomerId, merchant_id: &common_utils::id_type::MerchantId, status: storage_enums::PaymentMethodStatus, limit: Option<i64>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::customer_id .eq(customer_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::status.eq(status)), limit, None, Some(dsl::last_used_at.desc()), ) .await } pub async fn find_by_global_customer_id( conn: &PgPooledConn, customer_id: &common_utils::id_type::GlobalCustomerId, limit: Option<i64>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::customer_id.eq(customer_id.to_owned()), limit, None, Some(dsl::last_used_at.desc()), ) .await } pub async fn update_with_id( self, conn: &PgPooledConn, payment_method: payment_method::PaymentMethodUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, pm_id.eq(self.id.to_owned()), payment_method) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn find_by_fingerprint_id( conn: &PgPooledConn, fingerprint_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::locker_fingerprint_id.eq(fingerprint_id.to_owned()), ) .await } pub async fn get_count_by_merchant_id_status( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> StorageResult<i64> { let query = <Self as HasTable>::table().count().filter( dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::status.eq(status.to_owned())), ); router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( query.get_result_async::<i64>(conn), generics::db_metrics::DatabaseOperation::Count, ) .await .change_context(errors::DatabaseError::Others) .attach_printable("Failed to get a count of payment methods") } }
crates/diesel_models/src/query/payment_method.rs
diesel_models::src::query::payment_method
2,347
true
// File: crates/diesel_models/src/query/merchant_connector_account.rs // Module: diesel_models::src::query::merchant_connector_account use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] use crate::schema::merchant_connector_account::dsl; #[cfg(feature = "v2")] use crate::schema_v2::merchant_connector_account::dsl; use crate::{ errors, merchant_connector_account::{ MerchantConnectorAccount, MerchantConnectorAccountNew, MerchantConnectorAccountUpdateInternal, }, PgPooledConn, StorageResult, }; impl MerchantConnectorAccountNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantConnectorAccount> { generics::generic_insert(conn, self).await } } #[cfg(feature = "v1")] impl MerchantConnectorAccount { pub async fn update( self, conn: &PgPooledConn, merchant_connector_account: MerchantConnectorAccountUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.merchant_connector_id.to_owned(), merchant_connector_account, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn delete_by_merchant_id_merchant_connector_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::merchant_connector_id.eq(merchant_connector_id.to_owned())), ) .await } pub async fn find_by_merchant_id_connector( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_label: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_label.eq(connector_label.to_owned())), ) .await } pub async fn find_by_profile_id_connector_name( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::connector_name.eq(connector_name.to_owned())), ) .await } pub async fn find_by_merchant_id_connector_name( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_name.eq(connector_name.to_owned())), None, None, None, ) .await } pub async fn find_by_merchant_id_merchant_connector_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::merchant_connector_id.eq(merchant_connector_id.to_owned())), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, ) -> StorageResult<Vec<Self>> { if get_disabled { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), None, None, Some(dsl::created_at.asc()), ) .await } else { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::disabled.eq(false)), None, None, None, ) .await } } pub async fn list_enabled_by_profile_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, connector_type: common_enums::ConnectorType, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::disabled.eq(false)) .and(dsl::connector_type.eq(connector_type)), None, None, Some(dsl::created_at.asc()), ) .await } } #[cfg(feature = "v2")] impl MerchantConnectorAccount { pub async fn update( self, conn: &PgPooledConn, merchant_connector_account: MerchantConnectorAccountUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.id.to_owned(), merchant_connector_account, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn delete_by_id( conn: &PgPooledConn, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>(conn, dsl::id.eq(id.to_owned())) .await } pub async fn find_by_id( conn: &PgPooledConn, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, ) -> StorageResult<Vec<Self>> { if get_disabled { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), None, None, Some(dsl::created_at.asc()), ) .await } else { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::disabled.eq(false)), None, None, None, ) .await } } pub async fn list_by_profile_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::profile_id.eq(profile_id.to_owned()), None, None, Some(dsl::created_at.asc()), ) .await } pub async fn list_enabled_by_profile_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, connector_type: common_enums::ConnectorType, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::disabled.eq(false)) .and(dsl::connector_type.eq(connector_type)), None, None, Some(dsl::created_at.asc()), ) .await } }
crates/diesel_models/src/query/merchant_connector_account.rs
diesel_models::src::query::merchant_connector_account
1,964
true
// File: crates/diesel_models/src/query/configs.rs // Module: diesel_models::src::query::configs use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ configs::{Config, ConfigNew, ConfigUpdate, ConfigUpdateInternal}, errors, schema::configs::dsl, PgPooledConn, StorageResult, }; impl ConfigNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Config> { generics::generic_insert(conn, self).await } } impl Config { pub async fn find_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, key.to_owned()).await } pub async fn update_by_key( conn: &PgPooledConn, key: &str, config_update: ConfigUpdate, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, key.to_owned(), ConfigUpdateInternal::from(config_update), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>( conn, key.to_owned(), ) .await } _ => Err(error), }, result => result, } } pub async fn delete_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::key.eq(key.to_owned()), ) .await } }
crates/diesel_models/src/query/configs.rs
diesel_models::src::query::configs
405
true
// File: crates/diesel_models/src/query/blocklist_fingerprint.rs // Module: diesel_models::src::query::blocklist_fingerprint use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ blocklist_fingerprint::{BlocklistFingerprint, BlocklistFingerprintNew}, schema::blocklist_fingerprint::dsl, PgPooledConn, StorageResult, }; impl BlocklistFingerprintNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistFingerprint> { generics::generic_insert(conn, self).await } } impl BlocklistFingerprint { pub async fn find_by_merchant_id_fingerprint_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), ) .await } }
crates/diesel_models/src/query/blocklist_fingerprint.rs
diesel_models::src::query::blocklist_fingerprint
256
true
// File: crates/diesel_models/src/query/routing_algorithm.rs // Module: diesel_models::src::query::routing_algorithm use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl}; use error_stack::{report, ResultExt}; use time::PrimitiveDateTime; use crate::{ enums, errors::DatabaseError, query::generics, routing_algorithm::{RoutingAlgorithm, RoutingProfileMetadata}, schema::routing_algorithm::dsl, PgPooledConn, StorageResult, }; impl RoutingAlgorithm { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn find_by_algorithm_id_merchant_id( conn: &PgPooledConn, algorithm_id: &common_utils::id_type::RoutingId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::algorithm_id .eq(algorithm_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .await } pub async fn find_by_algorithm_id_profile_id( conn: &PgPooledConn, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::algorithm_id .eq(algorithm_id.to_owned()) .and(dsl::profile_id.eq(profile_id.to_owned())), ) .await } pub async fn find_metadata_by_algorithm_id_profile_id( conn: &PgPooledConn, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<RoutingProfileMetadata> { Self::table() .select(( dsl::profile_id, dsl::algorithm_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter( dsl::algorithm_id .eq(algorithm_id.to_owned()) .and(dsl::profile_id.eq(profile_id.to_owned())), ) .limit(1) .load_async::<( common_utils::id_type::ProfileId, common_utils::id_type::RoutingId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .next() .ok_or(report!(DatabaseError::NotFound)) .map( |( profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, } }, ) } pub async fn list_metadata_by_profile_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, limit: i64, offset: i64, ) -> StorageResult<Vec<RoutingProfileMetadata>> { Ok(Self::table() .select(( dsl::algorithm_id, dsl::profile_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter(dsl::profile_id.eq(profile_id.to_owned())) .limit(limit) .offset(offset) .load_async::<( common_utils::id_type::RoutingId, common_utils::id_type::ProfileId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .map( |( algorithm_id, profile_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, profile_id, } }, ) .collect()) } pub async fn list_metadata_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, limit: i64, offset: i64, ) -> StorageResult<Vec<RoutingProfileMetadata>> { Ok(Self::table() .select(( dsl::profile_id, dsl::algorithm_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .limit(limit) .offset(offset) .order(dsl::modified_at.desc()) .load_async::<( common_utils::id_type::ProfileId, common_utils::id_type::RoutingId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .map( |( profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, } }, ) .collect()) } pub async fn list_metadata_by_merchant_id_transaction_type( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, transaction_type: &enums::TransactionType, limit: i64, offset: i64, ) -> StorageResult<Vec<RoutingProfileMetadata>> { Ok(Self::table() .select(( dsl::profile_id, dsl::algorithm_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::algorithm_for.eq(transaction_type.to_owned())) .limit(limit) .offset(offset) .order(dsl::modified_at.desc()) .load_async::<( common_utils::id_type::ProfileId, common_utils::id_type::RoutingId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .map( |( profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, } }, ) .collect()) } }
crates/diesel_models/src/query/routing_algorithm.rs
diesel_models::src::query::routing_algorithm
1,716
true
// File: crates/diesel_models/src/query/subscription.rs // Module: diesel_models::src::query::subscription use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use error_stack::report; use super::generics; use crate::{ errors, schema::subscription::dsl, subscription::{Subscription, SubscriptionNew, SubscriptionUpdate}, PgPooledConn, StorageResult, }; impl SubscriptionNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Subscription> { generics::generic_insert(conn, self).await } } impl Subscription { pub async fn find_by_merchant_id_subscription_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, id: String, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::id.eq(id.to_owned())), ) .await } pub async fn update_subscription_entry( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, id: String, subscription_update: SubscriptionUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::< <Self as HasTable>::Table, SubscriptionUpdate, _, _, >( conn, dsl::id .eq(id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), subscription_update, ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating subscription entry") }) } }
crates/diesel_models/src/query/subscription.rs
diesel_models::src::query::subscription
401
true
// File: crates/diesel_models/src/query/address.rs // Module: diesel_models::src::query::address use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ address::{Address, AddressNew, AddressUpdateInternal}, errors, schema::address::dsl, PgPooledConn, StorageResult, }; impl AddressNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Address> { generics::generic_insert(conn, self).await } } impl Address { pub async fn find_by_address_id(conn: &PgPooledConn, address_id: &str) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, address_id.to_owned()) .await } pub async fn update_by_address_id( conn: &PgPooledConn, address_id: String, address: AddressUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, address_id.clone(), address, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NotFound => { Err(error.attach_printable("Address with the given ID doesn't exist")) } errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>( conn, address_id.clone(), ) .await } _ => Err(error), }, result => result, } } pub async fn update( self, conn: &PgPooledConn, address_update_internal: AddressUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::address_id.eq(self.address_id.clone()), address_update_internal, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn delete_by_address_id( conn: &PgPooledConn, address_id: &str, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::address_id.eq(address_id.to_owned()), ) .await } pub async fn update_by_merchant_id_customer_id( conn: &PgPooledConn, customer_id: &common_utils::id_type::CustomerId, merchant_id: &common_utils::id_type::MerchantId, address: AddressUpdateInternal, ) -> StorageResult<Vec<Self>> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::customer_id.eq(customer_id.to_owned())), address, ) .await } pub async fn find_by_merchant_id_payment_id_address_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, address_id: &str, ) -> StorageResult<Self> { match generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_id .eq(payment_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::address_id.eq(address_id.to_owned())), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NotFound => { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>( conn, address_id.to_owned(), ) .await } _ => Err(error), }, result => result, } } pub async fn find_optional_by_address_id( conn: &PgPooledConn, address_id: &str, ) -> StorageResult<Option<Self>> { generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>( conn, address_id.to_owned(), ) .await } }
crates/diesel_models/src/query/address.rs
diesel_models::src::query::address
987
true
// File: crates/diesel_models/src/query/blocklist_lookup.rs // Module: diesel_models::src::query::blocklist_lookup use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ blocklist_lookup::{BlocklistLookup, BlocklistLookupNew}, schema::blocklist_lookup::dsl, PgPooledConn, StorageResult, }; impl BlocklistLookupNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistLookup> { generics::generic_insert(conn, self).await } } impl BlocklistLookup { pub async fn find_by_merchant_id_fingerprint( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint.eq(fingerprint.to_owned())), ) .await } pub async fn delete_by_merchant_id_fingerprint( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint.eq(fingerprint.to_owned())), ) .await } }
crates/diesel_models/src/query/blocklist_lookup.rs
diesel_models::src::query::blocklist_lookup
353
true