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/drainer/src/secrets_transformers.rs // Module: drainer::src::secrets_transformers use common_utils::errors::CustomResult; use hyperswitch_interfaces::secrets_interface::{ secret_handler::SecretsHandler, secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; use crate::settings::{Database, Settings}; #[async_trait::async_trait] impl SecretsHandler for Database { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let secured_db_config = value.get_inner(); let raw_db_password = secret_management_client .get_secret(secured_db_config.password.clone()) .await?; Ok(value.transition_state(|db| Self { password: raw_db_password, ..db })) } } /// # Panics /// /// Will panic even if fetching raw secret fails for at least one config value pub async fn fetch_raw_secrets( conf: Settings<SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> Settings<RawSecret> { #[allow(clippy::expect_used)] let database = Database::convert_to_raw_secret(conf.master_database, secret_management_client) .await .expect("Failed to decrypt database password"); Settings { server: conf.server, master_database: database, redis: conf.redis, log: conf.log, drainer: conf.drainer, encryption_management: conf.encryption_management, secrets_management: conf.secrets_management, multitenancy: conf.multitenancy, } }
crates/drainer/src/secrets_transformers.rs
drainer::src::secrets_transformers
375
true
// File: crates/drainer/src/settings.rs // Module: drainer::src::settings use std::{collections::HashMap, path::PathBuf, sync::Arc}; use common_utils::{ext_traits::ConfigExt, id_type, DbConnectionParams}; use config::{Environment, File}; use external_services::managers::{ encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig, }; use hyperswitch_interfaces::{ encryption_interface::EncryptionManagementInterface, secrets_interface::secret_state::{ RawSecret, SecretState, SecretStateContainer, SecuredSecret, }, }; use masking::Secret; use redis_interface as redis; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use router_env::{env, logger}; use serde::Deserialize; use crate::{errors, secrets_transformers}; #[derive(clap::Parser, Default)] #[cfg_attr(feature = "vergen", command(version = router_env::version!()))] pub struct CmdLineConf { /// Config file. /// Application will look for "config/config.toml" if this option isn't specified. #[arg(short = 'f', long, value_name = "FILE")] pub config_path: Option<PathBuf>, } #[derive(Clone)] pub struct AppState { pub conf: Arc<Settings<RawSecret>>, pub encryption_client: Arc<dyn EncryptionManagementInterface>, } impl AppState { /// # Panics /// /// Panics if secret or encryption management client cannot be initiated pub async fn new(conf: Settings<SecuredSecret>) -> Self { #[allow(clippy::expect_used)] let secret_management_client = conf .secrets_management .get_secret_management_client() .await .expect("Failed to create secret management client"); let raw_conf = secrets_transformers::fetch_raw_secrets(conf, &*secret_management_client).await; #[allow(clippy::expect_used)] let encryption_client = raw_conf .encryption_management .get_encryption_management_client() .await .expect("Failed to create encryption management client"); Self { conf: Arc::new(raw_conf), encryption_client, } } } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Settings<S: SecretState> { pub server: Server, pub master_database: SecretStateContainer<Database, S>, pub redis: redis::RedisSettings, pub log: Log, pub drainer: DrainerSettings, pub encryption_management: EncryptionManagementConfig, pub secrets_management: SecretsManagementConfig, pub multitenancy: Multitenancy, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Database { pub username: String, pub password: Secret<String>, pub host: String, pub port: u16, pub dbname: String, pub pool_size: u32, pub connection_timeout: u64, } impl DbConnectionParams for Database { fn get_username(&self) -> &str { &self.username } fn get_password(&self) -> Secret<String> { self.password.clone() } fn get_host(&self) -> &str { &self.host } fn get_port(&self) -> u16 { self.port } fn get_dbname(&self) -> &str { &self.dbname } } #[derive(Debug, Clone, Deserialize)] #[serde(default)] pub struct DrainerSettings { pub stream_name: String, pub num_partitions: u8, pub max_read_count: u64, pub shutdown_interval: u32, // in milliseconds pub loop_interval: u32, // in milliseconds } #[derive(Debug, Deserialize, Clone, Default)] pub struct Multitenancy { pub enabled: bool, pub tenants: TenantConfig, } impl Multitenancy { pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> { &self.tenants.0 } pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> { self.tenants .0 .values() .map(|tenant| tenant.tenant_id.clone()) .collect() } pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> { self.tenants.0.get(tenant_id) } } #[derive(Debug, Clone, Default)] pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>); impl<'de> Deserialize<'de> for TenantConfig { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] struct Inner { base_url: String, schema: String, accounts_schema: String, redis_key_prefix: String, clickhouse_database: String, } let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?; Ok(Self( hashmap .into_iter() .map(|(key, value)| { ( key.clone(), Tenant { tenant_id: key, base_url: value.base_url, schema: value.schema, accounts_schema: value.accounts_schema, redis_key_prefix: value.redis_key_prefix, clickhouse_database: value.clickhouse_database, }, ) }) .collect(), )) } } #[derive(Debug, Deserialize, Clone)] pub struct Tenant { pub tenant_id: id_type::TenantId, pub base_url: String, pub schema: String, pub accounts_schema: String, pub redis_key_prefix: String, pub clickhouse_database: String, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Server { pub port: u16, pub workers: usize, pub host: String, } impl Server { pub fn validate(&self) -> Result<(), errors::DrainerError> { common_utils::fp_utils::when(self.host.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "server host must not be empty".into(), )) }) } } impl Default for Database { fn default() -> Self { Self { username: String::new(), password: String::new().into(), host: "localhost".into(), port: 5432, dbname: String::new(), pool_size: 5, connection_timeout: 10, } } } impl Default for DrainerSettings { fn default() -> Self { Self { stream_name: "DRAINER_STREAM".into(), num_partitions: 64, max_read_count: 100, shutdown_interval: 1000, // in milliseconds loop_interval: 100, // in milliseconds } } } impl Default for Server { fn default() -> Self { Self { host: "127.0.0.1".to_string(), port: 8080, workers: 1, } } } impl Database { fn validate(&self) -> Result<(), errors::DrainerError> { use common_utils::fp_utils::when; when(self.host.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "database host must not be empty".into(), )) })?; when(self.dbname.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "database name must not be empty".into(), )) })?; when(self.username.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "database user username must not be empty".into(), )) })?; when(self.password.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "database user password must not be empty".into(), )) }) } } impl DrainerSettings { fn validate(&self) -> Result<(), errors::DrainerError> { common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || { Err(errors::DrainerError::ConfigParsingError( "drainer stream name must not be empty".into(), )) }) } } impl Settings<SecuredSecret> { pub fn new() -> Result<Self, errors::DrainerError> { Self::with_config_path(None) } pub fn with_config_path(config_path: Option<PathBuf>) -> Result<Self, errors::DrainerError> { // Configuration values are picked up in the following priority order (1 being least // priority): // 1. Defaults from the implementation of the `Default` trait. // 2. Values from config file. The config file accessed depends on the environment // specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of // `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`, // `/config/development.toml` file is read. // 3. Environment variables prefixed with `DRAINER` and each level separated by double // underscores. // // Values in config file override the defaults in `Default` trait, and the values set using // environment variables override both the defaults and the config file values. let environment = env::which(); let config_path = router_env::Config::config_path(&environment.to_string(), config_path); let config = router_env::Config::builder(&environment.to_string())? .add_source(File::from(config_path).required(false)) .add_source( Environment::with_prefix("DRAINER") .try_parsing(true) .separator("__") .list_separator(",") .with_list_parse_key("redis.cluster_urls"), ) .build()?; // The logger may not yet be initialized when constructing the application configuration #[allow(clippy::print_stderr)] serde_path_to_error::deserialize(config).map_err(|error| { logger::error!(%error, "Unable to deserialize application configuration"); eprintln!("Unable to deserialize application configuration: {error}"); errors::DrainerError::from(error.into_inner()) }) } pub fn validate(&self) -> Result<(), errors::DrainerError> { self.server.validate()?; self.master_database.get_inner().validate()?; // The logger may not yet be initialized when validating the application configuration #[allow(clippy::print_stderr)] self.redis.validate().map_err(|error| { eprintln!("{error}"); errors::DrainerError::ConfigParsingError("invalid Redis configuration".into()) })?; self.drainer.validate()?; // The logger may not yet be initialized when validating the application configuration #[allow(clippy::print_stderr)] self.secrets_management.validate().map_err(|error| { eprintln!("{error}"); errors::DrainerError::ConfigParsingError( "invalid secrets management configuration".into(), ) })?; // The logger may not yet be initialized when validating the application configuration #[allow(clippy::print_stderr)] self.encryption_management.validate().map_err(|error| { eprintln!("{error}"); errors::DrainerError::ConfigParsingError( "invalid encryption management configuration".into(), ) })?; Ok(()) } }
crates/drainer/src/settings.rs
drainer::src::settings
2,476
true
// File: crates/drainer/src/connection.rs // Module: drainer::src::connection use bb8::PooledConnection; use common_utils::DbConnectionParams; use diesel::PgConnection; use crate::{settings::Database, Settings}; pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>; #[allow(clippy::expect_used)] pub async fn redis_connection(conf: &Settings) -> redis_interface::RedisConnectionPool { redis_interface::RedisConnectionPool::new(&conf.redis) .await .expect("Failed to create Redis connection Pool") } // TODO: use stores defined in storage_impl instead /// # Panics /// /// Will panic if could not create a db pool #[allow(clippy::expect_used)] pub async fn diesel_make_pg_pool( database: &Database, _test_transaction: bool, schema: &str, ) -> PgPool { let database_url = database.get_database_url(schema); let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url); let pool = bb8::Pool::builder() .max_size(database.pool_size) .connection_timeout(std::time::Duration::from_secs(database.connection_timeout)); pool.build(manager) .await .expect("Failed to create PostgreSQL connection pool") } #[allow(clippy::expect_used)] pub async fn pg_connection( pool: &PgPool, ) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>> { pool.get() .await .expect("Couldn't retrieve PostgreSQL connection") }
crates/drainer/src/connection.rs
drainer::src::connection
344
true
// File: crates/drainer/src/utils.rs // Module: drainer::src::utils use std::sync::{atomic, Arc}; use error_stack::report; use redis_interface as redis; use serde::de::Deserialize; use crate::{ errors, kv, metrics, stream::{StreamEntries, StreamReadResult}, }; pub fn parse_stream_entries<'a>( read_result: &'a StreamReadResult, stream_name: &str, ) -> errors::DrainerResult<&'a StreamEntries> { read_result.get(stream_name).ok_or_else(|| { report!(errors::DrainerError::RedisError(report!( redis::errors::RedisError::NotFound ))) }) } pub(crate) fn deserialize_i64<'de, D>(deserializer: D) -> Result<i64, D::Error> where D: serde::Deserializer<'de>, { let s = serde_json::Value::deserialize(deserializer)?; match s { serde_json::Value::String(str_val) => str_val.parse().map_err(serde::de::Error::custom), serde_json::Value::Number(num_val) => match num_val.as_i64() { Some(val) => Ok(val), None => Err(serde::de::Error::custom(format!( "could not convert {num_val:?} to i64" ))), }, other => Err(serde::de::Error::custom(format!( "unexpected data format - expected string or number, got: {other:?}" ))), } } pub(crate) fn deserialize_db_op<'de, D>(deserializer: D) -> Result<kv::DBOperation, D::Error> where D: serde::Deserializer<'de>, { let s = serde_json::Value::deserialize(deserializer)?; match s { serde_json::Value::String(str_val) => { serde_json::from_str(&str_val).map_err(serde::de::Error::custom) } other => Err(serde::de::Error::custom(format!( "unexpected data format - expected string got: {other:?}" ))), } } // Here the output is in the format (stream_index, jobs_picked), // similar to the first argument of the function #[inline(always)] pub async fn increment_stream_index( (index, jobs_picked): (u8, Arc<atomic::AtomicU8>), total_streams: u8, ) -> u8 { if index == total_streams - 1 { match jobs_picked.load(atomic::Ordering::SeqCst) { 0 => metrics::CYCLES_COMPLETED_UNSUCCESSFULLY.add(1, &[]), _ => metrics::CYCLES_COMPLETED_SUCCESSFULLY.add(1, &[]), } jobs_picked.store(0, atomic::Ordering::SeqCst); 0 } else { index + 1 } }
crates/drainer/src/utils.rs
drainer::src::utils
631
true
// File: crates/router_derive/src/lib.rs // Module: router_derive::src::lib //! Utility macros for the `router` crate. #![warn(missing_docs)] use syn::parse_macro_input; use crate::macros::diesel::DieselEnumMeta; mod macros; /// Uses the [`Debug`][Debug] implementation of a type to derive its [`Display`][Display] /// implementation. /// /// Causes a compilation error if the type doesn't implement the [`Debug`][Debug] trait. /// /// [Debug]: ::core::fmt::Debug /// [Display]: ::core::fmt::Display /// /// # Example /// /// ``` /// use router_derive::DebugAsDisplay; /// /// #[derive(Debug, DebugAsDisplay)] /// struct Point { /// x: f32, /// y: f32, /// } /// /// #[derive(Debug, DebugAsDisplay)] /// enum Color { /// Red, /// Green, /// Blue, /// } /// ``` #[proc_macro_derive(DebugAsDisplay)] pub fn debug_as_display_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::debug_as_display_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } /// Derives the boilerplate code required for using an enum with `diesel` and a PostgreSQL database. /// The enum is required to implement (or derive) the [`ToString`][ToString] and the /// [`FromStr`][FromStr] traits for this derive macro to be used. /// /// Works in tandem with the [`diesel_enum`][diesel_enum] attribute macro to achieve the desired /// results. /// /// [diesel_enum]: macro@crate::diesel_enum /// [FromStr]: ::core::str::FromStr /// [ToString]: ::std::string::ToString /// /// # Example /// /// ``` /// use router_derive::diesel_enum; /// /// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it /// // yourself if required. /// #[derive(strum::Display, strum::EnumString)] /// #[derive(Debug)] /// #[diesel_enum(storage_type = "db_enum")] /// enum Color { /// Red, /// Green, /// Blue, /// } /// ``` #[proc_macro_derive(DieselEnum, attributes(storage_type))] pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } /// Similar to [`DieselEnum`] but uses text when storing in the database, this is to avoid /// making changes to the database when the enum variants are added or modified /// /// # Example /// [DieselEnum]: macro@crate::diesel_enum /// /// ``` /// use router_derive::{diesel_enum}; /// /// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it /// // yourself if required. /// #[derive(strum::Display, strum::EnumString)] /// #[derive(Debug)] /// #[diesel_enum(storage_type = "text")] /// enum Color { /// Red, /// Green, /// Blue, /// } /// ``` #[proc_macro_derive(DieselEnumText)] pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::diesel_enum_text_derive_inner(&ast) .unwrap_or_else(|error| error.to_compile_error()); tokens.into() } /// Derives the boilerplate code required for using an enum with `diesel` and a PostgreSQL database. /// /// Storage Type can either be "text" or "db_enum" /// Choosing text will store the enum as text in the database, whereas db_enum will map it to the /// corresponding database enum /// /// Works in tandem with the [`DieselEnum`][DieselEnum] derive macro to achieve the desired results. /// The enum is required to implement (or derive) the [`ToString`][ToString] and the /// [`FromStr`][FromStr] traits for the [`DieselEnum`][DieselEnum] derive macro to be used. /// /// [DieselEnum]: crate::DieselEnum /// [FromStr]: ::core::str::FromStr /// [ToString]: ::std::string::ToString /// /// # Example /// /// ``` /// use router_derive::{diesel_enum}; /// /// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it /// // yourself if required. (Required by the DieselEnum derive macro.) /// #[derive(strum::Display, strum::EnumString)] /// #[derive(Debug)] /// #[diesel_enum(storage_type = "text")] /// enum Color { /// Red, /// Green, /// Blue, /// } /// ``` #[proc_macro_attribute] pub fn diesel_enum( args: proc_macro::TokenStream, item: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let args_parsed = parse_macro_input!(args as DieselEnumMeta); let item = syn::parse_macro_input!(item as syn::ItemEnum); macros::diesel::diesel_enum_attribute_macro(args_parsed, &item) .unwrap_or_else(|error| error.to_compile_error()) .into() } /// A derive macro which generates the setter functions for any struct with fields /// # Example /// ``` /// use router_derive::Setter; /// /// #[derive(Setter)] /// struct Test { /// test:u32 /// } /// ``` /// The above Example will expand to /// ```rust, ignore /// impl Test { /// fn set_test(&mut self, val: u32) -> &mut Self { /// self.test = val; /// self /// } /// } /// ``` /// /// # Panics /// /// Panics if a struct without named fields is provided as input to the macro // FIXME: Remove allowed warnings, raise compile errors in a better manner instead of panicking #[allow(clippy::panic, clippy::unwrap_used)] #[proc_macro_derive(Setter, attributes(auth_based))] pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); let ident = &input.ident; // All the fields in the parent struct let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = input.data { named } else { // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; // Methods in the build struct like if the struct is // Struct i {n: u32} // this will be // pub fn set_n(&mut self,n: u32) let build_methods = fields.iter().map(|f| { let name = f.ident.as_ref().unwrap(); let method_name = format!("set_{name}"); let method_ident = syn::Ident::new(&method_name, name.span()); let ty = &f.ty; if check_if_auth_based_attr_is_present(f, "auth_based") { quote::quote! { pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{ if is_merchant_flow { self.#name = val; } self } } } else { quote::quote! { pub fn #method_ident(&mut self, val:#ty)->&mut Self{ self.#name = val; self } } } }); let output = quote::quote! { #[automatically_derived] impl #ident { #(#build_methods)* } }; output.into() } #[inline] fn check_if_auth_based_attr_is_present(f: &syn::Field, ident: &str) -> bool { for i in f.attrs.iter() { if i.path().is_ident(ident) { return true; } } false } /// Derives the [`Serialize`][Serialize] implementation for error responses that are returned by /// the API server. /// /// This macro can be only used with enums. In addition to deriving [`Serialize`][Serialize], this /// macro provides three methods: `error_type()`, `error_code()` and `error_message()`. Each enum /// variant must have three required fields: /// /// - `error_type`: This must be an enum variant which is returned by the `error_type()` method. /// - `code`: A string error code, returned by the `error_code()` method. /// - `message`: A string error message, returned by the `error_message()` method. The message /// provided will directly be passed to `format!()`. /// /// The return type of the `error_type()` method is provided by the `error_type_enum` field /// annotated to the entire enum. Thus, all enum variants provided to the `error_type` field must /// be variants of the enum provided to `error_type_enum` field. In addition, the enum passed to /// the `error_type_enum` field must implement [`Serialize`][Serialize]. /// /// **NOTE:** This macro does not implement the [`Display`][Display] trait. /// /// # Example /// /// ``` /// use router_derive::ApiError; /// /// #[derive(Clone, Debug, serde::Serialize)] /// enum ErrorType { /// StartupError, /// InternalError, /// SerdeError, /// } /// /// #[derive(Debug, ApiError)] /// #[error(error_type_enum = ErrorType)] /// enum MyError { /// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration")] /// ConfigurationError, /// #[error(error_type = ErrorType::InternalError, code = "E002", message = "A database error occurred")] /// DatabaseError, /// #[error(error_type = ErrorType::SerdeError, code = "E003", message = "Failed to deserialize object")] /// DeserializationError, /// #[error(error_type = ErrorType::SerdeError, code = "E004", message = "Failed to serialize object")] /// SerializationError, /// } /// /// impl ::std::fmt::Display for MyError { /// fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> { /// f.write_str(&self.error_message()) /// } /// } /// ``` /// /// # The Generated `Serialize` Implementation /// /// - For a simple enum variant with no fields, the generated [`Serialize`][Serialize] /// implementation has only three fields, `type`, `code` and `message`: /// /// ``` /// # use router_derive::ApiError; /// # #[derive(Clone, Debug, serde::Serialize)] /// # enum ErrorType { /// # StartupError, /// # } /// #[derive(Debug, ApiError)] /// #[error(error_type_enum = ErrorType)] /// enum MyError { /// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration")] /// ConfigurationError, /// // ... /// } /// # impl ::std::fmt::Display for MyError { /// # fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> { /// # f.write_str(&self.error_message()) /// # } /// # } /// /// let json = serde_json::json!({ /// "type": "StartupError", /// "code": "E001", /// "message": "Failed to read configuration" /// }); /// assert_eq!(serde_json::to_value(MyError::ConfigurationError).unwrap(), json); /// ``` /// /// - For an enum variant with named fields, the generated [`Serialize`][Serialize] implementation /// includes three mandatory fields, `type`, `code` and `message`, and any other fields not /// included in the message: /// /// ``` /// # use router_derive::ApiError; /// # #[derive(Clone, Debug, serde::Serialize)] /// # enum ErrorType { /// # StartupError, /// # } /// #[derive(Debug, ApiError)] /// #[error(error_type_enum = ErrorType)] /// enum MyError { /// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration file: {file_path}")] /// ConfigurationError { file_path: String, reason: String }, /// // ... /// } /// # impl ::std::fmt::Display for MyError { /// # fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> { /// # f.write_str(&self.error_message()) /// # } /// # } /// /// let json = serde_json::json!({ /// "type": "StartupError", /// "code": "E001", /// "message": "Failed to read configuration file: config.toml", /// "reason": "File not found" /// }); /// let error = MyError::ConfigurationError{ /// file_path: "config.toml".to_string(), /// reason: "File not found".to_string(), /// }; /// assert_eq!(serde_json::to_value(error).unwrap(), json); /// ``` /// /// [Serialize]: https://docs.rs/serde/latest/serde/trait.Serialize.html /// [Display]: ::core::fmt::Display #[proc_macro_derive(ApiError, attributes(error))] pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); let tokens = macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } /// Derives the `core::payments::Operation` trait on a type with a default base /// implementation. /// /// ## Usage /// On deriving, the conversion functions to be implemented need to be specified in an helper /// attribute `#[operation(..)]`. To derive all conversion functions, use `#[operation(all)]`. To /// derive specific conversion functions, pass the required identifiers to the attribute. /// `#[operation(validate_request, get_tracker)]`. Available conversions are listed below :- /// /// - validate_request /// - get_tracker /// - domain /// - update_tracker /// /// ## Example /// ```rust, ignore /// use router_derive::Operation; /// /// #[derive(Operation)] /// #[operation(all)] /// struct Point { /// x: u64, /// y: u64 /// } /// /// // The above will expand to this /// const _: () = { /// use crate::core::errors::RouterResult; /// use crate::core::payments::{GetTracker, PaymentData, UpdateTracker, ValidateRequest}; /// impl crate::core::payments::Operation for Point { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(self) /// } /// fn to_domain(&self) -> RouterResult<&dyn Domain> { /// Ok(self) /// } /// fn to_update_tracker(&self) -> RouterResult<&dyn UpdateTracker<PaymentData>> { /// Ok(self) /// } /// } /// impl crate::core::payments::Operation for &Point { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(*self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(*self) /// } /// fn to_domain(&self) -> RouterResult<&dyn Domain> { /// Ok(*self) /// } /// fn to_update_tracker(&self) -> RouterResult<&dyn UpdateTracker<PaymentData>> { /// Ok(*self) /// } /// } /// }; /// /// #[derive(Operation)] /// #[operation(validate_request, get_tracker)] /// struct Point3 { /// x: u64, /// y: u64, /// z: u64 /// } /// /// // The above will expand to this /// const _: () = { /// use crate::core::errors::RouterResult; /// use crate::core::payments::{GetTracker, PaymentData, UpdateTracker, ValidateRequest}; /// impl crate::core::payments::Operation for Point3 { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(self) /// } /// } /// impl crate::core::payments::Operation for &Point3 { /// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> { /// Ok(*self) /// } /// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> { /// Ok(*self) /// } /// } /// }; /// /// ``` /// /// The `const _: () = {}` allows us to import stuff with `use` without affecting the module /// imports, since use statements are not allowed inside of impl blocks. This technique is /// used by `diesel`. #[proc_macro_derive(PaymentOperation, attributes(operation))] pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::operation::operation_derive_inner(input) .unwrap_or_else(|err| err.to_compile_error().into()) } /// Generates different schemas with the ability to mark few fields as mandatory for certain schema /// Usage /// ``` /// use router_derive::PolymorphicSchema; /// /// #[derive(PolymorphicSchema)] /// #[generate_schemas(PaymentsCreateRequest, PaymentsConfirmRequest)] /// struct PaymentsRequest { /// #[mandatory_in(PaymentsCreateRequest = u64)] /// amount: Option<u64>, /// #[mandatory_in(PaymentsCreateRequest = String)] /// currency: Option<String>, /// payment_method: String, /// } /// ``` /// /// This will create two structs `PaymentsCreateRequest` and `PaymentsConfirmRequest` as follows /// It will retain all the other attributes that are used in the original struct, and only consume /// the #[mandatory_in] attribute to generate schemas /// /// ``` /// #[derive(utoipa::ToSchema)] /// struct PaymentsCreateRequest { /// #[schema(required = true)] /// amount: Option<u64>, /// /// #[schema(required = true)] /// currency: Option<String>, /// /// payment_method: String, /// } /// /// #[derive(utoipa::ToSchema)] /// struct PaymentsConfirmRequest { /// amount: Option<u64>, /// currency: Option<String>, /// payment_method: String, /// } /// ``` #[proc_macro_derive( PolymorphicSchema, attributes(mandatory_in, generate_schemas, remove_in) )] pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::polymorphic_macro_derive_inner(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } /// Implements the `Validate` trait to check if the config variable is present /// Usage /// ``` /// use router_derive::ConfigValidate; /// /// #[derive(ConfigValidate)] /// struct ConnectorParams { /// base_url: String, /// } /// /// enum ApplicationError { /// InvalidConfigurationValueError(String), /// } /// /// #[derive(ConfigValidate)] /// struct Connectors { /// pub stripe: ConnectorParams, /// pub checkout: ConnectorParams /// } /// ``` /// /// This will call the `validate()` function for all the fields in the struct /// /// ```rust, ignore /// impl Connectors { /// fn validate(&self) -> Result<(), ApplicationError> { /// self.stripe.validate()?; /// self.checkout.validate()?; /// } /// } /// ``` #[proc_macro_derive(ConfigValidate)] pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::misc::validate_config(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } /// Generates the function to get the value out of enum variant /// Usage /// ``` /// use router_derive::TryGetEnumVariant; /// /// impl std::fmt::Display for RedisError { /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { /// match self { /// Self::UnknownResult => write!(f, "Unknown result") /// } /// } /// } /// /// impl std::error::Error for RedisError {} /// /// #[derive(Debug)] /// enum RedisError { /// UnknownResult /// } /// /// #[derive(TryGetEnumVariant)] /// #[error(RedisError::UnknownResult)] /// enum RedisResult { /// Set(String), /// Get(i32) /// } /// ``` /// /// This will generate the function to get `String` and `i32` out of the variants /// /// ```rust, ignore /// impl RedisResult { /// fn try_into_get(&self)-> Result<i32, RedisError> { /// match self { /// Self::Get(a) => Ok(a), /// _=>Err(RedisError::UnknownResult) /// } /// } /// /// fn try_into_set(&self)-> Result<String, RedisError> { /// match self { /// Self::Set(a) => Ok(a), /// _=> Err(RedisError::UnknownResult) /// } /// } /// } /// ``` #[proc_macro_derive(TryGetEnumVariant, attributes(error))] pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::try_get_enum::try_get_enum_variant(input) .unwrap_or_else(|error| error.into_compile_error()) .into() } /// Uses the [`Serialize`] implementation of a type to derive a function implementation /// for converting nested keys structure into a HashMap of key, value where key is in /// the flattened form. /// /// Example /// /// ``` /// #[derive(Default, Serialize, FlatStruct)] /// pub struct User { /// name: String, /// address: Address, /// email: String, /// } /// /// #[derive(Default, Serialize)] /// pub struct Address { /// line1: String, /// line2: String, /// zip: String, /// } /// /// let user = User::default(); /// let flat_struct_map = user.flat_struct(); /// /// [ /// ("name", "Test"), /// ("address.line1", "1397"), /// ("address.line2", "Some street"), /// ("address.zip", "941222"), /// ("email", "test@example.com"), /// ] /// ``` #[proc_macro_derive(FlatStruct)] pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as syn::DeriveInput); let name = &input.ident; let expanded = quote::quote! { impl #name { pub fn flat_struct(&self) -> std::collections::HashMap<String, String> { use serde_json::Value; use std::collections::HashMap; fn flatten_value( value: &Value, prefix: &str, result: &mut HashMap<String, String> ) { match value { Value::Object(map) => { for (key, val) in map { let new_key = if prefix.is_empty() { key.to_string() } else { format!("{}.{}", prefix, key) }; flatten_value(val, &new_key, result); } } Value::String(s) => { result.insert(prefix.to_string(), s.clone()); } Value::Number(n) => { result.insert(prefix.to_string(), n.to_string()); } Value::Bool(b) => { result.insert(prefix.to_string(), b.to_string()); } _ => {} } } let mut result = HashMap::new(); let value = serde_json::to_value(self).unwrap(); flatten_value(&value, "", &mut result); result } } }; proc_macro::TokenStream::from(expanded) } /// Generates the permissions enum and implematations for the permissions /// /// **NOTE:** You have to make sure that all the identifiers used /// in the macro input are present in the respective enums as well. /// /// ## Usage /// ``` /// use router_derive::generate_permissions; /// /// enum Scope { /// Read, /// Write, /// } /// /// enum EntityType { /// Profile, /// Merchant, /// Org, /// } /// /// enum Resource { /// Payments, /// Refunds, /// } /// /// generate_permissions! { /// permissions: [ /// Payments: { /// scopes: [Read, Write], /// entities: [Profile, Merchant, Org] /// }, /// Refunds: { /// scopes: [Read], /// entities: [Profile, Org] /// } /// ] /// } /// ``` /// This will generate the following enum. /// ``` /// enum Permission { /// ProfilePaymentsRead, /// ProfilePaymentsWrite, /// MerchantPaymentsRead, /// MerchantPaymentsWrite, /// OrgPaymentsRead, /// OrgPaymentsWrite, /// ProfileRefundsRead, /// OrgRefundsRead, /// ``` #[proc_macro] pub fn generate_permissions(input: proc_macro::TokenStream) -> proc_macro::TokenStream { macros::generate_permissions_inner(input) } /// Generates the ToEncryptable trait for a type /// /// This macro generates the temporary structs which has the fields that needs to be encrypted /// /// fn to_encryptable: Convert the temp struct to a hashmap that can be sent over the network /// fn from_encryptable: Convert the hashmap back to temp struct #[proc_macro_derive(ToEncryption, attributes(encrypt))] pub fn derive_to_encryption_attr(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::derive_to_encryption(input) .unwrap_or_else(|err| err.into_compile_error()) .into() } /// Derives validation functionality for structs with string-based fields that have /// schema attributes specifying constraints like minimum and maximum lengths. /// /// This macro generates a `validate()` method that checks if string based fields /// meet the length requirements specified in their schema attributes. /// /// ## Supported Types /// - Option<T> or T: where T: String or Url /// /// ## Supported Schema Attributes /// /// - `min_length`: Specifies the minimum allowed character length /// - `max_length`: Specifies the maximum allowed character length /// /// ## Example /// /// ``` /// use utoipa::ToSchema; /// use router_derive::ValidateSchema; /// use url::Url; /// /// #[derive(Default, ToSchema, ValidateSchema)] /// pub struct PaymentRequest { /// #[schema(min_length = 10, max_length = 255)] /// pub description: String, /// /// #[schema(example = "https://example.com/return", max_length = 255)] /// pub return_url: Option<Url>, /// /// // Field without constraints /// pub amount: u64, /// } /// /// let payment = PaymentRequest { /// description: "Too short".to_string(), /// return_url: Some(Url::parse("https://very-long-domain.com/callback").unwrap()), /// amount: 1000, /// }; /// /// let validation_result = payment.validate(); /// assert!(validation_result.is_err()); /// assert_eq!( /// validation_result.unwrap_err(), /// "description must be at least 10 characters long. Received 9 characters" /// ); /// ``` /// /// ## Notes /// - For `Option` fields, validation is only performed when the value is `Some` /// - Fields without schema attributes or with unsupported types are ignored /// - The validation stops on the first error encountered /// - The generated `validate()` method returns `Ok(())` if all validations pass, or /// `Err(String)` with an error message if any validations fail. #[proc_macro_derive(ValidateSchema, attributes(schema))] pub fn validate_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); macros::validate_schema_derive(input) .unwrap_or_else(|error| error.into_compile_error()) .into() }
crates/router_derive/src/lib.rs
router_derive::src::lib
6,435
true
// File: crates/router_derive/src/macros.rs // Module: router_derive::src::macros pub(crate) mod api_error; pub(crate) mod diesel; pub(crate) mod generate_permissions; pub(crate) mod generate_schema; pub(crate) mod misc; pub(crate) mod operation; pub(crate) mod schema; pub(crate) mod to_encryptable; pub(crate) mod try_get_enum; mod helpers; use proc_macro2::TokenStream; use quote::quote; use syn::DeriveInput; pub(crate) use self::{ api_error::api_error_derive_inner, diesel::{diesel_enum_derive_inner, diesel_enum_text_derive_inner}, generate_permissions::generate_permissions_inner, generate_schema::polymorphic_macro_derive_inner, schema::validate_schema_derive, to_encryptable::derive_to_encryption, }; pub(crate) fn debug_as_display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); Ok(quote! { #[automatically_derived] impl #impl_generics ::core::fmt::Display for #name #ty_generics #where_clause { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> { f.write_str(&format!("{:?}", self)) } } }) }
crates/router_derive/src/macros.rs
router_derive::src::macros
319
true
// File: crates/router_derive/src/macros/operation.rs // Module: router_derive::src::macros::operation use std::str::FromStr; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use strum::IntoEnumIterator; use syn::{self, parse::Parse, DeriveInput}; use crate::macros::helpers; #[derive(Debug, Clone, Copy, strum::EnumString, strum::EnumIter, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum Derives { Sync, Cancel, Reject, Capture, ApproveData, Authorize, AuthorizeData, SyncData, CancelData, CancelPostCapture, CancelPostCaptureData, CaptureData, CompleteAuthorizeData, RejectData, SetupMandateData, Start, Verify, Session, SessionData, IncrementalAuthorization, IncrementalAuthorizationData, ExtendAuthorization, ExtendAuthorizationData, SdkSessionUpdate, SdkSessionUpdateData, PostSessionTokens, PostSessionTokensData, UpdateMetadata, UpdateMetadataData, } impl Derives { fn to_operation( self, fns: impl Iterator<Item = TokenStream> + Clone, struct_name: &syn::Ident, ) -> TokenStream { let req_type = Conversion::get_req_type(self); quote! { #[automatically_derived] impl<F:Send+Clone+Sync> Operation<F,#req_type> for #struct_name { type Data = PaymentData<F>; #(#fns)* } } } fn to_ref_operation( self, ref_fns: impl Iterator<Item = TokenStream> + Clone, struct_name: &syn::Ident, ) -> TokenStream { let req_type = Conversion::get_req_type(self); quote! { #[automatically_derived] impl<F:Send+Clone+Sync> Operation<F,#req_type> for &#struct_name { type Data = PaymentData<F>; #(#ref_fns)* } } } } #[derive(Debug, Clone, strum::EnumString, strum::EnumIter, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum Conversion { ValidateRequest, GetTracker, Domain, UpdateTracker, PostUpdateTracker, All, Invalid(String), } impl Conversion { fn get_req_type(ident: Derives) -> syn::Ident { match ident { Derives::Authorize => syn::Ident::new("PaymentsRequest", Span::call_site()), Derives::AuthorizeData => syn::Ident::new("PaymentsAuthorizeData", Span::call_site()), Derives::Sync => syn::Ident::new("PaymentsRetrieveRequest", Span::call_site()), Derives::SyncData => syn::Ident::new("PaymentsSyncData", Span::call_site()), Derives::Cancel => syn::Ident::new("PaymentsCancelRequest", Span::call_site()), Derives::CancelData => syn::Ident::new("PaymentsCancelData", Span::call_site()), Derives::ApproveData => syn::Ident::new("PaymentsApproveData", Span::call_site()), Derives::Reject => syn::Ident::new("PaymentsRejectRequest", Span::call_site()), Derives::RejectData => syn::Ident::new("PaymentsRejectData", Span::call_site()), Derives::Capture => syn::Ident::new("PaymentsCaptureRequest", Span::call_site()), Derives::CaptureData => syn::Ident::new("PaymentsCaptureData", Span::call_site()), Derives::CompleteAuthorizeData => { syn::Ident::new("CompleteAuthorizeData", Span::call_site()) } Derives::Start => syn::Ident::new("PaymentsStartRequest", Span::call_site()), Derives::Verify => syn::Ident::new("VerifyRequest", Span::call_site()), Derives::SetupMandateData => { syn::Ident::new("SetupMandateRequestData", Span::call_site()) } Derives::Session => syn::Ident::new("PaymentsSessionRequest", Span::call_site()), Derives::SessionData => syn::Ident::new("PaymentsSessionData", Span::call_site()), Derives::IncrementalAuthorization => { syn::Ident::new("PaymentsIncrementalAuthorizationRequest", Span::call_site()) } Derives::IncrementalAuthorizationData => { syn::Ident::new("PaymentsIncrementalAuthorizationData", Span::call_site()) } Derives::SdkSessionUpdate => { syn::Ident::new("PaymentsDynamicTaxCalculationRequest", Span::call_site()) } Derives::SdkSessionUpdateData => { syn::Ident::new("SdkPaymentsSessionUpdateData", Span::call_site()) } Derives::PostSessionTokens => { syn::Ident::new("PaymentsPostSessionTokensRequest", Span::call_site()) } Derives::PostSessionTokensData => { syn::Ident::new("PaymentsPostSessionTokensData", Span::call_site()) } Derives::UpdateMetadata => { syn::Ident::new("PaymentsUpdateMetadataRequest", Span::call_site()) } Derives::UpdateMetadataData => { syn::Ident::new("PaymentsUpdateMetadataData", Span::call_site()) } Derives::CancelPostCapture => { syn::Ident::new("PaymentsCancelPostCaptureRequest", Span::call_site()) } Derives::CancelPostCaptureData => { syn::Ident::new("PaymentsCancelPostCaptureData", Span::call_site()) } Derives::ExtendAuthorization => { syn::Ident::new("PaymentsExtendAuthorizationRequest", Span::call_site()) } Derives::ExtendAuthorizationData => { syn::Ident::new("PaymentsExtendAuthorizationData", Span::call_site()) } } } fn to_function(&self, ident: Derives) -> TokenStream { let req_type = Self::get_req_type(ident); match self { Self::ValidateRequest => quote! { fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type, Self::Data> + Send + Sync)> { Ok(self) } }, Self::GetTracker => quote! { fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(self) } }, Self::Domain => quote! { fn to_domain(&self) -> RouterResult<&dyn Domain<F,#req_type, Self::Data>> { Ok(self) } }, Self::UpdateTracker => quote! { fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(self) } }, Self::PostUpdateTracker => quote! { fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(self) } }, Self::Invalid(s) => { helpers::syn_error(Span::call_site(), &format!("Invalid identifier {s}")) .to_compile_error() } Self::All => { let validate_request = Self::ValidateRequest.to_function(ident); let get_tracker = Self::GetTracker.to_function(ident); let domain = Self::Domain.to_function(ident); let update_tracker = Self::UpdateTracker.to_function(ident); quote! { #validate_request #get_tracker #domain #update_tracker } } } } fn to_ref_function(&self, ident: Derives) -> TokenStream { let req_type = Self::get_req_type(ident); match self { Self::ValidateRequest => quote! { fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F, #req_type, Self::Data> + Send + Sync)> { Ok(*self) } }, Self::GetTracker => quote! { fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data,#req_type> + Send + Sync)> { Ok(*self) } }, Self::Domain => quote! { fn to_domain(&self) -> RouterResult<&(dyn Domain<F,#req_type, Self::Data>)> { Ok(*self) } }, Self::UpdateTracker => quote! { fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F, Self::Data,#req_type> + Send + Sync)> { Ok(*self) } }, Self::PostUpdateTracker => quote! { fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, #req_type> + Send + Sync)> { Ok(*self) } }, Self::Invalid(s) => { helpers::syn_error(Span::call_site(), &format!("Invalid identifier {s}")) .to_compile_error() } Self::All => { let validate_request = Self::ValidateRequest.to_ref_function(ident); let get_tracker = Self::GetTracker.to_ref_function(ident); let domain = Self::Domain.to_ref_function(ident); let update_tracker = Self::UpdateTracker.to_ref_function(ident); quote! { #validate_request #get_tracker #domain #update_tracker } } } } } mod operations_keyword { use syn::custom_keyword; custom_keyword!(operations); custom_keyword!(flow); } #[derive(Debug)] pub enum OperationsEnumMeta { Operations { keyword: operations_keyword::operations, value: Vec<Conversion>, }, Flow { keyword: operations_keyword::flow, value: Vec<Derives>, }, } #[derive(Clone)] pub struct OperationProperties { operations: Vec<Conversion>, flows: Vec<Derives>, } fn get_operation_properties( operation_enums: Vec<OperationsEnumMeta>, ) -> syn::Result<OperationProperties> { let mut operations = vec![]; let mut flows = vec![]; for operation in operation_enums { match operation { OperationsEnumMeta::Operations { value, .. } => { operations = value; } OperationsEnumMeta::Flow { value, .. } => { flows = value; } } } if operations.is_empty() { Err(syn::Error::new( Span::call_site(), "atleast one operation must be specitied", ))?; } if flows.is_empty() { Err(syn::Error::new( Span::call_site(), "atleast one flow must be specitied", ))?; } Ok(OperationProperties { operations, flows }) } impl Parse for Derives { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let text = input.parse::<syn::LitStr>()?; let value = text.value(); value.as_str().parse().map_err(|_| { syn::Error::new_spanned( &text, format!( "Unexpected value for flow: `{value}`. Possible values are `{}`", helpers::get_possible_values_for_enum::<Self>() ), ) }) } } impl Parse for Conversion { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let text = input.parse::<syn::LitStr>()?; let value = text.value(); value.as_str().parse().map_err(|_| { syn::Error::new_spanned( &text, format!( "Unexpected value for operation: `{value}`. Possible values are `{}`", helpers::get_possible_values_for_enum::<Self>() ), ) }) } } fn parse_list_string<T>(list_string: String, keyword: &str) -> syn::Result<Vec<T>> where T: FromStr + IntoEnumIterator + ToString, { list_string .split(',') .map(str::trim) .map(T::from_str) .map(|result| { result.map_err(|_| { syn::Error::new( Span::call_site(), format!( "Unexpected {keyword}, possible values are {}", helpers::get_possible_values_for_enum::<T>() ), ) }) }) .collect() } fn get_conversions(input: syn::parse::ParseStream<'_>) -> syn::Result<Vec<Conversion>> { let lit_str_list = input.parse::<syn::LitStr>()?; parse_list_string(lit_str_list.value(), "operation") } fn get_derives(input: syn::parse::ParseStream<'_>) -> syn::Result<Vec<Derives>> { let lit_str_list = input.parse::<syn::LitStr>()?; parse_list_string(lit_str_list.value(), "flow") } impl Parse for OperationsEnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(operations_keyword::operations) { let keyword = input.parse()?; input.parse::<syn::Token![=]>()?; let value = get_conversions(input)?; Ok(Self::Operations { keyword, value }) } else if lookahead.peek(operations_keyword::flow) { let keyword = input.parse()?; input.parse::<syn::Token![=]>()?; let value = get_derives(input)?; Ok(Self::Flow { keyword, value }) } else { Err(lookahead.error()) } } } trait OperationsDeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<OperationsEnumMeta>>; } impl OperationsDeriveInputExt for DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<OperationsEnumMeta>> { helpers::get_metadata_inner("operation", &self.attrs) } } impl ToTokens for OperationsEnumMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::Operations { keyword, .. } => keyword.to_tokens(tokens), Self::Flow { keyword, .. } => keyword.to_tokens(tokens), } } } pub fn operation_derive_inner(input: DeriveInput) -> syn::Result<proc_macro::TokenStream> { let struct_name = &input.ident; let operations_meta = input.get_metadata()?; let operation_properties = get_operation_properties(operations_meta)?; let current_crate = syn::Ident::new("crate", Span::call_site()); let trait_derive = operation_properties .clone() .flows .into_iter() .map(|derive| { let fns = operation_properties .operations .iter() .map(|conversion| conversion.to_function(derive)); derive.to_operation(fns, struct_name) }) .collect::<Vec<_>>(); let ref_trait_derive = operation_properties .flows .into_iter() .map(|derive| { let fns = operation_properties .operations .iter() .map(|conversion| conversion.to_ref_function(derive)); derive.to_ref_operation(fns, struct_name) }) .collect::<Vec<_>>(); let trait_derive = quote! { #(#ref_trait_derive)* #(#trait_derive)* }; let output = quote! { const _: () = { use #current_crate::core::errors::RouterResult; use #current_crate::core::payments::{PaymentData,operations::{ ValidateRequest, PostUpdateTracker, GetTracker, UpdateTracker, }}; use #current_crate::types::{ SetupMandateRequestData, PaymentsSyncData, PaymentsCaptureData, PaymentsCancelData, PaymentsApproveData, PaymentsRejectData, PaymentsAuthorizeData, PaymentsSessionData, CompleteAuthorizeData, PaymentsIncrementalAuthorizationData, SdkPaymentsSessionUpdateData, PaymentsPostSessionTokensData, PaymentsUpdateMetadataData, PaymentsCancelPostCaptureData, PaymentsExtendAuthorizationData, api::{ PaymentsCaptureRequest, PaymentsCancelRequest, PaymentsApproveRequest, PaymentsRejectRequest, PaymentsRetrieveRequest, PaymentsRequest, PaymentsStartRequest, PaymentsSessionRequest, VerifyRequest, PaymentsDynamicTaxCalculationRequest, PaymentsIncrementalAuthorizationRequest, PaymentsPostSessionTokensRequest, PaymentsUpdateMetadataRequest, PaymentsCancelPostCaptureRequest, PaymentsExtendAuthorizationRequest, } }; #trait_derive }; }; Ok(proc_macro::TokenStream::from(output)) }
crates/router_derive/src/macros/operation.rs
router_derive::src::macros::operation
3,647
true
// File: crates/router_derive/src/macros/api_error.rs // Module: router_derive::src::macros::api_error mod helpers; use std::collections::HashMap; use proc_macro2::TokenStream; use quote::quote; use syn::{ punctuated::Punctuated, token::Comma, Data, DeriveInput, Fields, Ident, ImplGenerics, TypeGenerics, Variant, WhereClause, }; use crate::macros::{ api_error::helpers::{ check_missing_attributes, get_unused_fields, ErrorTypeProperties, ErrorVariantProperties, HasErrorTypeProperties, HasErrorVariantProperties, }, helpers::non_enum_error, }; pub(crate) fn api_error_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let variants = match &ast.data { Data::Enum(e) => &e.variants, _ => return Err(non_enum_error()), }; let type_properties = ast.get_type_properties()?; let mut variants_properties_map = HashMap::new(); for variant in variants { let variant_properties = variant.get_variant_properties()?; check_missing_attributes(variant, &variant_properties)?; variants_properties_map.insert(variant, variant_properties); } let error_type_fn = implement_error_type(name, &type_properties, &variants_properties_map); let error_code_fn = implement_error_code(name, &variants_properties_map); let error_message_fn = implement_error_message(name, &variants_properties_map); let serialize_impl = implement_serialize( name, (&impl_generics, &ty_generics, where_clause), &type_properties, &variants_properties_map, ); Ok(quote! { #[automatically_derived] impl #impl_generics std::error::Error for #name #ty_generics #where_clause {} #[automatically_derived] impl #impl_generics #name #ty_generics #where_clause { #error_type_fn #error_code_fn #error_message_fn } #serialize_impl }) } fn implement_error_type( enum_name: &Ident, type_properties: &ErrorTypeProperties, variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>, ) -> TokenStream { let mut arms = Vec::new(); for (&variant, properties) in variants_properties_map.iter() { let ident = &variant.ident; let params = match variant.fields { Fields::Unit => quote! {}, Fields::Unnamed(..) => quote! { (..) }, Fields::Named(..) => quote! { {..} }, }; // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_type = properties.error_type.as_ref().unwrap(); arms.push(quote! { #enum_name::#ident #params => #error_type }); } // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_type_enum = type_properties.error_type_enum.as_ref().unwrap(); quote! { pub fn error_type(&self) -> #error_type_enum { match self { #(#arms),* } } } } fn implement_error_code( enum_name: &Ident, variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>, ) -> TokenStream { let mut arms = Vec::new(); for (&variant, properties) in variants_properties_map.iter() { let ident = &variant.ident; let params = match variant.fields { Fields::Unit => quote! {}, Fields::Unnamed(..) => quote! { (..) }, Fields::Named(..) => quote! { {..} }, }; // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_code = properties.code.as_ref().unwrap(); arms.push(quote! { #enum_name::#ident #params => #error_code.to_string() }); } quote! { pub fn error_code(&self) -> String { match self { #(#arms),* } } } } fn implement_error_message( enum_name: &Ident, variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>, ) -> TokenStream { let mut arms = Vec::new(); for (&variant, properties) in variants_properties_map.iter() { let ident = &variant.ident; let params = match variant.fields { Fields::Unit => quote! {}, Fields::Unnamed(..) => quote! { (..) }, Fields::Named(ref fields) => { let fields = fields .named .iter() .map(|f| { // Safety: Named fields are guaranteed to have an identifier. #[allow(clippy::unwrap_used)] f.ident.as_ref().unwrap() }) .collect::<Punctuated<&Ident, Comma>>(); quote! { {#fields} } } }; // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_message = properties.message.as_ref().unwrap(); arms.push(quote! { #enum_name::#ident #params => format!(#error_message) }); } quote! { pub fn error_message(&self) -> String { match self { #(#arms),* } } } } fn implement_serialize( enum_name: &Ident, generics: (&ImplGenerics<'_>, &TypeGenerics<'_>, Option<&WhereClause>), type_properties: &ErrorTypeProperties, variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>, ) -> TokenStream { let (impl_generics, ty_generics, where_clause) = generics; let mut arms = Vec::new(); for (&variant, properties) in variants_properties_map.iter() { let ident = &variant.ident; let params = match variant.fields { Fields::Unit => quote! {}, Fields::Unnamed(..) => quote! { (..) }, Fields::Named(ref fields) => { let fields = fields .named .iter() .map(|f| { // Safety: Named fields are guaranteed to have an identifier. #[allow(clippy::unwrap_used)] f.ident.as_ref().unwrap() }) .collect::<Punctuated<&Ident, Comma>>(); quote! { {#fields} } } }; // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_message = properties.message.as_ref().unwrap(); let msg_unused_fields = get_unused_fields(&variant.fields, &error_message.value(), &properties.ignore); // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_type_enum = type_properties.error_type_enum.as_ref().unwrap(); let response_definition = if msg_unused_fields.is_empty() { quote! { #[derive(Clone, Debug, serde::Serialize)] struct ErrorResponse { #[serde(rename = "type")] error_type: #error_type_enum, code: String, message: String, } } } else { let mut extra_fields = Vec::new(); for field in &msg_unused_fields { let vis = &field.vis; // Safety: `msq_unused_fields` is expected to contain named fields only. #[allow(clippy::unwrap_used)] let ident = &field.ident.as_ref().unwrap(); let ty = &field.ty; extra_fields.push(quote! { #vis #ident: #ty }); } quote! { #[derive(Clone, Debug, serde::Serialize)] struct ErrorResponse #ty_generics #where_clause { #[serde(rename = "type")] error_type: #error_type_enum, code: String, message: String, #(#extra_fields),* } } }; // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let error_type = properties.error_type.as_ref().unwrap(); // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let code = properties.code.as_ref().unwrap(); // Safety: Missing attributes are already checked before this function is called. #[allow(clippy::unwrap_used)] let message = properties.message.as_ref().unwrap(); let extra_fields = msg_unused_fields .iter() .map(|field| { // Safety: `extra_fields` is expected to contain named fields only. #[allow(clippy::unwrap_used)] let field_name = field.ident.as_ref().unwrap(); quote! { #field_name: #field_name.to_owned() } }) .collect::<Vec<TokenStream>>(); arms.push(quote! { #enum_name::#ident #params => { #response_definition let response = ErrorResponse { error_type: #error_type, code: #code.to_string(), message: format!(#message), #(#extra_fields),* }; response.serialize(serializer) } }); } quote! { #[automatically_derived] impl #impl_generics serde::Serialize for #enum_name #ty_generics #where_clause { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match self { #(#arms),* } } } } }
crates/router_derive/src/macros/api_error.rs
router_derive::src::macros::api_error
2,089
true
// File: crates/router_derive/src/macros/try_get_enum.rs // Module: router_derive::src::macros::try_get_enum use proc_macro2::Span; use quote::ToTokens; use syn::{parse::Parse, punctuated::Punctuated}; mod try_get_keyword { use syn::custom_keyword; custom_keyword!(error_type); } #[derive(Debug)] pub struct TryGetEnumMeta { error_type: syn::Ident, variant: syn::Ident, } impl Parse for TryGetEnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let error_type = input.parse()?; _ = input.parse::<syn::Token![::]>()?; let variant = input.parse()?; Ok(Self { error_type, variant, }) } } trait TryGetDeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<TryGetEnumMeta>>; } impl TryGetDeriveInputExt for syn::DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<TryGetEnumMeta>> { super::helpers::get_metadata_inner("error", &self.attrs) } } impl ToTokens for TryGetEnumMeta { fn to_tokens(&self, _: &mut proc_macro2::TokenStream) {} } /// Try and get the variants for an enum pub fn try_get_enum_variant( input: syn::DeriveInput, ) -> Result<proc_macro2::TokenStream, syn::Error> { let name = &input.ident; let parsed_error_type = input.get_metadata()?; let (error_type, error_variant) = parsed_error_type .first() .ok_or(syn::Error::new( Span::call_site(), "One error should be specified", )) .map(|error_struct| (&error_struct.error_type, &error_struct.variant))?; let (impl_generics, generics, where_clause) = input.generics.split_for_impl(); let variants = get_enum_variants(&input.data)?; let try_into_fns = variants.iter().map(|variant| { let variant_name = &variant.ident; let variant_field = get_enum_variant_field(variant)?; let variant_types = variant_field.iter().map(|f|f.ty.clone()); let try_into_fn = syn::Ident::new( &format!("try_into_{}", variant_name.to_string().to_lowercase()), Span::call_site(), ); Ok(quote::quote! { pub fn #try_into_fn(self)->Result<(#(#variant_types),*),error_stack::Report<#error_type>> { match self { Self::#variant_name(inner) => Ok(inner), _=> Err(error_stack::report!(#error_type::#error_variant)), } } }) }).collect::<Result<Vec<proc_macro2::TokenStream>,syn::Error>>()?; let expanded = quote::quote! { impl #impl_generics #name #generics #where_clause { #(#try_into_fns)* } }; Ok(expanded) } /// Get variants from Enum fn get_enum_variants(data: &syn::Data) -> syn::Result<Punctuated<syn::Variant, syn::token::Comma>> { if let syn::Data::Enum(syn::DataEnum { variants, .. }) = data { Ok(variants.clone()) } else { Err(super::helpers::non_enum_error()) } } /// Get Field from an enum variant fn get_enum_variant_field( variant: &syn::Variant, ) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> { let field = match variant.fields.clone() { syn::Fields::Unnamed(un) => un.unnamed, syn::Fields::Named(n) => n.named, syn::Fields::Unit => { return Err(super::helpers::syn_error( Span::call_site(), "The enum is a unit variant it's not supported", )) } }; Ok(field) }
crates/router_derive/src/macros/try_get_enum.rs
router_derive::src::macros::try_get_enum
890
true
// File: crates/router_derive/src/macros/misc.rs // Module: router_derive::src::macros::misc pub fn get_field_type(field_type: syn::Type) -> Option<syn::Ident> { if let syn::Type::Path(path) = field_type { path.path .segments .last() .map(|last_path_segment| last_path_segment.ident.to_owned()) } else { None } } /// Implement the `validate` function for the struct by calling `validate` function on the fields pub fn validate_config(input: syn::DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> { let fields = super::helpers::get_struct_fields(input.data) .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?; let struct_name = input.ident; let function_expansions = fields .into_iter() .flat_map(|field| field.ident.to_owned().zip(get_field_type(field.ty))) .filter_map(|(field_ident, field_type_ident)| { // Check if a field is a leaf field, only String ( connector urls ) is supported for now let field_ident_string = field_ident.to_string(); let is_optional_field = field_type_ident.eq("Option"); let is_secret_field = field_type_ident.eq("Secret"); // Do not call validate if it is an optional field if !is_optional_field && !is_secret_field { let is_leaf_field = field_type_ident.eq("String"); let validate_expansion = if is_leaf_field { quote::quote!(common_utils::fp_utils::when( self.#field_ident.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( format!("{} must not be empty for {}", #field_ident_string, parent_field).into(), )) } )?; ) } else { quote::quote!( self.#field_ident.validate(#field_ident_string)?; ) }; Some(validate_expansion) } else { None } }) .collect::<Vec<_>>(); let expansion = quote::quote! { impl #struct_name { /// Validates that the configuration provided for the `parent_field` does not contain empty or default values pub fn validate(&self, parent_field: &str) -> Result<(), ApplicationError> { #(#function_expansions)* Ok(()) } } }; Ok(expansion) }
crates/router_derive/src/macros/misc.rs
router_derive::src::macros::misc
537
true
// File: crates/router_derive/src/macros/diesel.rs // Module: router_derive::src::macros::diesel use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, ToTokens}; use syn::{parse::Parse, Data, DeriveInput, ItemEnum}; use crate::macros::helpers; pub(crate) fn diesel_enum_text_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); match &ast.data { Data::Enum(_) => (), _ => return Err(helpers::non_enum_error()), }; Ok(quote! { #[automatically_derived] impl #impl_generics ::diesel::serialize::ToSql<::diesel::sql_types::Text, ::diesel::pg::Pg> for #name #ty_generics #where_clause { fn to_sql<'b>(&'b self, out: &mut ::diesel::serialize::Output<'b, '_, ::diesel::pg::Pg>) -> ::diesel::serialize::Result { use ::std::io::Write; out.write_all(self.to_string().as_bytes())?; Ok(::diesel::serialize::IsNull::No) } } #[automatically_derived] impl #impl_generics ::diesel::deserialize::FromSql<::diesel::sql_types::Text, ::diesel::pg::Pg> for #name #ty_generics #where_clause { fn from_sql(value: ::diesel::pg::PgValue) -> diesel::deserialize::Result<Self> { use ::core::str::FromStr; Self::from_str(::core::str::from_utf8(value.as_bytes())?) .map_err(|_| "Unrecognized enum variant".into()) } } }) } pub(crate) fn diesel_enum_db_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); match &ast.data { Data::Enum(_) => (), _ => return Err(helpers::non_enum_error()), }; let struct_name = format_ident!("Db{name}"); let type_name = format!("{name}"); Ok(quote! { #[derive(::core::clone::Clone, ::core::marker::Copy, ::core::fmt::Debug, ::diesel::QueryId, ::diesel::SqlType)] #[diesel(postgres_type(name = #type_name))] pub struct #struct_name; #[automatically_derived] impl #impl_generics ::diesel::serialize::ToSql<#struct_name, ::diesel::pg::Pg> for #name #ty_generics #where_clause { fn to_sql<'b>(&'b self, out: &mut ::diesel::serialize::Output<'b, '_, ::diesel::pg::Pg>) -> ::diesel::serialize::Result { use ::std::io::Write; out.write_all(self.to_string().as_bytes())?; Ok(::diesel::serialize::IsNull::No) } } #[automatically_derived] impl #impl_generics ::diesel::deserialize::FromSql<#struct_name, ::diesel::pg::Pg> for #name #ty_generics #where_clause { fn from_sql(value: ::diesel::pg::PgValue) -> diesel::deserialize::Result<Self> { use ::core::str::FromStr; Self::from_str(::core::str::from_utf8(value.as_bytes())?) .map_err(|_| "Unrecognized enum variant".into()) } } }) } mod diesel_keyword { use syn::custom_keyword; custom_keyword!(storage_type); custom_keyword!(db_enum); custom_keyword!(text); } #[derive(Debug, strum::EnumString, strum::EnumIter, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum StorageType { /// Store the Enum as Text value in the database Text, /// Store the Enum as Enum in the database. This requires a corresponding enum to be created /// in the database with the same name DbEnum, } #[derive(Debug)] pub enum DieselEnumMeta { StorageTypeEnum { keyword: diesel_keyword::storage_type, value: StorageType, }, } impl Parse for StorageType { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let text = input.parse::<syn::LitStr>()?; let value = text.value(); value.as_str().parse().map_err(|_| { syn::Error::new_spanned( &text, format!( "Unexpected value for storage_type: `{value}`. Possible values are `{}`", helpers::get_possible_values_for_enum::<Self>() ), ) }) } } impl DieselEnumMeta { pub fn get_storage_type(&self) -> &StorageType { match self { Self::StorageTypeEnum { value, .. } => value, } } } impl Parse for DieselEnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(diesel_keyword::storage_type) { let keyword = input.parse()?; input.parse::<syn::Token![=]>()?; let value = input.parse()?; Ok(Self::StorageTypeEnum { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for DieselEnumMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::StorageTypeEnum { keyword, .. } => keyword.to_tokens(tokens), } } } trait DieselDeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<DieselEnumMeta>>; } impl DieselDeriveInputExt for DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<DieselEnumMeta>> { helpers::get_metadata_inner("storage_type", &self.attrs) } } pub(crate) fn diesel_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let storage_type = ast.get_metadata()?; match storage_type .first() .ok_or(syn::Error::new( Span::call_site(), "Storage type must be specified", ))? .get_storage_type() { StorageType::Text => diesel_enum_text_derive_inner(ast), StorageType::DbEnum => diesel_enum_db_enum_derive_inner(ast), } } /// Based on the storage type, derive appropriate diesel traits /// This will add the appropriate #[diesel(sql_type)] /// Since the `FromSql` and `ToSql` have to be derived for all the enums, this will add the /// `DieselEnum` derive trait. pub(crate) fn diesel_enum_attribute_macro( diesel_enum_meta: DieselEnumMeta, item: &ItemEnum, ) -> syn::Result<TokenStream> { let diesel_derives = quote!(#[derive(diesel::AsExpression, diesel::FromSqlRow, router_derive::DieselEnum) ]); match diesel_enum_meta { DieselEnumMeta::StorageTypeEnum { value: storage_type, .. } => match storage_type { StorageType::Text => Ok(quote! { #diesel_derives #[diesel(sql_type = ::diesel::sql_types::Text)] #[storage_type(storage_type = "text")] #item }), StorageType::DbEnum => { let name = &item.ident; let type_name = format_ident!("Db{name}"); Ok(quote! { #diesel_derives #[diesel(sql_type = #type_name)] #[storage_type(storage_type= "db_enum")] #item }) } }, } }
crates/router_derive/src/macros/diesel.rs
router_derive::src::macros::diesel
1,768
true
// File: crates/router_derive/src/macros/helpers.rs // Module: router_derive::src::macros::helpers use proc_macro2::Span; use quote::ToTokens; use syn::{parse::Parse, punctuated::Punctuated, spanned::Spanned, Attribute, Token}; pub fn non_enum_error() -> syn::Error { syn::Error::new(Span::call_site(), "This macro only supports enums.") } pub(super) fn occurrence_error<T: ToTokens>( first_keyword: T, second_keyword: T, attr: &str, ) -> syn::Error { let mut error = syn::Error::new_spanned( second_keyword, format!("Found multiple occurrences of error({attr})"), ); error.combine(syn::Error::new_spanned(first_keyword, "first one here")); error } pub(super) fn syn_error(span: Span, message: &str) -> syn::Error { syn::Error::new(span, message) } /// Get all the variants of a enum in the form of a string pub fn get_possible_values_for_enum<T>() -> String where T: strum::IntoEnumIterator + ToString, { T::iter() .map(|variants| variants.to_string()) .collect::<Vec<_>>() .join(", ") } pub(super) fn get_metadata_inner<'a, T: Parse + Spanned>( ident: &str, attrs: impl IntoIterator<Item = &'a Attribute>, ) -> syn::Result<Vec<T>> { attrs .into_iter() .filter(|attr| attr.path().is_ident(ident)) .try_fold(Vec::new(), |mut vec, attr| { vec.extend(attr.parse_args_with(Punctuated::<T, Token![,]>::parse_terminated)?); Ok(vec) }) } pub(super) fn get_struct_fields( data: syn::Data, ) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> { if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = data { Ok(named.to_owned()) } else { Err(syn::Error::new( Span::call_site(), "This macro cannot be used on structs with no fields", )) } }
crates/router_derive/src/macros/helpers.rs
router_derive::src::macros::helpers
516
true
// File: crates/router_derive/src/macros/schema.rs // Module: router_derive::src::macros::schema mod helpers; use quote::quote; use crate::macros::{ helpers as macro_helpers, schema::helpers::{HasSchemaParameters, IsSchemaFieldApplicableForValidation}, }; pub fn validate_schema_derive(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let name = &input.ident; // Extract struct fields let fields = macro_helpers::get_struct_fields(input.data) .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?; // Map over each field let validation_checks = fields.iter().filter_map(|field| { let field_name = field.ident.as_ref()?; let field_type = &field.ty; // Check if field type is valid for validation let is_field_valid = match IsSchemaFieldApplicableForValidation::from(field_type) { IsSchemaFieldApplicableForValidation::Invalid => return None, val => val, }; // Parse attribute parameters for 'schema' let schema_params = match field.get_schema_parameters() { Ok(params) => params, Err(_) => return None, }; let min_length = schema_params.min_length; let max_length = schema_params.max_length; // Skip if no length validation is needed if min_length.is_none() && max_length.is_none() { return None; } let min_check = min_length.map(|min_val| { quote! { if value_len < #min_val { return Err(format!("{} must be at least {} characters long. Received {} characters", stringify!(#field_name), #min_val, value_len)); } } }).unwrap_or_else(|| quote! {}); let max_check = max_length.map(|max_val| { quote! { if value_len > #max_val { return Err(format!("{} must be at most {} characters long. Received {} characters", stringify!(#field_name), #max_val, value_len)); } } }).unwrap_or_else(|| quote! {}); // Generate length validation if is_field_valid == IsSchemaFieldApplicableForValidation::ValidOptional { Some(quote! { if let Some(value) = &self.#field_name { let value_len = value.as_str().len(); #min_check #max_check } }) } else { Some(quote! { { let value_len = self.#field_name.as_str().len(); #min_check #max_check } }) } }).collect::<Vec<_>>(); Ok(quote! { impl #name { pub fn validate(&self) -> Result<(), String> { #(#validation_checks)* Ok(()) } } }) }
crates/router_derive/src/macros/schema.rs
router_derive::src::macros::schema
622
true
// File: crates/router_derive/src/macros/to_encryptable.rs // Module: router_derive::src::macros::to_encryptable use std::iter::Iterator; use quote::{format_ident, quote}; use syn::{parse::Parse, punctuated::Punctuated, token::Comma, Field, Ident, Type as SynType}; use crate::macros::{helpers::get_struct_fields, misc::get_field_type}; pub struct FieldMeta { _meta_type: Ident, pub value: Ident, } impl Parse for FieldMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let _meta_type: Ident = input.parse()?; input.parse::<syn::Token![=]>()?; let value: Ident = input.parse()?; Ok(Self { _meta_type, value }) } } impl quote::ToTokens for FieldMeta { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { self.value.to_tokens(tokens); } } fn get_encryption_ty_meta(field: &Field) -> Option<FieldMeta> { let attrs = &field.attrs; attrs .iter() .flat_map(|s| s.parse_args::<FieldMeta>()) .find(|s| s._meta_type.eq("ty")) } fn get_inner_type(path: &syn::TypePath) -> syn::Result<syn::TypePath> { path.path .segments .last() .and_then(|segment| match &segment.arguments { syn::PathArguments::AngleBracketed(args) => args.args.first(), _ => None, }) .and_then(|arg| match arg { syn::GenericArgument::Type(SynType::Path(path)) => Some(path.clone()), _ => None, }) .ok_or_else(|| { syn::Error::new( proc_macro2::Span::call_site(), "Only path fields are supported", ) }) } /// This function returns the inner most type recursively /// For example: /// /// In the case of `Encryptable<Secret<String>>> this returns String fn get_inner_most_type(ty: SynType) -> syn::Result<Ident> { fn get_inner_type_recursive(path: syn::TypePath) -> syn::Result<syn::TypePath> { match get_inner_type(&path) { Ok(inner_path) => get_inner_type_recursive(inner_path), Err(_) => Ok(path), } } match ty { SynType::Path(path) => { let inner_path = get_inner_type_recursive(path)?; inner_path .path .segments .last() .map(|last_segment| last_segment.ident.to_owned()) .ok_or_else(|| { syn::Error::new( proc_macro2::Span::call_site(), "At least one ident must be specified", ) }) } _ => Err(syn::Error::new( proc_macro2::Span::call_site(), "Only path fields are supported", )), } } /// This returns the field which implement #[encrypt] attribute fn get_encryptable_fields(fields: Punctuated<Field, Comma>) -> Vec<Field> { fields .into_iter() .filter(|field| { field .attrs .iter() .any(|attr| attr.path().is_ident("encrypt")) }) .collect() } /// This function returns the inner most type of a field fn get_field_and_inner_types(fields: &[Field]) -> Vec<(Field, Ident)> { fields .iter() .flat_map(|field| { get_inner_most_type(field.ty.clone()).map(|field_name| (field.to_owned(), field_name)) }) .collect() } /// The type of the struct for which the batch encryption/decryption needs to be implemented #[derive(PartialEq, Copy, Clone)] enum StructType { Encrypted, Decrypted, DecryptedUpdate, FromRequest, Updated, } impl StructType { /// Generates the fields for temporary structs which consists of the fields that should be /// encrypted/decrypted fn generate_struct_fields(self, fields: &[(Field, Ident)]) -> Vec<proc_macro2::TokenStream> { fields .iter() .map(|(field, inner_ty)| { let provided_ty = get_encryption_ty_meta(field); let is_option = get_field_type(field.ty.clone()) .map(|f| f.eq("Option")) .unwrap_or_default(); let ident = &field.ident; let inner_ty = if let Some(ref ty) = provided_ty { &ty.value } else { inner_ty }; match (self, is_option) { (Self::Encrypted, true) => quote! { pub #ident: Option<Encryption> }, (Self::Encrypted, false) => quote! { pub #ident: Encryption }, (Self::Decrypted, true) => { quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> } } (Self::Decrypted, false) => { quote! { pub #ident: Encryptable<Secret<#inner_ty>> } } (Self::DecryptedUpdate, _) => { quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> } } (Self::FromRequest, true) => { quote! { pub #ident: Option<Secret<#inner_ty>> } } (Self::FromRequest, false) => quote! { pub #ident: Secret<#inner_ty> }, (Self::Updated, _) => quote! { pub #ident: Option<Secret<#inner_ty>> }, } }) .collect() } /// Generates the ToEncryptable trait implementation fn generate_impls( self, gen1: proc_macro2::TokenStream, gen2: proc_macro2::TokenStream, gen3: proc_macro2::TokenStream, impl_st: proc_macro2::TokenStream, inner: &[Field], ) -> proc_macro2::TokenStream { let map_length = inner.len(); let to_encryptable_impl = inner.iter().flat_map(|field| { get_field_type(field.ty.clone()).map(|field_ty| { let is_option = field_ty.eq("Option"); let field_ident = &field.ident; let field_ident_string = field_ident.as_ref().map(|s| s.to_string()); if is_option || self == Self::Updated { quote! { self.#field_ident.map(|s| map.insert(#field_ident_string.to_string(), s)) } } else { quote! { map.insert(#field_ident_string.to_string(), self.#field_ident) } } }) }); let from_encryptable_impl = inner.iter().flat_map(|field| { get_field_type(field.ty.clone()).map(|field_ty| { let is_option = field_ty.eq("Option"); let field_ident = &field.ident; let field_ident_string = field_ident.as_ref().map(|s| s.to_string()); if is_option || self == Self::Updated { quote! { #field_ident: map.remove(#field_ident_string) } } else { quote! { #field_ident: map.remove(#field_ident_string).ok_or( error_stack::report!(common_utils::errors::ParsingError::EncodeError( "Unable to convert from HashMap", )) )? } } }) }); quote! { impl ToEncryptable<#gen1, #gen2, #gen3> for #impl_st { fn to_encryptable(self) -> FxHashMap<String, #gen3> { let mut map = FxHashMap::with_capacity_and_hasher(#map_length, Default::default()); #(#to_encryptable_impl;)* map } fn from_encryptable( mut map: FxHashMap<String, Encryptable<#gen2>>, ) -> CustomResult<#gen1, common_utils::errors::ParsingError> { Ok(#gen1 { #(#from_encryptable_impl,)* }) } } } } } /// This function generates the temporary struct and ToEncryptable impls for the temporary structs fn generate_to_encryptable( struct_name: Ident, fields: Vec<Field>, ) -> syn::Result<proc_macro2::TokenStream> { let struct_types = [ // The first two are to be used as return types we do not need to implement ToEncryptable // on it ("Decrypted", StructType::Decrypted), ("DecryptedUpdate", StructType::DecryptedUpdate), ("FromRequestEncryptable", StructType::FromRequest), ("Encrypted", StructType::Encrypted), ("UpdateEncryptable", StructType::Updated), ]; let inner_types = get_field_and_inner_types(&fields); let inner_type = inner_types.first().ok_or_else(|| { syn::Error::new( proc_macro2::Span::call_site(), "Please use the macro with attribute #[encrypt] on the fields you want to encrypt", ) })?; let provided_ty = get_encryption_ty_meta(&inner_type.0) .map(|ty| ty.value.clone()) .unwrap_or(inner_type.1.clone()); let structs = struct_types.iter().map(|(prefix, struct_type)| { let name = format_ident!("{}{}", prefix, struct_name); let temp_fields = struct_type.generate_struct_fields(&inner_types); quote! { pub struct #name { #(#temp_fields,)* } } }); // These implementations shouldn't be implemented Decrypted and DecryptedUpdate temp structs // So skip the first two entries in the list let impls = struct_types .iter() .skip(2) .map(|(prefix, struct_type)| { let name = format_ident!("{}{}", prefix, struct_name); let impl_block = if *struct_type != StructType::DecryptedUpdate || *struct_type != StructType::Decrypted { let (gen1, gen2, gen3) = match struct_type { StructType::FromRequest => { let decrypted_name = format_ident!("Decrypted{}", struct_name); ( quote! { #decrypted_name }, quote! { Secret<#provided_ty> }, quote! { Secret<#provided_ty> }, ) } StructType::Encrypted => { let decrypted_name = format_ident!("Decrypted{}", struct_name); ( quote! { #decrypted_name }, quote! { Secret<#provided_ty> }, quote! { Encryption }, ) } StructType::Updated => { let decrypted_update_name = format_ident!("DecryptedUpdate{}", struct_name); ( quote! { #decrypted_update_name }, quote! { Secret<#provided_ty> }, quote! { Secret<#provided_ty> }, ) } //Unreachable statement _ => (quote! {}, quote! {}, quote! {}), }; struct_type.generate_impls(gen1, gen2, gen3, quote! { #name }, &fields) } else { quote! {} }; Ok(quote! { #impl_block }) }) .collect::<syn::Result<Vec<_>>>()?; Ok(quote! { #(#structs)* #(#impls)* }) } pub fn derive_to_encryption( input: syn::DeriveInput, ) -> Result<proc_macro2::TokenStream, syn::Error> { let struct_name = input.ident; let fields = get_encryptable_fields(get_struct_fields(input.data)?); generate_to_encryptable(struct_name, fields) }
crates/router_derive/src/macros/to_encryptable.rs
router_derive::src::macros::to_encryptable
2,564
true
// File: crates/router_derive/src/macros/generate_schema.rs // Module: router_derive::src::macros::generate_schema use std::collections::{HashMap, HashSet}; use indexmap::IndexMap; use syn::{self, parse::Parse, parse_quote, punctuated::Punctuated, Token}; use crate::macros::helpers; /// Parse schemas from attribute /// Example /// /// #[mandatory_in(PaymentsCreateRequest, PaymentsUpdateRequest)] /// would return /// /// [PaymentsCreateRequest, PaymentsUpdateRequest] fn get_inner_path_ident(attribute: &syn::Attribute) -> syn::Result<Vec<syn::Ident>> { Ok(attribute .parse_args_with(Punctuated::<syn::Ident, Token![,]>::parse_terminated)? .into_iter() .collect::<Vec<_>>()) } #[allow(dead_code)] /// Get the type of field fn get_field_type(field_type: syn::Type) -> syn::Result<syn::Ident> { if let syn::Type::Path(path) = field_type { path.path .segments .last() .map(|last_path_segment| last_path_segment.ident.to_owned()) .ok_or(syn::Error::new( proc_macro2::Span::call_site(), "Atleast one ident must be specified", )) } else { Err(syn::Error::new( proc_macro2::Span::call_site(), "Only path fields are supported", )) } } #[allow(dead_code)] /// Get the inner type of option fn get_inner_option_type(field: &syn::Type) -> syn::Result<syn::Ident> { if let syn::Type::Path(ref path) = &field { if let Some(segment) = path.path.segments.last() { if let syn::PathArguments::AngleBracketed(ref args) = &segment.arguments { if let Some(syn::GenericArgument::Type(ty)) = args.args.first() { return get_field_type(ty.clone()); } } } } Err(syn::Error::new( proc_macro2::Span::call_site(), "Only path fields are supported", )) } mod schema_keyword { use syn::custom_keyword; custom_keyword!(schema); } #[derive(Debug, Clone)] pub struct SchemaMeta { struct_name: syn::Ident, type_ident: syn::Ident, } /// parse #[mandatory_in(PaymentsCreateRequest = u64)] impl Parse for SchemaMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let struct_name = input.parse::<syn::Ident>()?; input.parse::<syn::Token![=]>()?; let type_ident = input.parse::<syn::Ident>()?; Ok(Self { struct_name, type_ident, }) } } impl quote::ToTokens for SchemaMeta { fn to_tokens(&self, _: &mut proc_macro2::TokenStream) {} } pub fn polymorphic_macro_derive_inner( input: syn::DeriveInput, ) -> syn::Result<proc_macro2::TokenStream> { let schemas_to_create = helpers::get_metadata_inner::<syn::Ident>("generate_schemas", &input.attrs)?; let fields = helpers::get_struct_fields(input.data) .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?; // Go through all the fields and create a mapping of required fields for a schema // PaymentsCreate -> ["amount","currency"] // This will be stored in the hashmap with key as // required_fields -> ((amount, PaymentsCreate), (currency, PaymentsCreate)) // and values as the type // // (amount, PaymentsCreate) -> Amount let mut required_fields = HashMap::<(syn::Ident, syn::Ident), syn::Ident>::new(); // These fields will be removed in the schema // PaymentsUpdate -> ["client_secret"] // This will be stored in a hashset // hide_fields -> ((client_secret, PaymentsUpdate)) let mut hide_fields = HashSet::<(syn::Ident, syn::Ident)>::new(); let mut all_fields = IndexMap::<syn::Field, Vec<syn::Attribute>>::new(); for field in fields { // Partition the attributes of a field into two vectors // One with #[mandatory_in] attributes present // Rest of the attributes ( include only the schema attribute, serde is not required) let (mandatory_attribute, other_attributes) = field .attrs .iter() .partition::<Vec<_>, _>(|attribute| attribute.path().is_ident("mandatory_in")); let hidden_fields = field .attrs .iter() .filter(|attribute| attribute.path().is_ident("remove_in")) .collect::<Vec<_>>(); // Other attributes ( schema ) are to be printed as is other_attributes .iter() .filter(|attribute| { attribute.path().is_ident("schema") || attribute.path().is_ident("doc") }) .for_each(|attribute| { // Since attributes will be modified, the field should not contain any attributes // So create a field, with previous attributes removed let mut field_without_attributes = field.clone(); field_without_attributes.attrs.clear(); all_fields .entry(field_without_attributes.to_owned()) .or_default() .push(attribute.to_owned().to_owned()); }); // Mandatory attributes are to be inserted into hashset // The hashset will store it in this format // ("amount", PaymentsCreateRequest) // ("currency", PaymentsConfirmRequest) // // For these attributes, we need to later add #[schema(required = true)] attribute let field_ident = field.ident.ok_or(syn::Error::new( proc_macro2::Span::call_site(), "Cannot use `mandatory_in` on unnamed fields", ))?; // Parse the #[mandatory_in(PaymentsCreateRequest = u64)] and insert into hashmap // key -> ("amount", PaymentsCreateRequest) // value -> u64 if let Some(mandatory_in_attribute) = helpers::get_metadata_inner::<SchemaMeta>("mandatory_in", mandatory_attribute)?.first() { let key = ( field_ident.clone(), mandatory_in_attribute.struct_name.clone(), ); let value = mandatory_in_attribute.type_ident.clone(); required_fields.insert(key, value); } // Hidden fields are to be inserted in the Hashset // The hashset will store it in this format // ("client_secret", PaymentsUpdate) // // These fields will not be added to the struct _ = hidden_fields .iter() // Filter only #[mandatory_in] attributes .map(|&attribute| get_inner_path_ident(attribute)) .try_for_each(|schemas| { let res = schemas .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))? .iter() .map(|schema| (field_ident.clone(), schema.to_owned())) .collect::<HashSet<_>>(); hide_fields.extend(res); Ok::<_, syn::Error>(()) }); } // iterate over the schemas and build them with their fields let schemas = schemas_to_create .iter() .map(|schema| { let fields = all_fields .iter() .filter_map(|(field, attributes)| { let mut final_attributes = attributes.clone(); if let Some(field_ident) = field.ident.to_owned() { // If the field is required for this schema, then add // #[schema(value_type = type)] for this field if let Some(required_field_type) = required_fields.get(&(field_ident.clone(), schema.to_owned())) { // This is a required field in the Schema // Add the value type and remove original value type ( if present ) let attribute_without_schema_type = attributes .iter() .filter(|attribute| !attribute.path().is_ident("schema")) .map(Clone::clone) .collect::<Vec<_>>(); final_attributes = attribute_without_schema_type; let value_type_attribute: syn::Attribute = parse_quote!(#[schema(value_type = #required_field_type)]); final_attributes.push(value_type_attribute); } } // If the field is to be not shown then let is_hidden_field = field .ident .clone() .map(|field_ident| hide_fields.contains(&(field_ident, schema.to_owned()))) .unwrap_or(false); if is_hidden_field { None } else { Some(quote::quote! { #(#final_attributes)* #field, }) } }) .collect::<Vec<_>>(); quote::quote! { #[derive(utoipa::ToSchema)] pub struct #schema { #(#fields)* } } }) .collect::<Vec<_>>(); Ok(quote::quote! { #(#schemas)* }) }
crates/router_derive/src/macros/generate_schema.rs
router_derive::src::macros::generate_schema
1,952
true
// File: crates/router_derive/src/macros/generate_permissions.rs // Module: router_derive::src::macros::generate_permissions use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::{ braced, bracketed, parse::{Parse, ParseBuffer, ParseStream}, parse_macro_input, punctuated::Punctuated, token::Comma, Ident, Token, }; struct ResourceInput { resource_name: Ident, scopes: Punctuated<Ident, Token![,]>, entities: Punctuated<Ident, Token![,]>, } struct Input { permissions: Punctuated<ResourceInput, Token![,]>, } impl Parse for Input { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let (_permission_label, permissions) = parse_label_with_punctuated_data(input)?; Ok(Self { permissions }) } } impl Parse for ResourceInput { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let resource_name: Ident = input.parse()?; input.parse::<Token![:]>()?; // Expect ':' let content; braced!(content in input); let (_scopes_label, scopes) = parse_label_with_punctuated_data(&content)?; content.parse::<Comma>()?; let (_entities_label, entities) = parse_label_with_punctuated_data(&content)?; Ok(Self { resource_name, scopes, entities, }) } } fn parse_label_with_punctuated_data<T: Parse>( input: &ParseBuffer<'_>, ) -> syn::Result<(Ident, Punctuated<T, Token![,]>)> { let label: Ident = input.parse()?; input.parse::<Token![:]>()?; // Expect ':' let content; bracketed!(content in input); // Parse the list inside [] let data = Punctuated::<T, Token![,]>::parse_terminated(&content)?; Ok((label, data)) } pub fn generate_permissions_inner(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as Input); let res = input.permissions.iter(); let mut enum_keys = Vec::new(); let mut scope_impl_per = Vec::new(); let mut entity_impl_per = Vec::new(); let mut resource_impl_per = Vec::new(); let mut entity_impl_res = Vec::new(); for per in res { let resource_name = &per.resource_name; let mut permissions = Vec::new(); for scope in per.scopes.iter() { for entity in per.entities.iter() { let key = format_ident!("{}{}{}", entity, per.resource_name, scope); enum_keys.push(quote! { #key }); scope_impl_per.push(quote! { Permission::#key => PermissionScope::#scope }); entity_impl_per.push(quote! { Permission::#key => EntityType::#entity }); resource_impl_per.push(quote! { Permission::#key => Resource::#resource_name }); permissions.push(quote! { Permission::#key }); } let entities_iter = per.entities.iter(); entity_impl_res .push(quote! { Resource::#resource_name => vec![#(EntityType::#entities_iter),*] }); } } let expanded = quote! { #[derive( Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, serde::Serialize, serde::Deserialize, strum::Display )] pub enum Permission { #(#enum_keys),* } impl Permission { pub fn scope(&self) -> PermissionScope { match self { #(#scope_impl_per),* } } pub fn entity_type(&self) -> EntityType { match self { #(#entity_impl_per),* } } pub fn resource(&self) -> Resource { match self { #(#resource_impl_per),* } } } pub trait ResourceExt { fn entities(&self) -> Vec<EntityType>; } impl ResourceExt for Resource { fn entities(&self) -> Vec<EntityType> { match self { #(#entity_impl_res),* } } } }; expanded.into() }
crates/router_derive/src/macros/generate_permissions.rs
router_derive::src::macros::generate_permissions
916
true
// File: crates/router_derive/src/macros/api_error/helpers.rs // Module: router_derive::src::macros::api_error::helpers use proc_macro2::TokenStream; use quote::ToTokens; use syn::{ parse::Parse, spanned::Spanned, DeriveInput, Field, Fields, LitStr, Token, TypePath, Variant, }; use crate::macros::helpers::{get_metadata_inner, occurrence_error}; mod keyword { use syn::custom_keyword; // Enum metadata custom_keyword!(error_type_enum); // Variant metadata custom_keyword!(error_type); custom_keyword!(code); custom_keyword!(message); custom_keyword!(ignore); } enum EnumMeta { ErrorTypeEnum { keyword: keyword::error_type_enum, value: TypePath, }, } impl Parse for EnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(keyword::error_type_enum) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::ErrorTypeEnum { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for EnumMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::ErrorTypeEnum { keyword, .. } => keyword.to_tokens(tokens), } } } trait DeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<EnumMeta>>; } impl DeriveInputExt for DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<EnumMeta>> { get_metadata_inner("error", &self.attrs) } } pub(super) trait HasErrorTypeProperties { fn get_type_properties(&self) -> syn::Result<ErrorTypeProperties>; } #[derive(Clone, Debug, Default)] pub(super) struct ErrorTypeProperties { pub error_type_enum: Option<TypePath>, } impl HasErrorTypeProperties for DeriveInput { fn get_type_properties(&self) -> syn::Result<ErrorTypeProperties> { let mut output = ErrorTypeProperties::default(); let mut error_type_enum_keyword = None; for meta in self.get_metadata()? { match meta { EnumMeta::ErrorTypeEnum { keyword, value } => { if let Some(first_keyword) = error_type_enum_keyword { return Err(occurrence_error(first_keyword, keyword, "error_type_enum")); } error_type_enum_keyword = Some(keyword); output.error_type_enum = Some(value); } } } if output.error_type_enum.is_none() { return Err(syn::Error::new( self.span(), "error(error_type_enum) attribute not found", )); } Ok(output) } } enum VariantMeta { ErrorType { keyword: keyword::error_type, value: TypePath, }, Code { keyword: keyword::code, value: LitStr, }, Message { keyword: keyword::message, value: LitStr, }, Ignore { keyword: keyword::ignore, value: LitStr, }, } impl Parse for VariantMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(keyword::error_type) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::ErrorType { keyword, value }) } else if lookahead.peek(keyword::code) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Code { keyword, value }) } else if lookahead.peek(keyword::message) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Message { keyword, value }) } else if lookahead.peek(keyword::ignore) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Ignore { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for VariantMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::ErrorType { keyword, .. } => keyword.to_tokens(tokens), Self::Code { keyword, .. } => keyword.to_tokens(tokens), Self::Message { keyword, .. } => keyword.to_tokens(tokens), Self::Ignore { keyword, .. } => keyword.to_tokens(tokens), } } } trait VariantExt { /// Get all the error metadata associated with an enum variant. fn get_metadata(&self) -> syn::Result<Vec<VariantMeta>>; } impl VariantExt for Variant { fn get_metadata(&self) -> syn::Result<Vec<VariantMeta>> { get_metadata_inner("error", &self.attrs) } } pub(super) trait HasErrorVariantProperties { fn get_variant_properties(&self) -> syn::Result<ErrorVariantProperties>; } #[derive(Clone, Debug, Default, Eq, PartialEq)] pub(super) struct ErrorVariantProperties { pub error_type: Option<TypePath>, pub code: Option<LitStr>, pub message: Option<LitStr>, pub ignore: std::collections::HashSet<String>, } impl HasErrorVariantProperties for Variant { fn get_variant_properties(&self) -> syn::Result<ErrorVariantProperties> { let mut output = ErrorVariantProperties::default(); let mut error_type_keyword = None; let mut code_keyword = None; let mut message_keyword = None; let mut ignore_keyword = None; for meta in self.get_metadata()? { match meta { VariantMeta::ErrorType { keyword, value } => { if let Some(first_keyword) = error_type_keyword { return Err(occurrence_error(first_keyword, keyword, "error_type")); } error_type_keyword = Some(keyword); output.error_type = Some(value); } VariantMeta::Code { keyword, value } => { if let Some(first_keyword) = code_keyword { return Err(occurrence_error(first_keyword, keyword, "code")); } code_keyword = Some(keyword); output.code = Some(value); } VariantMeta::Message { keyword, value } => { if let Some(first_keyword) = message_keyword { return Err(occurrence_error(first_keyword, keyword, "message")); } message_keyword = Some(keyword); output.message = Some(value); } VariantMeta::Ignore { keyword, value } => { if let Some(first_keyword) = ignore_keyword { return Err(occurrence_error(first_keyword, keyword, "ignore")); } ignore_keyword = Some(keyword); output.ignore = value .value() .replace(' ', "") .split(',') .map(ToString::to_string) .collect(); } } } Ok(output) } } fn missing_attribute_error(variant: &Variant, attr: &str) -> syn::Error { syn::Error::new_spanned(variant, format!("{attr} must be specified")) } pub(super) fn check_missing_attributes( variant: &Variant, variant_properties: &ErrorVariantProperties, ) -> syn::Result<()> { if variant_properties.error_type.is_none() { return Err(missing_attribute_error(variant, "error_type")); } if variant_properties.code.is_none() { return Err(missing_attribute_error(variant, "code")); } if variant_properties.message.is_none() { return Err(missing_attribute_error(variant, "message")); } Ok(()) } /// Get all the fields not used in the error message. pub(super) fn get_unused_fields( fields: &Fields, message: &str, ignore: &std::collections::HashSet<String>, ) -> Vec<Field> { let fields = match fields { Fields::Unit => Vec::new(), Fields::Unnamed(_) => Vec::new(), Fields::Named(fields) => fields.named.iter().cloned().collect(), }; fields .iter() .filter(|&field| { // Safety: Named fields are guaranteed to have an identifier. #[allow(clippy::unwrap_used)] let field_name = format!("{}", field.ident.as_ref().unwrap()); !message.contains(&field_name) && !ignore.contains(&field_name) }) .cloned() .collect() }
crates/router_derive/src/macros/api_error/helpers.rs
router_derive::src::macros::api_error::helpers
1,857
true
// File: crates/router_derive/src/macros/schema/helpers.rs // Module: router_derive::src::macros::schema::helpers use proc_macro2::TokenStream; use quote::ToTokens; use syn::{parse::Parse, Field, LitInt, LitStr, Token, TypePath}; use crate::macros::helpers::{get_metadata_inner, occurrence_error}; mod keyword { use syn::custom_keyword; // Schema metadata custom_keyword!(value_type); custom_keyword!(min_length); custom_keyword!(max_length); custom_keyword!(example); } pub enum SchemaParameterVariant { ValueType { keyword: keyword::value_type, value: TypePath, }, MinLength { keyword: keyword::min_length, value: LitInt, }, MaxLength { keyword: keyword::max_length, value: LitInt, }, Example { keyword: keyword::example, value: LitStr, }, } impl Parse for SchemaParameterVariant { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(keyword::value_type) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::ValueType { keyword, value }) } else if lookahead.peek(keyword::min_length) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::MinLength { keyword, value }) } else if lookahead.peek(keyword::max_length) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::MaxLength { keyword, value }) } else if lookahead.peek(keyword::example) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::Example { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for SchemaParameterVariant { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::ValueType { keyword, .. } => keyword.to_tokens(tokens), Self::MinLength { keyword, .. } => keyword.to_tokens(tokens), Self::MaxLength { keyword, .. } => keyword.to_tokens(tokens), Self::Example { keyword, .. } => keyword.to_tokens(tokens), } } } pub trait FieldExt { /// Get all the schema metadata associated with a field. fn get_schema_metadata(&self) -> syn::Result<Vec<SchemaParameterVariant>>; } impl FieldExt for Field { fn get_schema_metadata(&self) -> syn::Result<Vec<SchemaParameterVariant>> { get_metadata_inner("schema", &self.attrs) } } #[derive(Clone, Debug, Default)] pub struct SchemaParameters { pub value_type: Option<TypePath>, pub min_length: Option<usize>, pub max_length: Option<usize>, pub example: Option<String>, } pub trait HasSchemaParameters { fn get_schema_parameters(&self) -> syn::Result<SchemaParameters>; } impl HasSchemaParameters for Field { fn get_schema_parameters(&self) -> syn::Result<SchemaParameters> { let mut output = SchemaParameters::default(); let mut value_type_keyword = None; let mut min_length_keyword = None; let mut max_length_keyword = None; let mut example_keyword = None; for meta in self.get_schema_metadata()? { match meta { SchemaParameterVariant::ValueType { keyword, value } => { if let Some(first_keyword) = value_type_keyword { return Err(occurrence_error(first_keyword, keyword, "value_type")); } value_type_keyword = Some(keyword); output.value_type = Some(value); } SchemaParameterVariant::MinLength { keyword, value } => { if let Some(first_keyword) = min_length_keyword { return Err(occurrence_error(first_keyword, keyword, "min_length")); } min_length_keyword = Some(keyword); let min_length = value.base10_parse::<usize>()?; output.min_length = Some(min_length); } SchemaParameterVariant::MaxLength { keyword, value } => { if let Some(first_keyword) = max_length_keyword { return Err(occurrence_error(first_keyword, keyword, "max_length")); } max_length_keyword = Some(keyword); let max_length = value.base10_parse::<usize>()?; output.max_length = Some(max_length); } SchemaParameterVariant::Example { keyword, value } => { if let Some(first_keyword) = example_keyword { return Err(occurrence_error(first_keyword, keyword, "example")); } example_keyword = Some(keyword); output.example = Some(value.value()); } } } Ok(output) } } /// Check if the field is applicable for running validations #[derive(PartialEq)] pub enum IsSchemaFieldApplicableForValidation { /// Not applicable for running validation checks Invalid, /// Applicable for running validation checks Valid, /// Applicable for validation but field is optional - this is needed for generating validation code only if the value of the field is present ValidOptional, } /// From implementation for checking if the field type is applicable for running schema validations impl From<&syn::Type> for IsSchemaFieldApplicableForValidation { fn from(ty: &syn::Type) -> Self { if let syn::Type::Path(type_path) = ty { if let Some(segment) = type_path.path.segments.last() { let ident = &segment.ident; if ident == "String" || ident == "Url" { return Self::Valid; } if ident == "Option" { if let syn::PathArguments::AngleBracketed(generic_args) = &segment.arguments { if let Some(syn::GenericArgument::Type(syn::Type::Path(inner_path))) = generic_args.args.first() { if let Some(inner_segment) = inner_path.path.segments.last() { if inner_segment.ident == "String" || inner_segment.ident == "Url" { return Self::ValidOptional; } } } } } } } Self::Invalid } }
crates/router_derive/src/macros/schema/helpers.rs
router_derive::src::macros::schema::helpers
1,349
true
// File: crates/subscriptions/src/core.rs // Module: subscriptions::src::core use api_models::subscription::{ self as subscription_types, SubscriptionResponse, SubscriptionStatus, }; use common_enums::connector_enums; use common_utils::id_type::GenerateId; use error_stack::ResultExt; use hyperswitch_domain_models::{ api::ApplicationResponse, invoice::InvoiceUpdateRequest, merchant_context::MerchantContext, }; pub type RouterResponse<T> = Result<ApplicationResponse<T>, error_stack::Report<errors::ApiErrorResponse>>; use crate::{ core::{ billing_processor_handler::BillingHandler, invoice_handler::InvoiceHandler, subscription_handler::SubscriptionHandler, }, state::SubscriptionState as SessionState, }; pub mod billing_processor_handler; pub mod errors; pub mod invoice_handler; pub mod payments_api_client; pub mod subscription_handler; pub const SUBSCRIPTION_CONNECTOR_ID: &str = "DefaultSubscriptionConnectorId"; pub const SUBSCRIPTION_PAYMENT_ID: &str = "DefaultSubscriptionPaymentId"; pub async fn create_subscription( state: SessionState, merchant_context: MerchantContext, profile_id: common_utils::id_type::ProfileId, request: subscription_types::CreateSubscriptionRequest, ) -> RouterResponse<SubscriptionResponse> { let subscription_id = common_utils::id_type::SubscriptionId::generate(); let profile = SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await .attach_printable("subscriptions: failed to find business profile")?; let _customer = SubscriptionHandler::find_customer(&state, &merchant_context, &request.customer_id) .await .attach_printable("subscriptions: failed to find customer")?; let billing_handler = BillingHandler::create( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), profile.clone(), ) .await?; let subscription_handler = SubscriptionHandler::new(&state, &merchant_context); let mut subscription = subscription_handler .create_subscription_entry( subscription_id, &request.customer_id, billing_handler.connector_name, billing_handler.merchant_connector_id.clone(), request.merchant_reference_id.clone(), &profile.clone(), request.plan_id.clone(), Some(request.item_price_id.clone()), ) .await .attach_printable("subscriptions: failed to create subscription entry")?; let estimate_request = subscription_types::EstimateSubscriptionQuery { plan_id: request.plan_id.clone(), item_price_id: request.item_price_id.clone(), coupon_code: None, }; let estimate = billing_handler .get_subscription_estimate(&state, estimate_request) .await?; let invoice_handler = subscription.get_invoice_handler(profile.clone()); let payment = invoice_handler .create_payment_with_confirm_false( subscription.handler.state, &request, estimate.total, estimate.currency, ) .await .attach_printable("subscriptions: failed to create payment")?; let invoice = invoice_handler .create_invoice_entry( &state, billing_handler.merchant_connector_id, Some(payment.payment_id.clone()), estimate.total, estimate.currency, connector_enums::InvoiceStatus::InvoiceCreated, billing_handler.connector_name, None, None, ) .await .attach_printable("subscriptions: failed to create invoice")?; subscription .update_subscription( hyperswitch_domain_models::subscription::SubscriptionUpdate::new( None, payment.payment_method_id.clone(), None, request.plan_id, Some(request.item_price_id), ), ) .await .attach_printable("subscriptions: failed to update subscription")?; let response = subscription.to_subscription_response(Some(payment), Some(&invoice))?; Ok(ApplicationResponse::Json(response)) } pub async fn get_subscription_plans( state: SessionState, merchant_context: MerchantContext, profile_id: common_utils::id_type::ProfileId, query: subscription_types::GetPlansQuery, ) -> RouterResponse<Vec<subscription_types::GetPlansResponse>> { let profile = SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await .attach_printable("subscriptions: failed to find business profile")?; let subscription_handler = SubscriptionHandler::new(&state, &merchant_context); if let Some(client_secret) = query.client_secret { subscription_handler .find_and_validate_subscription(&client_secret.into()) .await? }; let billing_handler = BillingHandler::create( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), profile.clone(), ) .await?; let get_plans_response = billing_handler .get_subscription_plans(&state, query.limit, query.offset) .await?; let mut response = Vec::new(); for plan in &get_plans_response.list { let plan_price_response = billing_handler .get_subscription_plan_prices(&state, plan.subscription_provider_plan_id.clone()) .await?; response.push(subscription_types::GetPlansResponse { plan_id: plan.subscription_provider_plan_id.clone(), name: plan.name.clone(), description: plan.description.clone(), price_id: plan_price_response .list .into_iter() .map(subscription_types::SubscriptionPlanPrices::from) .collect::<Vec<_>>(), }); } Ok(ApplicationResponse::Json(response)) } /// Creates and confirms a subscription in one operation. pub async fn create_and_confirm_subscription( state: SessionState, merchant_context: MerchantContext, profile_id: common_utils::id_type::ProfileId, request: subscription_types::CreateAndConfirmSubscriptionRequest, ) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> { let subscription_id = common_utils::id_type::SubscriptionId::generate(); let profile = SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await .attach_printable("subscriptions: failed to find business profile")?; let customer = SubscriptionHandler::find_customer(&state, &merchant_context, &request.customer_id) .await .attach_printable("subscriptions: failed to find customer")?; let billing_handler = BillingHandler::create( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), profile.clone(), ) .await?; let subscription_handler = SubscriptionHandler::new(&state, &merchant_context); let mut subs_handler = subscription_handler .create_subscription_entry( subscription_id.clone(), &request.customer_id, billing_handler.connector_name, billing_handler.merchant_connector_id.clone(), request.merchant_reference_id.clone(), &profile.clone(), request.plan_id.clone(), Some(request.item_price_id.clone()), ) .await .attach_printable("subscriptions: failed to create subscription entry")?; let invoice_handler = subs_handler.get_invoice_handler(profile.clone()); let customer_create_response = billing_handler .create_customer_on_connector( &state, customer.clone(), request.customer_id.clone(), request.get_billing_address(), request .payment_details .payment_method_data .clone() .and_then(|data| data.payment_method_data), ) .await?; let _customer_updated_response = SubscriptionHandler::update_connector_customer_id_in_customer( &state, &merchant_context, &billing_handler.merchant_connector_id, &customer, customer_create_response, ) .await .attach_printable("Failed to update customer with connector customer ID")?; let subscription_create_response = billing_handler .create_subscription_on_connector( &state, subs_handler.subscription.clone(), Some(request.item_price_id.clone()), request.get_billing_address(), ) .await?; let invoice_details = subscription_create_response.invoice_details; let (amount, currency) = InvoiceHandler::get_amount_and_currency((None, None), invoice_details.clone()); let payment_response = invoice_handler .create_and_confirm_payment(&state, &request, amount, currency) .await?; let invoice_entry = invoice_handler .create_invoice_entry( &state, profile.get_billing_processor_id()?, Some(payment_response.payment_id.clone()), amount, currency, invoice_details .clone() .and_then(|invoice| invoice.status) .unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated), billing_handler.connector_name, None, invoice_details.clone().map(|invoice| invoice.id), ) .await?; invoice_handler .create_invoice_sync_job( &state, &invoice_entry, invoice_details.clone().map(|details| details.id), billing_handler.connector_name, ) .await?; subs_handler .update_subscription( hyperswitch_domain_models::subscription::SubscriptionUpdate::new( Some( subscription_create_response .subscription_id .get_string_repr() .to_string(), ), payment_response.payment_method_id.clone(), Some(SubscriptionStatus::from(subscription_create_response.status).to_string()), request.plan_id, Some(request.item_price_id), ), ) .await?; let response = subs_handler.generate_response( &invoice_entry, &payment_response, subscription_create_response.status, )?; Ok(ApplicationResponse::Json(response)) } pub async fn confirm_subscription( state: SessionState, merchant_context: MerchantContext, profile_id: common_utils::id_type::ProfileId, request: subscription_types::ConfirmSubscriptionRequest, subscription_id: common_utils::id_type::SubscriptionId, ) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> { // Find the subscription from database let profile = SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await .attach_printable("subscriptions: failed to find business profile")?; let handler = SubscriptionHandler::new(&state, &merchant_context); if let Some(client_secret) = request.client_secret.clone() { handler .find_and_validate_subscription(&client_secret.into()) .await? }; let mut subscription_entry = handler.find_subscription(subscription_id).await?; let customer = SubscriptionHandler::find_customer( &state, &merchant_context, &subscription_entry.subscription.customer_id, ) .await .attach_printable("subscriptions: failed to find customer")?; let invoice_handler = subscription_entry.get_invoice_handler(profile.clone()); let invoice = invoice_handler .get_latest_invoice(&state) .await .attach_printable("subscriptions: failed to get latest invoice")?; let payment_response = invoice_handler .confirm_payment( &state, invoice .payment_intent_id .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_intent_id", })?, &request, ) .await?; let billing_handler = BillingHandler::create( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), profile.clone(), ) .await?; let invoice_handler = subscription_entry.get_invoice_handler(profile); let subscription = subscription_entry.subscription.clone(); let customer_create_response = billing_handler .create_customer_on_connector( &state, customer.clone(), subscription.customer_id.clone(), request.get_billing_address(), request .payment_details .payment_method_data .payment_method_data .clone(), ) .await?; let _customer_updated_response = SubscriptionHandler::update_connector_customer_id_in_customer( &state, &merchant_context, &billing_handler.merchant_connector_id, &customer, customer_create_response, ) .await .attach_printable("Failed to update customer with connector customer ID")?; let subscription_create_response = billing_handler .create_subscription_on_connector( &state, subscription.clone(), subscription.item_price_id.clone(), request.get_billing_address(), ) .await?; let invoice_details = subscription_create_response.invoice_details; let update_request = InvoiceUpdateRequest::update_payment_and_status( payment_response.payment_method_id.clone(), Some(payment_response.payment_id.clone()), invoice_details .clone() .and_then(|invoice| invoice.status) .unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated), invoice_details.clone().map(|invoice| invoice.id), ); let invoice_entry = invoice_handler .update_invoice(&state, invoice.id, update_request) .await?; invoice_handler .create_invoice_sync_job( &state, &invoice_entry, invoice_details.map(|invoice| invoice.id), billing_handler.connector_name, ) .await?; subscription_entry .update_subscription( hyperswitch_domain_models::subscription::SubscriptionUpdate::new( Some( subscription_create_response .subscription_id .get_string_repr() .to_string(), ), payment_response.payment_method_id.clone(), Some(SubscriptionStatus::from(subscription_create_response.status).to_string()), subscription.plan_id.clone(), subscription.item_price_id.clone(), ), ) .await?; let response = subscription_entry.generate_response( &invoice_entry, &payment_response, subscription_create_response.status, )?; Ok(ApplicationResponse::Json(response)) } pub async fn get_subscription( state: SessionState, merchant_context: MerchantContext, profile_id: common_utils::id_type::ProfileId, subscription_id: common_utils::id_type::SubscriptionId, ) -> RouterResponse<SubscriptionResponse> { let _profile = SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await .attach_printable( "subscriptions: failed to find business profile in get_subscription", )?; let handler = SubscriptionHandler::new(&state, &merchant_context); let subscription = handler .find_subscription(subscription_id) .await .attach_printable("subscriptions: failed to get subscription entry in get_subscription")?; let response = subscription.to_subscription_response(None, None)?; Ok(ApplicationResponse::Json(response)) } pub async fn get_estimate( state: SessionState, merchant_context: MerchantContext, profile_id: common_utils::id_type::ProfileId, query: subscription_types::EstimateSubscriptionQuery, ) -> RouterResponse<subscription_types::EstimateSubscriptionResponse> { let profile = SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await .attach_printable("subscriptions: failed to find business profile in get_estimate")?; let billing_handler = BillingHandler::create( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), profile, ) .await?; let estimate = billing_handler .get_subscription_estimate(&state, query) .await?; Ok(ApplicationResponse::Json(estimate.into())) } pub async fn update_subscription( state: SessionState, merchant_context: MerchantContext, profile_id: common_utils::id_type::ProfileId, subscription_id: common_utils::id_type::SubscriptionId, request: subscription_types::UpdateSubscriptionRequest, ) -> RouterResponse<SubscriptionResponse> { let profile = SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await .attach_printable( "subscriptions: failed to find business profile in get_subscription", )?; let handler = SubscriptionHandler::new(&state, &merchant_context); let mut subscription_entry = handler.find_subscription(subscription_id).await?; let invoice_handler = subscription_entry.get_invoice_handler(profile.clone()); let invoice = invoice_handler .get_latest_invoice(&state) .await .attach_printable("subscriptions: failed to get latest invoice")?; let subscription = subscription_entry.subscription.clone(); subscription_entry .update_subscription( hyperswitch_domain_models::subscription::SubscriptionUpdate::new( None, None, None, Some(request.plan_id.clone()), Some(request.item_price_id.clone()), ), ) .await?; let billing_handler = BillingHandler::create( &state, merchant_context.get_merchant_account(), merchant_context.get_merchant_key_store(), profile.clone(), ) .await?; let estimate_request = subscription_types::EstimateSubscriptionQuery { plan_id: Some(request.plan_id.clone()), item_price_id: request.item_price_id.clone(), coupon_code: None, }; let estimate = billing_handler .get_subscription_estimate(&state, estimate_request) .await?; let update_request = InvoiceUpdateRequest::update_amount_and_currency( estimate.total, estimate.currency.to_string(), ); let invoice_entry = invoice_handler .update_invoice(&state, invoice.id, update_request) .await?; let _payment_response = invoice_handler .update_payment( &state, estimate.total, estimate.currency, invoice_entry.payment_intent_id.ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_intent_id", }, )?, ) .await?; Box::pin(get_subscription( state, merchant_context, profile_id, subscription.id, )) .await }
crates/subscriptions/src/core.rs
subscriptions::src::core
3,714
true
// File: crates/subscriptions/src/types.rs // Module: subscriptions::src::types //! Types module for subscription functionality //! //! This module contains type definitions and storage types for subscriptions pub mod storage; // Re-export subscription types from api_models for convenience pub use api_models::subscription as subscription_types;
crates/subscriptions/src/types.rs
subscriptions::src::types
64
true
// File: crates/subscriptions/src/lib.rs // Module: subscriptions::src::lib //! Subscription management crate for Hyperswitch //! //! This crate provides functionality for managing subscriptions, including: //! - Subscription creation and management //! - Invoice handling //! - Billing processor integration //! - Payment processing for subscriptions #[cfg(feature = "v1")] pub mod core; pub mod helpers; pub mod state; pub mod types; #[cfg(feature = "v1")] pub mod workflows; pub mod webhooks; pub use core::*; pub use types::*;
crates/subscriptions/src/lib.rs
subscriptions::src::lib
114
true
// File: crates/subscriptions/src/helpers.rs // Module: subscriptions::src::helpers pub use hyperswitch_domain_models::errors::api_error_response; pub const X_PROFILE_ID: &str = "X-Profile-Id"; pub const X_TENANT_ID: &str = "x-tenant-id"; pub const X_MERCHANT_ID: &str = "X-Merchant-Id"; pub const X_INTERNAL_API_KEY: &str = "X-Internal-Api-Key"; pub trait ForeignFrom<F> { fn foreign_from(from: F) -> Self; } /// Trait for converting from one foreign type to another pub trait ForeignTryFrom<F>: Sized { /// Custom error for conversion failure type Error; /// Convert from a foreign type to the current type and return an error if the conversion fails fn foreign_try_from(from: F) -> Result<Self, Self::Error>; } pub trait StorageErrorExt<T, E> { #[track_caller] fn to_not_found_response(self, not_found_response: E) -> error_stack::Result<T, E>; #[track_caller] fn to_duplicate_response(self, duplicate_response: E) -> error_stack::Result<T, E>; } impl<T> StorageErrorExt<T, api_error_response::ApiErrorResponse> for error_stack::Result<T, storage_impl::StorageError> { #[track_caller] fn to_not_found_response( self, not_found_response: api_error_response::ApiErrorResponse, ) -> error_stack::Result<T, api_error_response::ApiErrorResponse> { self.map_err(|err| { let new_err = match err.current_context() { storage_impl::StorageError::ValueNotFound(_) => not_found_response, storage_impl::StorageError::CustomerRedacted => { api_error_response::ApiErrorResponse::CustomerRedacted } _ => api_error_response::ApiErrorResponse::InternalServerError, }; err.change_context(new_err) }) } #[track_caller] fn to_duplicate_response( self, duplicate_response: api_error_response::ApiErrorResponse, ) -> error_stack::Result<T, api_error_response::ApiErrorResponse> { self.map_err(|err| { let new_err = match err.current_context() { storage_impl::StorageError::DuplicateValue { .. } => duplicate_response, _ => api_error_response::ApiErrorResponse::InternalServerError, }; err.change_context(new_err) }) } }
crates/subscriptions/src/helpers.rs
subscriptions::src::helpers
520
true
// File: crates/subscriptions/src/state.rs // Module: subscriptions::src::state use common_utils::types::keymanager; use hyperswitch_domain_models::{ business_profile, configs as domain_configs, customer, invoice as invoice_domain, master_key, merchant_account, merchant_connector_account, merchant_key_store, subscription as subscription_domain, }; use hyperswitch_interfaces::configs; use router_env::tracing_actix_web::RequestId; use storage_impl::{errors, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore}; #[async_trait::async_trait] pub trait SubscriptionStorageInterface: Send + Sync + dyn_clone::DynClone + master_key::MasterKeyInterface + scheduler::SchedulerInterface + subscription_domain::SubscriptionInterface<Error = errors::StorageError> + invoice_domain::InvoiceInterface<Error = errors::StorageError> + business_profile::ProfileInterface<Error = errors::StorageError> + domain_configs::ConfigInterface<Error = errors::StorageError> + customer::CustomerInterface<Error = errors::StorageError> + merchant_account::MerchantAccountInterface<Error = errors::StorageError> + merchant_key_store::MerchantKeyStoreInterface<Error = errors::StorageError> + merchant_connector_account::MerchantConnectorAccountInterface<Error = errors::StorageError> + 'static { } dyn_clone::clone_trait_object!(SubscriptionStorageInterface); #[async_trait::async_trait] impl SubscriptionStorageInterface for MockDb {} #[async_trait::async_trait] impl<T: DatabaseStore + 'static> SubscriptionStorageInterface for RouterStore<T> where Self: scheduler::SchedulerInterface + master_key::MasterKeyInterface { } #[async_trait::async_trait] impl<T: DatabaseStore + 'static> SubscriptionStorageInterface for KVRouterStore<T> where Self: scheduler::SchedulerInterface + master_key::MasterKeyInterface { } pub struct SubscriptionState { pub store: Box<dyn SubscriptionStorageInterface>, pub key_store: Option<merchant_key_store::MerchantKeyStore>, pub key_manager_state: keymanager::KeyManagerState, pub api_client: Box<dyn hyperswitch_interfaces::api_client::ApiClient>, pub conf: SubscriptionConfig, pub tenant: configs::Tenant, pub event_handler: Box<dyn hyperswitch_interfaces::events::EventHandlerInterface>, pub connector_converter: Box<dyn hyperswitch_interfaces::api_client::ConnectorConverter>, } #[derive(Clone)] pub struct SubscriptionConfig { pub proxy: hyperswitch_interfaces::types::Proxy, pub internal_merchant_id_profile_id_auth: configs::InternalMerchantIdProfileIdAuthSettings, pub internal_services: configs::InternalServicesConfig, pub connectors: configs::Connectors, } impl From<&SubscriptionState> for keymanager::KeyManagerState { fn from(state: &SubscriptionState) -> Self { state.key_manager_state.clone() } } impl hyperswitch_interfaces::api_client::ApiClientWrapper for SubscriptionState { fn get_proxy(&self) -> hyperswitch_interfaces::types::Proxy { self.conf.proxy.clone() } fn get_api_client(&self) -> &dyn hyperswitch_interfaces::api_client::ApiClient { self.api_client.as_ref() } fn get_request_id(&self) -> Option<RequestId> { self.api_client.get_request_id() } fn get_request_id_str(&self) -> Option<String> { self.api_client .get_request_id() .map(|req_id| req_id.as_hyphenated().to_string()) } fn get_tenant(&self) -> configs::Tenant { self.tenant.clone() } fn get_connectors(&self) -> configs::Connectors { self.conf.connectors.clone() } fn event_handler(&self) -> &dyn hyperswitch_interfaces::events::EventHandlerInterface { self.event_handler.as_ref() } }
crates/subscriptions/src/state.rs
subscriptions::src::state
819
true
// File: crates/subscriptions/src/webhooks.rs // Module: subscriptions::src::webhooks use std::str::FromStr; use api_models::webhooks::WebhookResponseTracker; use common_enums::{connector_enums::Connector, InvoiceStatus}; use common_utils::{consts, errors::CustomResult, generate_id}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ business_profile, errors::api_error_response as errors, invoice, merchant_connector_account, merchant_context, }; use hyperswitch_interfaces::{ api::ConnectorCommon, connector_integration_interface, errors::ConnectorError, webhooks::IncomingWebhook, }; use router_env::{instrument, logger, tracing}; use crate::state::SubscriptionState as SessionState; #[cfg(feature = "v1")] use crate::subscription_handler::SubscriptionHandler; #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn incoming_webhook_flow( state: SessionState, merchant_context: merchant_context::MerchantContext, business_profile: business_profile::Profile, _webhook_details: api_models::webhooks::IncomingWebhookDetails, source_verified: bool, connector_enum: &connector_integration_interface::ConnectorEnum, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, event_type: api_models::webhooks::IncomingWebhookEvent, merchant_connector_account: merchant_connector_account::MerchantConnectorAccount, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let billing_connector_mca_id = merchant_connector_account.merchant_connector_id.clone(); // Only process invoice_generated events for MIT payments if event_type != api_models::webhooks::IncomingWebhookEvent::InvoiceGenerated { return Ok(WebhookResponseTracker::NoEffect); } if !source_verified { logger::error!("Webhook source verification failed for subscription webhook flow"); return Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )); } let connector_name = connector_enum.id().to_string(); let connector = Connector::from_str(&connector_name) .change_context(ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) .attach_printable_lazy(|| format!("unable to parse connector name {connector_name}"))?; let mit_payment_data = connector_enum .get_subscription_mit_payment_data(request_details) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to extract MIT payment data from subscription webhook")?; let profile_id = business_profile.get_id().clone(); let profile = SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id) .await .attach_printable( "subscriptions: failed to find business profile in get_subscription", )?; let handler = SubscriptionHandler::new(&state, &merchant_context); let subscription_id = mit_payment_data.subscription_id.clone(); let subscription_with_handler = handler .find_subscription(subscription_id.clone()) .await .attach_printable("subscriptions: failed to get subscription entry in get_subscription")?; let invoice_handler = subscription_with_handler.get_invoice_handler(profile.clone()); let invoice = invoice_handler .find_invoice_by_subscription_id_connector_invoice_id( &state, subscription_id, mit_payment_data.invoice_id.clone(), ) .await .attach_printable( "subscriptions: failed to get invoice by subscription id and connector invoice id", )?; if let Some(invoice) = invoice { // During CIT payment we would have already created invoice entry with status as PaymentPending or Paid. // So we skip incoming webhook for the already processed invoice if invoice.status != InvoiceStatus::InvoiceCreated { logger::info!("Invoice is already being processed, skipping MIT payment creation"); return Ok(WebhookResponseTracker::NoEffect); } } let payment_method_id = subscription_with_handler .subscription .payment_method_id .clone() .ok_or(errors::ApiErrorResponse::GenericNotFoundError { message: "No payment method found for subscription".to_string(), }) .attach_printable("No payment method found for subscription")?; logger::info!("Payment method ID found: {}", payment_method_id); let payment_id = generate_id(consts::ID_LENGTH, "pay"); let payment_id = common_utils::id_type::PaymentId::wrap(payment_id).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_id", }, )?; // Multiple MIT payments for the same invoice_generated event is avoided by having the unique constraint on (subscription_id, connector_invoice_id) in the invoices table let invoice_entry = invoice_handler .create_invoice_entry( &state, billing_connector_mca_id.clone(), Some(payment_id), mit_payment_data.amount_due, mit_payment_data.currency_code, InvoiceStatus::PaymentPending, connector, None, Some(mit_payment_data.invoice_id.clone()), ) .await?; // Create a sync job for the invoice with generated payment_id before initiating MIT payment creation. // This ensures that if payment creation call fails, the sync job can still retrieve the payment status invoice_handler .create_invoice_sync_job( &state, &invoice_entry, Some(mit_payment_data.invoice_id.clone()), connector, ) .await?; let payment_response = invoice_handler .create_mit_payment( &state, mit_payment_data.amount_due, mit_payment_data.currency_code, &payment_method_id.clone(), ) .await?; let update_request = invoice::InvoiceUpdateRequest::update_payment_and_status( payment_response.payment_method_id, Some(payment_response.payment_id.clone()), InvoiceStatus::from(payment_response.status), Some(mit_payment_data.invoice_id.clone()), ); let _updated_invoice = invoice_handler .update_invoice(&state, invoice_entry.id.clone(), update_request) .await?; Ok(WebhookResponseTracker::NoEffect) }
crates/subscriptions/src/webhooks.rs
subscriptions::src::webhooks
1,304
true
// File: crates/subscriptions/src/workflows.rs // Module: subscriptions::src::workflows //! Workflows module for subscription functionality //! //! This module contains workflow definitions for subscription-related operations pub mod invoice_sync; // Re-export workflow types for easier access pub use invoice_sync::*;
crates/subscriptions/src/workflows.rs
subscriptions::src::workflows
60
true
// File: crates/subscriptions/src/types/storage.rs // Module: subscriptions::src::types::storage pub mod invoice_sync;
crates/subscriptions/src/types/storage.rs
subscriptions::src::types::storage
27
true
// File: crates/subscriptions/src/types/storage/invoice_sync.rs // Module: subscriptions::src::types::storage::invoice_sync use api_models::enums as api_enums; use common_utils::id_type; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct InvoiceSyncTrackingData { pub subscription_id: id_type::SubscriptionId, pub invoice_id: id_type::InvoiceId, pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub customer_id: id_type::CustomerId, // connector_invoice_id is optional because in some cases (Trial/Future), the invoice might not have been created in the connector yet. pub connector_invoice_id: Option<id_type::InvoiceId>, pub connector_name: api_enums::Connector, // The connector to which the invoice belongs } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct InvoiceSyncRequest { pub subscription_id: id_type::SubscriptionId, pub invoice_id: id_type::InvoiceId, pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub customer_id: id_type::CustomerId, pub connector_invoice_id: Option<id_type::InvoiceId>, pub connector_name: api_enums::Connector, } impl From<InvoiceSyncRequest> for InvoiceSyncTrackingData { fn from(item: InvoiceSyncRequest) -> Self { Self { subscription_id: item.subscription_id, invoice_id: item.invoice_id, merchant_id: item.merchant_id, profile_id: item.profile_id, customer_id: item.customer_id, connector_invoice_id: item.connector_invoice_id, connector_name: item.connector_name, } } } impl InvoiceSyncRequest { #[allow(clippy::too_many_arguments)] pub fn new( subscription_id: id_type::SubscriptionId, invoice_id: id_type::InvoiceId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, customer_id: id_type::CustomerId, connector_invoice_id: Option<id_type::InvoiceId>, connector_name: api_enums::Connector, ) -> Self { Self { subscription_id, invoice_id, merchant_id, profile_id, customer_id, connector_invoice_id, connector_name, } } } impl InvoiceSyncTrackingData { #[allow(clippy::too_many_arguments)] pub fn new( subscription_id: id_type::SubscriptionId, invoice_id: id_type::InvoiceId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, customer_id: id_type::CustomerId, connector_invoice_id: Option<id_type::InvoiceId>, connector_name: api_enums::Connector, ) -> Self { Self { subscription_id, invoice_id, merchant_id, profile_id, customer_id, connector_invoice_id, connector_name, } } } #[derive(Debug, Clone)] pub enum InvoiceSyncPaymentStatus { PaymentSucceeded, PaymentProcessing, PaymentFailed, } impl From<common_enums::IntentStatus> for InvoiceSyncPaymentStatus { fn from(value: common_enums::IntentStatus) -> Self { match value { common_enums::IntentStatus::Succeeded => Self::PaymentSucceeded, common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresPaymentMethod => Self::PaymentProcessing, _ => Self::PaymentFailed, } } } impl From<InvoiceSyncPaymentStatus> for common_enums::connector_enums::InvoiceStatus { fn from(value: InvoiceSyncPaymentStatus) -> Self { match value { InvoiceSyncPaymentStatus::PaymentSucceeded => Self::InvoicePaid, InvoiceSyncPaymentStatus::PaymentProcessing => Self::PaymentPending, InvoiceSyncPaymentStatus::PaymentFailed => Self::PaymentFailed, } } }
crates/subscriptions/src/types/storage/invoice_sync.rs
subscriptions::src::types::storage::invoice_sync
874
true
// File: crates/subscriptions/src/core/subscription_handler.rs // Module: subscriptions::src::core::subscription_handler use std::str::FromStr; use api_models::{ enums as api_enums, subscription::{self as subscription_types, SubscriptionResponse}, }; use common_enums::connector_enums; use common_utils::{consts, ext_traits::OptionExt}; use error_stack::ResultExt; use hyperswitch_domain_models::{ customer, merchant_connector_account, merchant_context::MerchantContext, router_response_types::{self, subscriptions as subscription_response_types}, subscription::{Subscription, SubscriptionStatus}, }; use masking::Secret; use super::errors; use crate::{ core::invoice_handler::InvoiceHandler, errors::CustomResult, helpers::{ForeignTryFrom, StorageErrorExt}, state::SubscriptionState as SessionState, }; pub struct SubscriptionHandler<'a> { pub state: &'a SessionState, pub merchant_context: &'a MerchantContext, } impl<'a> SubscriptionHandler<'a> { pub fn new(state: &'a SessionState, merchant_context: &'a MerchantContext) -> Self { Self { state, merchant_context, } } #[allow(clippy::too_many_arguments)] /// Helper function to create a subscription entry in the database. pub async fn create_subscription_entry( &self, subscription_id: common_utils::id_type::SubscriptionId, customer_id: &common_utils::id_type::CustomerId, billing_processor: connector_enums::Connector, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, merchant_reference_id: Option<String>, profile: &hyperswitch_domain_models::business_profile::Profile, plan_id: Option<String>, item_price_id: Option<String>, ) -> errors::SubscriptionResult<SubscriptionWithHandler<'_>> { let store = self.state.store.clone(); let db = store.as_ref(); let mut subscription = Subscription { id: subscription_id, status: SubscriptionStatus::Created.to_string(), billing_processor: Some(billing_processor.to_string()), payment_method_id: None, merchant_connector_id: Some(merchant_connector_id), client_secret: None, connector_subscription_id: None, merchant_id: self .merchant_context .get_merchant_account() .get_id() .clone(), customer_id: customer_id.clone(), metadata: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), profile_id: profile.get_id().clone(), merchant_reference_id, plan_id, item_price_id, }; subscription.generate_and_set_client_secret(); let key_manager_state = &(self.state).into(); let merchant_key_store = self.merchant_context.get_merchant_key_store(); let new_subscription = db .insert_subscription_entry(key_manager_state, merchant_key_store, subscription) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("subscriptions: unable to insert subscription entry to database")?; Ok(SubscriptionWithHandler { handler: self, subscription: new_subscription, merchant_account: self.merchant_context.get_merchant_account().clone(), }) } /// Helper function to find and validate customer. pub async fn find_customer( state: &SessionState, merchant_context: &MerchantContext, customer_id: &common_utils::id_type::CustomerId, ) -> errors::SubscriptionResult<customer::Customer> { let key_manager_state = &(state).into(); let merchant_key_store = merchant_context.get_merchant_key_store(); let merchant_id = merchant_context.get_merchant_account().get_id(); state .store .find_customer_by_customer_id_merchant_id( key_manager_state, customer_id, merchant_id, merchant_key_store, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("subscriptions: unable to fetch customer from database") } pub async fn update_connector_customer_id_in_customer( state: &SessionState, merchant_context: &MerchantContext, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, customer: &customer::Customer, customer_create_response: Option<router_response_types::ConnectorCustomerResponseData>, ) -> errors::SubscriptionResult<customer::Customer> { match customer_create_response { Some(customer_response) => { match customer::update_connector_customer_in_customers( merchant_connector_id.get_string_repr(), Some(customer), Some(customer_response.connector_customer_id), ) .await { Some(customer_update) => Self::update_customer( state, merchant_context, customer.clone(), customer_update, ) .await .attach_printable("Failed to update customer with connector customer ID"), None => Ok(customer.clone()), } } None => Ok(customer.clone()), } } pub async fn update_customer( state: &SessionState, merchant_context: &MerchantContext, customer: customer::Customer, customer_update: customer::CustomerUpdate, ) -> errors::SubscriptionResult<customer::Customer> { let key_manager_state = &(state).into(); let merchant_key_store = merchant_context.get_merchant_key_store(); let merchant_id = merchant_context.get_merchant_account().get_id(); let db = state.store.as_ref(); let updated_customer = db .update_customer_by_customer_id_merchant_id( key_manager_state, customer.customer_id.clone(), merchant_id.clone(), customer, customer_update, merchant_key_store, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("subscriptions: unable to update customer entry in database")?; Ok(updated_customer) } /// Helper function to find business profile. pub async fn find_business_profile( state: &SessionState, merchant_context: &MerchantContext, profile_id: &common_utils::id_type::ProfileId, ) -> errors::SubscriptionResult<hyperswitch_domain_models::business_profile::Profile> { let key_manager_state = &(state).into(); let merchant_key_store = merchant_context.get_merchant_key_store(); state .store .find_business_profile_by_profile_id(key_manager_state, merchant_key_store, profile_id) .await .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_string(), }) } pub async fn find_and_validate_subscription( &self, client_secret: &hyperswitch_domain_models::subscription::ClientSecret, ) -> errors::SubscriptionResult<()> { let subscription_id = client_secret.get_subscription_id()?; let key_manager_state = &(self.state).into(); let key_store = self.merchant_context.get_merchant_key_store(); let subscription = self .state .store .find_by_merchant_id_subscription_id( key_manager_state, key_store, self.merchant_context.get_merchant_account().get_id(), subscription_id.to_string(), ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: format!("Subscription not found for id: {subscription_id}"), }) .attach_printable("Unable to find subscription")?; self.validate_client_secret(client_secret, &subscription)?; Ok(()) } pub fn validate_client_secret( &self, client_secret: &hyperswitch_domain_models::subscription::ClientSecret, subscription: &Subscription, ) -> errors::SubscriptionResult<()> { let stored_client_secret = subscription .client_secret .clone() .get_required_value("client_secret") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "client_secret", }) .attach_printable("client secret not found in db")?; if client_secret.to_string() != stored_client_secret { Err(errors::ApiErrorResponse::ClientSecretInvalid.into()) } else { let current_timestamp = common_utils::date_time::now(); let session_expiry = subscription .created_at .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)); if current_timestamp > session_expiry { Err(errors::ApiErrorResponse::ClientSecretExpired.into()) } else { Ok(()) } } } pub async fn find_subscription( &self, subscription_id: common_utils::id_type::SubscriptionId, ) -> errors::SubscriptionResult<SubscriptionWithHandler<'_>> { let subscription = self .state .store .find_by_merchant_id_subscription_id( &(self.state).into(), self.merchant_context.get_merchant_key_store(), self.merchant_context.get_merchant_account().get_id(), subscription_id.get_string_repr().to_string().clone(), ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: format!( "subscription not found for id: {}", subscription_id.get_string_repr() ), })?; Ok(SubscriptionWithHandler { handler: self, subscription, merchant_account: self.merchant_context.get_merchant_account().clone(), }) } } pub struct SubscriptionWithHandler<'a> { pub handler: &'a SubscriptionHandler<'a>, pub subscription: Subscription, pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, } impl SubscriptionWithHandler<'_> { pub fn generate_response( &self, invoice: &hyperswitch_domain_models::invoice::Invoice, payment_response: &subscription_types::PaymentResponseData, status: subscription_response_types::SubscriptionStatus, ) -> errors::SubscriptionResult<subscription_types::ConfirmSubscriptionResponse> { Ok(subscription_types::ConfirmSubscriptionResponse { id: self.subscription.id.clone(), merchant_reference_id: self.subscription.merchant_reference_id.clone(), status: subscription_types::SubscriptionStatus::from(status), plan_id: self.subscription.plan_id.clone(), profile_id: self.subscription.profile_id.to_owned(), payment: Some(payment_response.clone()), customer_id: Some(self.subscription.customer_id.clone()), item_price_id: self.subscription.item_price_id.clone(), coupon: None, billing_processor_subscription_id: self.subscription.connector_subscription_id.clone(), invoice: Some(subscription_types::Invoice::foreign_try_from(invoice)?), }) } pub fn to_subscription_response( &self, payment: Option<subscription_types::PaymentResponseData>, invoice: Option<&hyperswitch_domain_models::invoice::Invoice>, ) -> errors::SubscriptionResult<SubscriptionResponse> { Ok(SubscriptionResponse::new( self.subscription.id.clone(), self.subscription.merchant_reference_id.clone(), subscription_types::SubscriptionStatus::from_str(&self.subscription.status) .unwrap_or(subscription_types::SubscriptionStatus::Created), self.subscription.plan_id.clone(), self.subscription.item_price_id.clone(), self.subscription.profile_id.to_owned(), self.subscription.merchant_id.to_owned(), self.subscription.client_secret.clone().map(Secret::new), self.subscription.customer_id.clone(), payment, invoice .map( |invoice| -> errors::SubscriptionResult<subscription_types::Invoice> { subscription_types::Invoice::foreign_try_from(invoice) }, ) .transpose()?, )) } pub async fn update_subscription( &mut self, subscription_update: hyperswitch_domain_models::subscription::SubscriptionUpdate, ) -> errors::SubscriptionResult<()> { let db = self.handler.state.store.as_ref(); let updated_subscription = db .update_subscription_entry( &(self.handler.state).into(), self.handler.merchant_context.get_merchant_key_store(), self.handler .merchant_context .get_merchant_account() .get_id(), self.subscription.id.get_string_repr().to_string(), subscription_update, ) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Subscription Update".to_string(), }) .attach_printable("subscriptions: unable to update subscription entry in database")?; self.subscription = updated_subscription; Ok(()) } pub fn get_invoice_handler( &self, profile: hyperswitch_domain_models::business_profile::Profile, ) -> InvoiceHandler { InvoiceHandler { subscription: self.subscription.clone(), merchant_account: self.merchant_account.clone(), profile, merchant_key_store: self .handler .merchant_context .get_merchant_key_store() .clone(), } } pub async fn get_mca( &mut self, connector_name: &str, ) -> CustomResult<merchant_connector_account::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = self.handler.state.store.as_ref(); let key_manager_state = &(self.handler.state).into(); match &self.subscription.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, self.handler .merchant_context .get_merchant_account() .get_id(), merchant_connector_id, self.handler.merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } } None => { // Fallback to profile-based lookup when merchant_connector_id is not set #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, &self.subscription.profile_id, connector_name, self.handler.merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {connector_name}", self.subscription.profile_id.get_string_repr() ), }, ) } } } } } impl ForeignTryFrom<&hyperswitch_domain_models::invoice::Invoice> for subscription_types::Invoice { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( invoice: &hyperswitch_domain_models::invoice::Invoice, ) -> Result<Self, Self::Error> { Ok(Self { id: invoice.id.clone(), subscription_id: invoice.subscription_id.clone(), merchant_id: invoice.merchant_id.clone(), profile_id: invoice.profile_id.clone(), merchant_connector_id: invoice.merchant_connector_id.clone(), payment_intent_id: invoice.payment_intent_id.clone(), payment_method_id: invoice.payment_method_id.clone(), customer_id: invoice.customer_id.clone(), amount: invoice.amount, currency: api_enums::Currency::from_str(invoice.currency.as_str()) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "currency", }) .attach_printable(format!( "unable to parse currency name {currency:?}", currency = invoice.currency ))?, status: invoice.status.clone(), }) } }
crates/subscriptions/src/core/subscription_handler.rs
subscriptions::src::core::subscription_handler
3,280
true
// File: crates/subscriptions/src/core/billing_processor_handler.rs // Module: subscriptions::src::core::billing_processor_handler use std::str::FromStr; use api_models::subscription as subscription_types; use common_enums::{connector_enums, CallConnectorAction}; use common_utils::{ext_traits::ValueExt, pii}; use error_stack::ResultExt; use hyperswitch_domain_models::{ errors::api_error_response as errors, router_data_v2::flow_common_types::{ GetSubscriptionEstimateData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, InvoiceRecordBackData, SubscriptionCreateData, SubscriptionCustomerData, }, router_request_types::{ revenue_recovery::InvoiceRecordBackRequest, subscriptions as subscription_request_types, ConnectorCustomerData, }, router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, subscriptions as subscription_response_types, ConnectorCustomerResponseData, PaymentsResponseData, }, }; use hyperswitch_interfaces::{ api_client, configs::MerchantConnectorAccountType, connector_integration_interface, }; use crate::{errors::SubscriptionResult, state::SubscriptionState as SessionState}; pub struct BillingHandler { pub auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType, pub connector_name: connector_enums::Connector, pub connector_enum: connector_integration_interface::ConnectorEnum, pub connector_params: hyperswitch_domain_models::connector_endpoints::ConnectorParams, pub connector_metadata: Option<pii::SecretSerdeValue>, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, } #[allow(clippy::todo)] impl BillingHandler { pub async fn create( state: &SessionState, merchant_account: &hyperswitch_domain_models::merchant_account::MerchantAccount, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, profile: hyperswitch_domain_models::business_profile::Profile, ) -> SubscriptionResult<Self> { let merchant_connector_id = profile.get_billing_processor_id()?; let billing_processor_mca = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &(state).into(), merchant_account.get_id(), &merchant_connector_id, key_store, ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; let connector_name = billing_processor_mca.connector_name.clone(); let auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType = MerchantConnectorAccountType::DbVal(Box::new(billing_processor_mca.clone())) .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; let connector_enum = state .connector_converter .get_connector_enum_by_name(&connector_name) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) .attach_printable( "invalid connector name received in billing merchant connector account", )?; let connector_data = connector_enums::Connector::from_str(connector_name.as_str()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!("unable to parse connector name {connector_name:?}"))?; let connector_params = hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params( &state.conf.connectors, connector_data, ) .change_context(errors::ApiErrorResponse::ConfigNotFound) .attach_printable(format!( "cannot find connector params for this connector {connector_name} in this flow", ))?; Ok(Self { auth_type, connector_enum, connector_name: connector_data, connector_params, connector_metadata: billing_processor_mca.metadata.clone(), merchant_connector_id, }) } pub async fn create_customer_on_connector( &self, state: &SessionState, customer: hyperswitch_domain_models::customer::Customer, customer_id: common_utils::id_type::CustomerId, billing_address: Option<api_models::payments::Address>, payment_method_data: Option<api_models::payments::PaymentMethodData>, ) -> SubscriptionResult<Option<ConnectorCustomerResponseData>> { let connector_customer_map = customer.get_connector_customer_map(); if connector_customer_map.contains_key(&self.merchant_connector_id) { // Customer already exists on the connector, no need to create again return Ok(None); } let customer_req = ConnectorCustomerData { email: customer.email.clone().map(pii::Email::from), payment_method_data: payment_method_data.clone().map(|pmd| pmd.into()), description: None, phone: None, name: None, preprocessing_id: None, split_payments: None, setup_future_usage: None, customer_acceptance: None, customer_id: Some(customer_id.clone()), billing_address: billing_address .as_ref() .and_then(|add| add.address.clone()) .and_then(|addr| addr.into()), }; let router_data = self.build_router_data( state, customer_req, SubscriptionCustomerData { connector_meta_data: self.connector_metadata.clone(), }, )?; let connector_integration = self.connector_enum.get_connector_integration(); let response = Box::pin(self.call_connector( state, router_data, "create customer on connector", connector_integration, )) .await?; match response { Ok(response_data) => match response_data { PaymentsResponseData::ConnectorCustomerResponse(customer_response) => { Ok(Some(customer_response)) } _ => Err(errors::ApiErrorResponse::SubscriptionError { operation: "Subscription Customer Create".to_string(), } .into()), }, Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: self.connector_name.to_string(), status_code: err.status_code, reason: err.reason, } .into()), } } pub async fn create_subscription_on_connector( &self, state: &SessionState, subscription: hyperswitch_domain_models::subscription::Subscription, item_price_id: Option<String>, billing_address: Option<api_models::payments::Address>, ) -> SubscriptionResult<subscription_response_types::SubscriptionCreateResponse> { let subscription_item = subscription_request_types::SubscriptionItem { item_price_id: item_price_id.ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "item_price_id", })?, quantity: Some(1), }; let subscription_req = subscription_request_types::SubscriptionCreateRequest { subscription_id: subscription.id.to_owned(), customer_id: subscription.customer_id.to_owned(), subscription_items: vec![subscription_item], billing_address: billing_address.ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "billing", }, )?, auto_collection: subscription_request_types::SubscriptionAutoCollection::Off, connector_params: self.connector_params.clone(), }; let router_data = self.build_router_data( state, subscription_req, SubscriptionCreateData { connector_meta_data: self.connector_metadata.clone(), }, )?; let connector_integration = self.connector_enum.get_connector_integration(); let response = self .call_connector( state, router_data, "create subscription on connector", connector_integration, ) .await?; match response { Ok(response_data) => Ok(response_data), Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: self.connector_name.to_string(), status_code: err.status_code, reason: err.reason, } .into()), } } #[allow(clippy::too_many_arguments)] pub async fn record_back_to_billing_processor( &self, state: &SessionState, invoice_id: common_utils::id_type::InvoiceId, payment_id: common_utils::id_type::PaymentId, payment_status: common_enums::AttemptStatus, amount: common_utils::types::MinorUnit, currency: common_enums::Currency, payment_method_type: Option<common_enums::PaymentMethodType>, ) -> SubscriptionResult<InvoiceRecordBackResponse> { let invoice_record_back_req = InvoiceRecordBackRequest { amount, currency, payment_method_type, attempt_status: payment_status, merchant_reference_id: common_utils::id_type::PaymentReferenceId::from_str( invoice_id.get_string_repr(), ) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "invoice_id", })?, connector_params: self.connector_params.clone(), connector_transaction_id: Some(common_utils::types::ConnectorTransactionId::TxnId( payment_id.get_string_repr().to_string(), )), }; let router_data = self.build_router_data( state, invoice_record_back_req, InvoiceRecordBackData { connector_meta_data: self.connector_metadata.clone(), }, )?; let connector_integration = self.connector_enum.get_connector_integration(); let response = self .call_connector( state, router_data, "invoice record back", connector_integration, ) .await?; match response { Ok(response_data) => Ok(response_data), Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: self.connector_name.to_string(), status_code: err.status_code, reason: err.reason, } .into()), } } pub async fn get_subscription_estimate( &self, state: &SessionState, estimate_request: subscription_types::EstimateSubscriptionQuery, ) -> SubscriptionResult<subscription_response_types::GetSubscriptionEstimateResponse> { let estimate_req = subscription_request_types::GetSubscriptionEstimateRequest { price_id: estimate_request.item_price_id.clone(), }; let router_data = self.build_router_data( state, estimate_req, GetSubscriptionEstimateData { connector_meta_data: self.connector_metadata.clone(), }, )?; let connector_integration = self.connector_enum.get_connector_integration(); let response = Box::pin(self.call_connector( state, router_data, "get subscription estimate from connector", connector_integration, )) .await?; match response { Ok(response_data) => Ok(response_data), Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: self.connector_name.to_string(), status_code: err.status_code, reason: err.reason, } .into()), } } pub async fn get_subscription_plans( &self, state: &SessionState, limit: Option<u32>, offset: Option<u32>, ) -> SubscriptionResult<subscription_response_types::GetSubscriptionPlansResponse> { let get_plans_request = subscription_request_types::GetSubscriptionPlansRequest::new(limit, offset); let router_data = self.build_router_data( state, get_plans_request, GetSubscriptionPlansData { connector_meta_data: self.connector_metadata.clone(), }, )?; let connector_integration = self.connector_enum.get_connector_integration(); let response = self .call_connector( state, router_data, "get subscription plans", connector_integration, ) .await?; match response { Ok(resp) => Ok(resp), Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: self.connector_name.to_string().clone(), status_code: err.status_code, reason: err.reason, } .into()), } } pub async fn get_subscription_plan_prices( &self, state: &SessionState, plan_price_id: String, ) -> SubscriptionResult<subscription_response_types::GetSubscriptionPlanPricesResponse> { let get_plan_prices_request = subscription_request_types::GetSubscriptionPlanPricesRequest { plan_price_id }; let router_data = self.build_router_data( state, get_plan_prices_request, GetSubscriptionPlanPricesData { connector_meta_data: self.connector_metadata.clone(), }, )?; let connector_integration = self.connector_enum.get_connector_integration(); let response = self .call_connector( state, router_data, "get subscription plan prices", connector_integration, ) .await?; match response { Ok(resp) => Ok(resp), Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: self.connector_name.to_string().clone(), status_code: err.status_code, reason: err.reason, } .into()), } } async fn call_connector<F, ResourceCommonData, Req, Resp>( &self, state: &SessionState, router_data: hyperswitch_domain_models::router_data_v2::RouterDataV2< F, ResourceCommonData, Req, Resp, >, operation_name: &str, connector_integration: connector_integration_interface::BoxedConnectorIntegrationInterface< F, ResourceCommonData, Req, Resp, >, ) -> SubscriptionResult<Result<Resp, hyperswitch_domain_models::router_data::ErrorResponse>> where F: Clone + std::fmt::Debug + 'static, Req: Clone + std::fmt::Debug + 'static, Resp: Clone + std::fmt::Debug + 'static, ResourceCommonData: connector_integration_interface::RouterDataConversion<F, Req, Resp> + Clone + 'static, { let old_router_data = ResourceCommonData::to_old_router_data(router_data).change_context( errors::ApiErrorResponse::SubscriptionError { operation: { operation_name.to_string() }, }, )?; let router_resp = api_client::execute_connector_processing_step( state, connector_integration, &old_router_data, CallConnectorAction::Trigger, None, None, ) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: operation_name.to_string(), }) .attach_printable(format!( "Failed while in subscription operation: {operation_name}" ))?; Ok(router_resp.response) } fn build_router_data<F, ResourceCommonData, Req, Resp>( &self, state: &SessionState, req: Req, resource_common_data: ResourceCommonData, ) -> SubscriptionResult< hyperswitch_domain_models::router_data_v2::RouterDataV2<F, ResourceCommonData, Req, Resp>, > { Ok(hyperswitch_domain_models::router_data_v2::RouterDataV2 { flow: std::marker::PhantomData, connector_auth_type: self.auth_type.clone(), resource_common_data, tenant_id: state.tenant.tenant_id.clone(), request: req, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), }) } }
crates/subscriptions/src/core/billing_processor_handler.rs
subscriptions::src::core::billing_processor_handler
3,272
true
// File: crates/subscriptions/src/core/errors.rs // Module: subscriptions::src::core::errors pub use common_utils::errors::{CustomResult, ParsingError, ValidationError}; pub use hyperswitch_domain_models::{ api, errors::api_error_response::{self, *}, }; pub type SubscriptionResult<T> = CustomResult<T, ApiErrorResponse>;
crates/subscriptions/src/core/errors.rs
subscriptions::src::core::errors
73
true
// File: crates/subscriptions/src/core/payments_api_client.rs // Module: subscriptions::src::core::payments_api_client use api_models::subscription as subscription_types; use common_utils::{ext_traits::BytesExt, request as services}; use error_stack::ResultExt; use hyperswitch_interfaces::api_client as api; use crate::{core::errors, helpers, state::SubscriptionState as SessionState}; pub struct PaymentsApiClient; #[derive(Debug, serde::Deserialize)] pub struct ErrorResponse { error: ErrorResponseDetails, } #[derive(Debug, serde::Deserialize)] pub struct ErrorResponseDetails { #[serde(rename = "type")] error_type: Option<String>, code: String, message: String, } impl PaymentsApiClient { fn get_internal_auth_headers( state: &SessionState, merchant_id: &str, profile_id: &str, ) -> Vec<(String, masking::Maskable<String>)> { vec![ ( helpers::X_INTERNAL_API_KEY.to_string(), masking::Maskable::Masked( state .conf .internal_merchant_id_profile_id_auth .internal_api_key .clone(), ), ), ( helpers::X_TENANT_ID.to_string(), masking::Maskable::Normal(state.tenant.tenant_id.get_string_repr().to_string()), ), ( helpers::X_MERCHANT_ID.to_string(), masking::Maskable::Normal(merchant_id.to_string()), ), ( helpers::X_PROFILE_ID.to_string(), masking::Maskable::Normal(profile_id.to_string()), ), ] } /// Generic method to handle payment API calls with different HTTP methods and URL patterns async fn make_payment_api_call( state: &SessionState, method: services::Method, url: String, request_body: Option<common_utils::request::RequestContent>, operation_name: &str, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let subscription_error = errors::ApiErrorResponse::SubscriptionError { operation: operation_name.to_string(), }; let headers = Self::get_internal_auth_headers(state, merchant_id, profile_id); let mut request_builder = services::RequestBuilder::new() .method(method) .url(&url) .headers(headers); // Add request body only if provided (for POST requests) if let Some(body) = request_body { request_builder = request_builder.set_body(body); } let request = request_builder.build(); let response = api::call_connector_api(state, request, "Subscription Payments") .await .change_context(subscription_error.clone())?; match response { Ok(res) => { let api_response: subscription_types::PaymentResponseData = res .response .parse_struct(std::any::type_name::<subscription_types::PaymentResponseData>()) .change_context(subscription_error)?; Ok(api_response) } Err(err) => { let error_response: ErrorResponse = err .response .parse_struct(std::any::type_name::<ErrorResponse>()) .change_context(subscription_error)?; Err(errors::ApiErrorResponse::ExternalConnectorError { code: error_response.error.code, message: error_response.error.message, connector: "payments_microservice".to_string(), status_code: err.status_code, reason: error_response.error.error_type, } .into()) } } } pub async fn create_cit_payment( state: &SessionState, request: subscription_types::CreatePaymentsRequestData, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments", base_url); Self::make_payment_api_call( state, services::Method::Post, url, Some(common_utils::request::RequestContent::Json(Box::new( request, ))), "Create Payment", merchant_id, profile_id, ) .await } pub async fn create_and_confirm_payment( state: &SessionState, request: subscription_types::CreateAndConfirmPaymentsRequestData, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments", base_url); Self::make_payment_api_call( state, services::Method::Post, url, Some(common_utils::request::RequestContent::Json(Box::new( request, ))), "Create And Confirm Payment", merchant_id, profile_id, ) .await } pub async fn confirm_payment( state: &SessionState, request: subscription_types::ConfirmPaymentsRequestData, payment_id: String, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments/{}/confirm", base_url, payment_id); Self::make_payment_api_call( state, services::Method::Post, url, Some(common_utils::request::RequestContent::Json(Box::new( request, ))), "Confirm Payment", merchant_id, profile_id, ) .await } pub async fn sync_payment( state: &SessionState, payment_id: String, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments/{}", base_url, payment_id); Self::make_payment_api_call( state, services::Method::Get, url, None, "Sync Payment", merchant_id, profile_id, ) .await } pub async fn create_mit_payment( state: &SessionState, request: subscription_types::CreateMitPaymentRequestData, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments", base_url); Self::make_payment_api_call( state, services::Method::Post, url, Some(common_utils::request::RequestContent::Json(Box::new( request, ))), "Create MIT Payment", merchant_id, profile_id, ) .await } pub async fn update_payment( state: &SessionState, request: subscription_types::CreatePaymentsRequestData, payment_id: String, merchant_id: &str, profile_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let base_url = &state.conf.internal_services.payments_base_url; let url = format!("{}/payments/{}", base_url, payment_id); Self::make_payment_api_call( state, services::Method::Post, url, Some(common_utils::request::RequestContent::Json(Box::new( request, ))), "Update Payment", merchant_id, profile_id, ) .await } }
crates/subscriptions/src/core/payments_api_client.rs
subscriptions::src::core::payments_api_client
1,632
true
// File: crates/subscriptions/src/core/invoice_handler.rs // Module: subscriptions::src::core::invoice_handler use api_models::{ enums as api_enums, subscription::{self as subscription_types}, }; use common_enums::connector_enums; use common_utils::{pii, types::MinorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::router_response_types::subscriptions as subscription_response_types; use super::errors; use crate::{ core::payments_api_client, state::SubscriptionState as SessionState, types::storage as storage_types, workflows::invoice_sync as invoice_sync_workflow, }; pub struct InvoiceHandler { pub subscription: hyperswitch_domain_models::subscription::Subscription, pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, pub profile: hyperswitch_domain_models::business_profile::Profile, pub merchant_key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, } #[allow(clippy::todo)] impl InvoiceHandler { pub fn new( subscription: hyperswitch_domain_models::subscription::Subscription, merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, profile: hyperswitch_domain_models::business_profile::Profile, merchant_key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> Self { Self { subscription, merchant_account, profile, merchant_key_store, } } #[allow(clippy::too_many_arguments)] pub async fn create_invoice_entry( &self, state: &SessionState, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, payment_intent_id: Option<common_utils::id_type::PaymentId>, amount: MinorUnit, currency: common_enums::Currency, status: connector_enums::InvoiceStatus, provider_name: connector_enums::Connector, metadata: Option<pii::SecretSerdeValue>, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> { let invoice_new = hyperswitch_domain_models::invoice::Invoice::to_invoice( self.subscription.id.to_owned(), self.subscription.merchant_id.to_owned(), self.subscription.profile_id.to_owned(), merchant_connector_id, payment_intent_id, self.subscription.payment_method_id.clone(), self.subscription.customer_id.to_owned(), amount, currency.to_string(), status, provider_name, metadata, connector_invoice_id, ); let key_manager_state = &(state).into(); let invoice = state .store .insert_invoice_entry(key_manager_state, &self.merchant_key_store, invoice_new) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Create Invoice".to_string(), }) .attach_printable("invoices: unable to insert invoice entry to database")?; Ok(invoice) } pub async fn update_invoice( &self, state: &SessionState, invoice_id: common_utils::id_type::InvoiceId, update_request: hyperswitch_domain_models::invoice::InvoiceUpdateRequest, ) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> { let update_invoice: hyperswitch_domain_models::invoice::InvoiceUpdate = update_request.into(); let key_manager_state = &(state).into(); state .store .update_invoice_entry( key_manager_state, &self.merchant_key_store, invoice_id.get_string_repr().to_string(), update_invoice, ) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Invoice Update".to_string(), }) .attach_printable("invoices: unable to update invoice entry in database") } pub fn get_amount_and_currency( request: (Option<MinorUnit>, Option<api_enums::Currency>), invoice_details: Option<subscription_response_types::SubscriptionInvoiceData>, ) -> (MinorUnit, api_enums::Currency) { // Use request amount and currency if provided, else fallback to invoice details from connector response request.0.zip(request.1).unwrap_or( invoice_details .clone() .map(|invoice| (invoice.total, invoice.currency_code)) .unwrap_or((MinorUnit::new(0), api_enums::Currency::default())), ) // Default to 0 and a default currency if not provided } pub async fn create_payment_with_confirm_false( &self, state: &SessionState, request: &subscription_types::CreateSubscriptionRequest, amount: MinorUnit, currency: api_enums::Currency, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let payment_details = &request.payment_details; let payment_request = subscription_types::CreatePaymentsRequestData { amount, currency, customer_id: Some(self.subscription.customer_id.clone()), billing: request.billing.clone(), shipping: request.shipping.clone(), profile_id: Some(self.profile.get_id().clone()), setup_future_usage: payment_details.setup_future_usage, return_url: Some(payment_details.return_url.clone()), capture_method: payment_details.capture_method, authentication_type: payment_details.authentication_type, }; payments_api_client::PaymentsApiClient::create_cit_payment( state, payment_request, self.merchant_account.get_id().get_string_repr(), self.profile.get_id().get_string_repr(), ) .await } pub async fn get_payment_details( &self, state: &SessionState, payment_id: common_utils::id_type::PaymentId, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { payments_api_client::PaymentsApiClient::sync_payment( state, payment_id.get_string_repr().to_string(), self.merchant_account.get_id().get_string_repr(), self.profile.get_id().get_string_repr(), ) .await } pub async fn create_and_confirm_payment( &self, state: &SessionState, request: &subscription_types::CreateAndConfirmSubscriptionRequest, amount: MinorUnit, currency: common_enums::Currency, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let payment_details = &request.payment_details; let payment_request = subscription_types::CreateAndConfirmPaymentsRequestData { amount, currency, confirm: true, customer_id: Some(self.subscription.customer_id.clone()), billing: request.get_billing_address(), shipping: request.shipping.clone(), profile_id: Some(self.profile.get_id().clone()), setup_future_usage: payment_details.setup_future_usage, return_url: payment_details.return_url.clone(), capture_method: payment_details.capture_method, authentication_type: payment_details.authentication_type, payment_method: payment_details.payment_method, payment_method_type: payment_details.payment_method_type, payment_method_data: payment_details.payment_method_data.clone(), customer_acceptance: payment_details.customer_acceptance.clone(), payment_type: payment_details.payment_type, }; payments_api_client::PaymentsApiClient::create_and_confirm_payment( state, payment_request, self.merchant_account.get_id().get_string_repr(), self.profile.get_id().get_string_repr(), ) .await } pub async fn confirm_payment( &self, state: &SessionState, payment_id: common_utils::id_type::PaymentId, request: &subscription_types::ConfirmSubscriptionRequest, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let payment_details = &request.payment_details; let cit_payment_request = subscription_types::ConfirmPaymentsRequestData { billing: request.get_billing_address(), shipping: request.payment_details.shipping.clone(), profile_id: Some(self.profile.get_id().clone()), payment_method: payment_details.payment_method, payment_method_type: payment_details.payment_method_type, payment_method_data: payment_details.payment_method_data.clone(), customer_acceptance: payment_details.customer_acceptance.clone(), payment_type: payment_details.payment_type, }; payments_api_client::PaymentsApiClient::confirm_payment( state, cit_payment_request, payment_id.get_string_repr().to_string(), self.merchant_account.get_id().get_string_repr(), self.profile.get_id().get_string_repr(), ) .await } pub async fn get_latest_invoice( &self, state: &SessionState, ) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> { let key_manager_state = &(state).into(); state .store .get_latest_invoice_for_subscription( key_manager_state, &self.merchant_key_store, self.subscription.id.get_string_repr().to_string(), ) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Get Latest Invoice".to_string(), }) .attach_printable("invoices: unable to get latest invoice from database") } pub async fn get_invoice_by_id( &self, state: &SessionState, invoice_id: common_utils::id_type::InvoiceId, ) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> { let key_manager_state = &(state).into(); state .store .find_invoice_by_invoice_id( key_manager_state, &self.merchant_key_store, invoice_id.get_string_repr().to_string(), ) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Get Invoice by ID".to_string(), }) .attach_printable("invoices: unable to get invoice by id from database") } pub async fn find_invoice_by_subscription_id_connector_invoice_id( &self, state: &SessionState, subscription_id: common_utils::id_type::SubscriptionId, connector_invoice_id: common_utils::id_type::InvoiceId, ) -> errors::SubscriptionResult<Option<hyperswitch_domain_models::invoice::Invoice>> { let key_manager_state = &(state).into(); state .store .find_invoice_by_subscription_id_connector_invoice_id( key_manager_state, &self.merchant_key_store, subscription_id.get_string_repr().to_string(), connector_invoice_id, ) .await .change_context(errors::ApiErrorResponse::SubscriptionError { operation: "Get Invoice by Subscription ID and Connector Invoice ID".to_string(), }) .attach_printable("invoices: unable to get invoice by subscription id and connector invoice id from database") } pub async fn create_invoice_sync_job( &self, state: &SessionState, invoice: &hyperswitch_domain_models::invoice::Invoice, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, connector_name: connector_enums::Connector, ) -> errors::SubscriptionResult<()> { let request = storage_types::invoice_sync::InvoiceSyncRequest::new( self.subscription.id.to_owned(), invoice.id.to_owned(), self.subscription.merchant_id.to_owned(), self.subscription.profile_id.to_owned(), self.subscription.customer_id.to_owned(), connector_invoice_id, connector_name, ); invoice_sync_workflow::create_invoice_sync_job(state, request) .await .attach_printable("invoices: unable to create invoice sync job in database")?; Ok(()) } pub async fn create_mit_payment( &self, state: &SessionState, amount: MinorUnit, currency: common_enums::Currency, payment_method_id: &str, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let mit_payment_request = subscription_types::CreateMitPaymentRequestData { amount, currency, confirm: true, customer_id: Some(self.subscription.customer_id.clone()), recurring_details: Some(api_models::mandates::RecurringDetails::PaymentMethodId( payment_method_id.to_owned(), )), off_session: Some(true), profile_id: Some(self.profile.get_id().clone()), }; payments_api_client::PaymentsApiClient::create_mit_payment( state, mit_payment_request, self.merchant_account.get_id().get_string_repr(), self.profile.get_id().get_string_repr(), ) .await } pub async fn update_payment( &self, state: &SessionState, amount: MinorUnit, currency: common_enums::Currency, payment_id: common_utils::id_type::PaymentId, ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> { let payment_update_request = subscription_types::CreatePaymentsRequestData { amount, currency, customer_id: None, billing: None, shipping: None, profile_id: None, setup_future_usage: None, return_url: None, capture_method: None, authentication_type: None, }; payments_api_client::PaymentsApiClient::update_payment( state, payment_update_request, payment_id.get_string_repr().to_string(), self.merchant_account.get_id().get_string_repr(), self.profile.get_id().get_string_repr(), ) .await } }
crates/subscriptions/src/core/invoice_handler.rs
subscriptions::src::core::invoice_handler
2,825
true
// File: crates/subscriptions/src/workflows/invoice_sync.rs // Module: subscriptions::src::workflows::invoice_sync #[cfg(feature = "v1")] use api_models::subscription as subscription_types; use common_utils::{errors::CustomResult, ext_traits::StringExt}; use error_stack::ResultExt; use hyperswitch_domain_models::invoice::InvoiceUpdateRequest; use router_env::logger; use scheduler::{ errors, types::process_data, utils as scheduler_utils, workflows::storage::{business_status, ProcessTracker, ProcessTrackerNew}, }; use storage_impl::StorageError; use crate::{ core::{ billing_processor_handler as billing, errors as router_errors, invoice_handler, payments_api_client, }, state::{SubscriptionState as SessionState, SubscriptionStorageInterface as StorageInterface}, types::storage, }; const INVOICE_SYNC_WORKFLOW: &str = "INVOICE_SYNC"; const INVOICE_SYNC_WORKFLOW_TAG: &str = "INVOICE"; pub struct InvoiceSyncHandler<'a> { pub state: &'a SessionState, pub tracking_data: storage::invoice_sync::InvoiceSyncTrackingData, pub key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount, pub customer: hyperswitch_domain_models::customer::Customer, pub profile: hyperswitch_domain_models::business_profile::Profile, pub subscription: hyperswitch_domain_models::subscription::Subscription, pub invoice: hyperswitch_domain_models::invoice::Invoice, } #[cfg(feature = "v1")] impl<'a> InvoiceSyncHandler<'a> { pub async fn create( state: &'a SessionState, tracking_data: storage::invoice_sync::InvoiceSyncTrackingData, ) -> Result<Self, errors::ProcessTrackerError> { let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &tracking_data.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .attach_printable("Failed to fetch Merchant key store from DB")?; let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &tracking_data.merchant_id, &key_store, ) .await .attach_printable("Subscriptions: Failed to fetch Merchant Account from DB")?; let profile = state .store .find_business_profile_by_profile_id( &(state).into(), &key_store, &tracking_data.profile_id, ) .await .attach_printable("Subscriptions: Failed to fetch Business Profile from DB")?; let customer = state .store .find_customer_by_customer_id_merchant_id( &(state).into(), &tracking_data.customer_id, merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .attach_printable("Subscriptions: Failed to fetch Customer from DB")?; let subscription = state .store .find_by_merchant_id_subscription_id( &state.into(), &key_store, merchant_account.get_id(), tracking_data.subscription_id.get_string_repr().to_string(), ) .await .attach_printable("Subscriptions: Failed to fetch subscription from DB")?; let invoice = state .store .find_invoice_by_invoice_id( &state.into(), &key_store, tracking_data.invoice_id.get_string_repr().to_string(), ) .await .attach_printable("invoices: unable to get latest invoice from database")?; Ok(Self { state, tracking_data, key_store, merchant_account, customer, profile, subscription, invoice, }) } async fn finish_process_with_business_status( &self, process: &ProcessTracker, business_status: &'static str, ) -> CustomResult<(), router_errors::ApiErrorResponse> { self.state .store .as_scheduler() .finish_process_with_business_status(process.clone(), business_status) .await .change_context(router_errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update process tracker status") } pub async fn perform_payments_sync( &self, ) -> CustomResult<subscription_types::PaymentResponseData, router_errors::ApiErrorResponse> { logger::info!( "perform_payments_sync called for invoice_id: {:?} and payment_id: {:?}", self.invoice.id, self.invoice.payment_intent_id ); let payment_id = self.invoice.payment_intent_id.clone().ok_or( router_errors::ApiErrorResponse::SubscriptionError { operation: "Invoice_sync: Missing Payment Intent ID in Invoice".to_string(), }, )?; let payments_response = payments_api_client::PaymentsApiClient::sync_payment( self.state, payment_id.get_string_repr().to_string(), self.merchant_account.get_id().get_string_repr(), self.profile.get_id().get_string_repr(), ) .await .change_context(router_errors::ApiErrorResponse::SubscriptionError { operation: "Invoice_sync: Failed to sync payment status from payments microservice" .to_string(), }) .attach_printable("Failed to sync payment status from payments microservice")?; Ok(payments_response) } pub async fn perform_billing_processor_record_back_if_possible( &self, payment_response: subscription_types::PaymentResponseData, payment_status: common_enums::AttemptStatus, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, invoice_sync_status: storage::invoice_sync::InvoiceSyncPaymentStatus, ) -> CustomResult<(), router_errors::ApiErrorResponse> { if let Some(connector_invoice_id) = connector_invoice_id { Box::pin(self.perform_billing_processor_record_back( payment_response, payment_status, connector_invoice_id, invoice_sync_status, )) .await .attach_printable("Failed to record back to billing processor")?; } Ok(()) } pub async fn perform_billing_processor_record_back( &self, payment_response: subscription_types::PaymentResponseData, payment_status: common_enums::AttemptStatus, connector_invoice_id: common_utils::id_type::InvoiceId, invoice_sync_status: storage::invoice_sync::InvoiceSyncPaymentStatus, ) -> CustomResult<(), router_errors::ApiErrorResponse> { logger::info!("perform_billing_processor_record_back"); let billing_handler = billing::BillingHandler::create( self.state, &self.merchant_account, &self.key_store, self.profile.clone(), ) .await .attach_printable("Failed to create billing handler")?; let invoice_handler = invoice_handler::InvoiceHandler::new( self.subscription.clone(), self.merchant_account.clone(), self.profile.clone(), self.key_store.clone(), ); // TODO: Handle retries here on failure billing_handler .record_back_to_billing_processor( self.state, connector_invoice_id.clone(), payment_response.payment_id.to_owned(), payment_status, payment_response.amount, payment_response.currency, payment_response.payment_method_type, ) .await .attach_printable("Failed to record back to billing processor")?; let update_request = InvoiceUpdateRequest::update_connector_and_status( connector_invoice_id, common_enums::connector_enums::InvoiceStatus::from(invoice_sync_status), ); invoice_handler .update_invoice(self.state, self.invoice.id.to_owned(), update_request) .await .attach_printable("Failed to update invoice in DB")?; Ok(()) } pub async fn transition_workflow_state( &self, process: ProcessTracker, payment_response: subscription_types::PaymentResponseData, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> CustomResult<(), router_errors::ApiErrorResponse> { logger::info!( "transition_workflow_state called with status: {:?}", payment_response.status ); let invoice_sync_status = storage::invoice_sync::InvoiceSyncPaymentStatus::from(payment_response.status); let (payment_status, status) = match invoice_sync_status { storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentSucceeded => (common_enums::AttemptStatus::Charged, "succeeded"), storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentFailed => (common_enums::AttemptStatus::Failure, "failed"), storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentProcessing => return Err( router_errors::ApiErrorResponse::SubscriptionError { operation: "Invoice_sync: Payment in processing state, cannot transition workflow state" .to_string(), }, )?, }; logger::info!("Performing billing processor record back for status: {status}"); Box::pin(self.perform_billing_processor_record_back_if_possible( payment_response.clone(), payment_status, connector_invoice_id, invoice_sync_status.clone(), )) .await .attach_printable(format!( "Failed to record back {status} status to billing processor" ))?; self.finish_process_with_business_status(&process, business_status::COMPLETED_BY_PT) .await .change_context(router_errors::ApiErrorResponse::SubscriptionError { operation: "Invoice_sync process_tracker task completion".to_string(), }) .attach_printable("Failed to update process tracker status") } } #[cfg(feature = "v1")] pub async fn perform_subscription_invoice_sync( state: &SessionState, process: ProcessTracker, tracking_data: storage::invoice_sync::InvoiceSyncTrackingData, ) -> Result<(), errors::ProcessTrackerError> { let handler = InvoiceSyncHandler::create(state, tracking_data).await?; let payment_status = handler.perform_payments_sync().await?; if let Err(e) = Box::pin(handler.transition_workflow_state( process.clone(), payment_status, handler.tracking_data.connector_invoice_id.clone(), )) .await { logger::error!(?e, "Error in transitioning workflow state"); retry_subscription_invoice_sync_task( &*handler.state.store, handler.tracking_data.connector_name.to_string().clone(), handler.merchant_account.get_id().to_owned(), process, ) .await .change_context(router_errors::ApiErrorResponse::SubscriptionError { operation: "Invoice_sync process_tracker task retry".to_string(), }) .attach_printable("Failed to update process tracker status")?; }; Ok(()) } pub async fn create_invoice_sync_job( state: &SessionState, request: storage::invoice_sync::InvoiceSyncRequest, ) -> CustomResult<(), router_errors::ApiErrorResponse> { let tracking_data = storage::invoice_sync::InvoiceSyncTrackingData::from(request); let process_tracker_entry = ProcessTrackerNew::new( common_utils::generate_id(common_utils::consts::ID_LENGTH, "proc"), INVOICE_SYNC_WORKFLOW.to_string(), common_enums::ProcessTrackerRunner::InvoiceSyncflow, vec![INVOICE_SYNC_WORKFLOW_TAG.to_string()], tracking_data, Some(0), common_utils::date_time::now(), common_types::consts::API_VERSION, ) .change_context(router_errors::ApiErrorResponse::InternalServerError) .attach_printable("subscriptions: unable to form process_tracker type")?; state .store .insert_process(process_tracker_entry) .await .change_context(router_errors::ApiErrorResponse::InternalServerError) .attach_printable("subscriptions: unable to insert process_tracker entry in DB")?; Ok(()) } pub async fn get_subscription_invoice_sync_process_schedule_time( db: &dyn StorageInterface, connector: &str, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let mapping: CustomResult<process_data::SubscriptionInvoiceSyncPTMapping, StorageError> = db .find_config_by_key(&format!("invoice_sync_pt_mapping_{connector}")) .await .map(|value| value.config) .and_then(|config| { config .parse_struct("SubscriptionInvoiceSyncPTMapping") .change_context(StorageError::DeserializationFailed) .attach_printable("Failed to deserialize invoice_sync_pt_mapping config to struct") }); let mapping = match mapping { Ok(x) => x, Err(error) => { logger::info!(?error, "Redis Mapping Error"); process_data::SubscriptionInvoiceSyncPTMapping::default() } }; let time_delta = scheduler_utils::get_subscription_invoice_sync_retry_schedule_time( mapping, merchant_id, retry_count, ); Ok(scheduler_utils::get_time_from_delta(time_delta)) } pub async fn retry_subscription_invoice_sync_task( db: &dyn StorageInterface, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let schedule_time = get_subscription_invoice_sync_process_schedule_time( db, connector.as_str(), &merchant_id, pt.retry_count + 1, ) .await?; match schedule_time { Some(s_time) => { db.as_scheduler() .retry_process(pt, s_time) .await .attach_printable("Failed to retry subscription invoice sync task")?; } None => { db.as_scheduler() .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) .await .attach_printable("Failed to finish subscription invoice sync task")?; } } Ok(()) }
crates/subscriptions/src/workflows/invoice_sync.rs
subscriptions::src::workflows::invoice_sync
2,963
true
// File: crates/hsdev/src/main.rs // Module: hsdev::src::main #![allow(clippy::print_stdout, clippy::print_stderr)] use clap::{Parser, ValueHint}; use diesel::{pg::PgConnection, Connection}; use diesel_migrations::{FileBasedMigrations, HarnessWithOutput, MigrationHarness}; use toml::Value; mod input_file; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { #[arg(short, long, value_hint = ValueHint::FilePath)] toml_file: std::path::PathBuf, #[arg(long, default_value_t = String::from(""))] toml_table: String, } fn main() { let args = Args::parse(); let toml_file = &args.toml_file; let table_name = &args.toml_table; let toml_contents = match std::fs::read_to_string(toml_file) { Ok(contents) => contents, Err(e) => { eprintln!("Error reading TOML file: {e}"); return; } }; let toml_data: Value = match toml_contents.parse() { Ok(data) => data, Err(e) => { eprintln!("Error parsing TOML file: {e}"); return; } }; let table = get_toml_table(table_name, &toml_data); let input = match input_file::InputData::read(table) { Ok(data) => data, Err(e) => { eprintln!("Error loading TOML file: {e}"); return; } }; let db_url = input.postgres_url(); println!("Attempting to connect to {db_url}"); let mut conn = match PgConnection::establish(&db_url) { Ok(value) => value, Err(_) => { eprintln!("Unable to establish database connection"); return; } }; let migrations = match FileBasedMigrations::find_migrations_directory() { Ok(value) => value, Err(_) => { eprintln!("Could not find migrations directory"); return; } }; let mut harness = HarnessWithOutput::write_to_stdout(&mut conn); match harness.run_pending_migrations(migrations) { Ok(_) => println!("Successfully ran migrations"), Err(_) => eprintln!("Couldn't run migrations"), }; } pub fn get_toml_table<'a>(table_name: &'a str, toml_data: &'a Value) -> &'a Value { if !table_name.is_empty() { match toml_data.get(table_name) { Some(value) => value, None => { eprintln!("Unable to find toml table: \"{}\"", &table_name); std::process::abort() } } } else { toml_data } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use std::str::FromStr; use toml::Value; use crate::{get_toml_table, input_file::InputData}; #[test] fn test_input_file() { let toml_str = r#"username = "db_user" password = "db_pass" dbname = "db_name" host = "localhost" port = 5432"#; let toml_value = Value::from_str(toml_str); assert!(toml_value.is_ok()); let toml_value = toml_value.unwrap(); let toml_table = InputData::read(&toml_value); assert!(toml_table.is_ok()); let toml_table = toml_table.unwrap(); let db_url = toml_table.postgres_url(); assert_eq!("postgres://db_user:db_pass@localhost:5432/db_name", db_url); } #[test] fn test_given_toml() { let toml_str_table = r#"[database] username = "db_user" password = "db_pass" dbname = "db_name" host = "localhost" port = 5432"#; let table_name = "database"; let toml_value = Value::from_str(toml_str_table).unwrap(); let table = get_toml_table(table_name, &toml_value); assert!(table.is_table()); let table_name = ""; let table = get_toml_table(table_name, &toml_value); assert!(table.is_table()); } }
crates/hsdev/src/main.rs
hsdev::src::main
972
true
// File: crates/hsdev/src/input_file.rs // Module: hsdev::src::input_file use std::string::String; use serde::Deserialize; use toml::Value; #[derive(Deserialize)] pub struct InputData { username: String, password: String, dbname: String, host: String, port: u16, } impl InputData { pub fn read(db_table: &Value) -> Result<Self, toml::de::Error> { db_table.clone().try_into() } pub fn postgres_url(&self) -> String { format!( "postgres://{}:{}@{}:{}/{}", self.username, self.password, self.host, self.port, self.dbname ) } }
crates/hsdev/src/input_file.rs
hsdev::src::input_file
163
true
// File: crates/euclid/benches/backends.rs // Module: euclid::benches::backends #![allow(unused, clippy::expect_used)] use common_utils::types::MinorUnit; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use euclid::{ backend::{inputs, EuclidBackend, InterpreterBackend, VirInterpreterBackend}, enums, frontend::ast::{self, parser}, types::DummyOutput, }; fn get_program_data() -> (ast::Program<DummyOutput>, inputs::BackendInput) { let code1 = r#" default: ["stripe", "adyen", "checkout"] stripe_first: ["stripe", "aci"] { payment_method = card & amount = 40 { payment_method = (card, bank_redirect) amount = (40, 50) } } adyen_first: ["adyen", "checkout"] { payment_method = bank_redirect & amount > 60 { payment_method = (card, bank_redirect) amount = (40, 50) } } auth_first: ["authorizedotnet", "adyen"] { payment_method = wallet } "#; let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), card_bin: None, currency: enums::Currency::USD, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Sofort), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, issuer_data: None, acquirer_data: None, customer_device_data: None, }; let (_, program) = parser::program(code1).expect("Parser"); (program, inp) } fn interpreter_vs_jit_vs_vir_interpreter(c: &mut Criterion) { let (program, binputs) = get_program_data(); let interp_b = InterpreterBackend::with_program(program.clone()).expect("Interpreter backend"); let vir_interp_b = VirInterpreterBackend::with_program(program).expect("Vir Interpreter Backend"); c.bench_function("Raw Interpreter Backend", |b| { b.iter(|| { interp_b .execute(binputs.clone()) .expect("Interpreter EXECUTION"); }); }); c.bench_function("Valued Interpreter Backend", |b| { b.iter(|| { vir_interp_b .execute(binputs.clone()) .expect("Vir Interpreter execution"); }) }); } criterion_group!(benches, interpreter_vs_jit_vs_vir_interpreter); criterion_main!(benches);
crates/euclid/benches/backends.rs
euclid::benches::backends
691
true
// File: crates/euclid/src/frontend.rs // Module: euclid::src::frontend pub mod ast; pub mod dir; pub mod vir;
crates/euclid/src/frontend.rs
euclid::src::frontend
33
true
// File: crates/euclid/src/types.rs // Module: euclid::src::types pub mod transformers; use common_utils::types::MinorUnit; use euclid_macros::EnumNums; use serde::{Deserialize, Serialize}; use strum::VariantNames; use crate::{ dssa::types::EuclidAnalysable, enums, frontend::{ ast, dir::{ enums::{CustomerDeviceDisplaySize, CustomerDevicePlatform, CustomerDeviceType}, DirKeyKind, DirValue, EuclidDirFilter, }, }, }; pub type Metadata = std::collections::HashMap<String, serde_json::Value>; #[derive( Debug, Clone, EnumNums, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumString, )] pub enum EuclidKey { #[strum(serialize = "payment_method")] PaymentMethod, #[strum(serialize = "card_bin")] CardBin, #[strum(serialize = "metadata")] Metadata, #[strum(serialize = "mandate_type")] MandateType, #[strum(serialize = "mandate_acceptance_type")] MandateAcceptanceType, #[strum(serialize = "payment_type")] PaymentType, #[strum(serialize = "payment_method_type")] PaymentMethodType, #[strum(serialize = "card_network")] CardNetwork, #[strum(serialize = "authentication_type")] AuthenticationType, #[strum(serialize = "capture_method")] CaptureMethod, #[strum(serialize = "amount")] PaymentAmount, #[strum(serialize = "currency")] PaymentCurrency, #[cfg(feature = "payouts")] #[strum(serialize = "payout_currency")] PayoutCurrency, #[strum(serialize = "country", to_string = "business_country")] BusinessCountry, #[strum(serialize = "billing_country")] BillingCountry, #[strum(serialize = "business_label")] BusinessLabel, #[strum(serialize = "setup_future_usage")] SetupFutureUsage, #[strum(serialize = "issuer_name")] IssuerName, #[strum(serialize = "issuer_country")] IssuerCountry, #[strum(serialize = "acquirer_country")] AcquirerCountry, #[strum(serialize = "acquirer_fraud_rate")] AcquirerFraudRate, #[strum(serialize = "customer_device_type")] CustomerDeviceType, #[strum(serialize = "customer_device_display_size")] CustomerDeviceDisplaySize, #[strum(serialize = "customer_device_platform")] CustomerDevicePlatform, } impl EuclidDirFilter for DummyOutput { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::AuthenticationType, DirKeyKind::PaymentMethod, DirKeyKind::CardType, DirKeyKind::PaymentCurrency, DirKeyKind::CaptureMethod, DirKeyKind::AuthenticationType, DirKeyKind::CardBin, DirKeyKind::PayLaterType, DirKeyKind::PaymentAmount, DirKeyKind::MetaData, DirKeyKind::MandateAcceptanceType, DirKeyKind::MandateType, DirKeyKind::PaymentType, DirKeyKind::SetupFutureUsage, ]; } impl EuclidAnalysable for DummyOutput { fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(DirValue, Metadata)> { self.outputs .iter() .map(|dummyc| { let metadata_key = "MetadataKey".to_string(); let metadata_value = dummyc; ( DirValue::MetaData(MetadataValue { key: metadata_key.clone(), value: metadata_value.clone(), }), std::collections::HashMap::from_iter([( "DUMMY_OUTPUT".to_string(), serde_json::json!({ "rule_name":rule_name, "Metadata_Key" :metadata_key, "Metadata_Value" : metadata_value, }), )]), ) }) .collect() } } #[derive(Debug, Clone, Serialize)] pub struct DummyOutput { pub outputs: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, strum::Display)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DataType { Number, EnumVariant, MetadataValue, StrValue, } impl EuclidKey { pub fn key_type(&self) -> DataType { match self { Self::PaymentMethod => DataType::EnumVariant, Self::CardBin => DataType::StrValue, Self::Metadata => DataType::MetadataValue, Self::PaymentMethodType => DataType::EnumVariant, Self::CardNetwork => DataType::EnumVariant, Self::AuthenticationType => DataType::EnumVariant, Self::CaptureMethod => DataType::EnumVariant, Self::PaymentAmount => DataType::Number, Self::PaymentCurrency => DataType::EnumVariant, #[cfg(feature = "payouts")] Self::PayoutCurrency => DataType::EnumVariant, Self::BusinessCountry => DataType::EnumVariant, Self::BillingCountry => DataType::EnumVariant, Self::MandateType => DataType::EnumVariant, Self::MandateAcceptanceType => DataType::EnumVariant, Self::PaymentType => DataType::EnumVariant, Self::BusinessLabel => DataType::StrValue, Self::SetupFutureUsage => DataType::EnumVariant, Self::IssuerName => DataType::StrValue, Self::IssuerCountry => DataType::EnumVariant, Self::AcquirerCountry => DataType::EnumVariant, Self::AcquirerFraudRate => DataType::Number, Self::CustomerDeviceType => DataType::EnumVariant, Self::CustomerDeviceDisplaySize => DataType::EnumVariant, Self::CustomerDevicePlatform => DataType::EnumVariant, } } } enums::collect_variants!(EuclidKey); #[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum NumValueRefinement { NotEqual, GreaterThan, LessThan, GreaterThanEqual, LessThanEqual, } impl From<ast::ComparisonType> for Option<NumValueRefinement> { fn from(comp_type: ast::ComparisonType) -> Self { match comp_type { ast::ComparisonType::Equal => None, ast::ComparisonType::NotEqual => Some(NumValueRefinement::NotEqual), ast::ComparisonType::GreaterThan => Some(NumValueRefinement::GreaterThan), ast::ComparisonType::LessThan => Some(NumValueRefinement::LessThan), ast::ComparisonType::LessThanEqual => Some(NumValueRefinement::LessThanEqual), ast::ComparisonType::GreaterThanEqual => Some(NumValueRefinement::GreaterThanEqual), } } } impl From<NumValueRefinement> for ast::ComparisonType { fn from(value: NumValueRefinement) -> Self { match value { NumValueRefinement::NotEqual => Self::NotEqual, NumValueRefinement::LessThan => Self::LessThan, NumValueRefinement::GreaterThan => Self::GreaterThan, NumValueRefinement::GreaterThanEqual => Self::GreaterThanEqual, NumValueRefinement::LessThanEqual => Self::LessThanEqual, } } } #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct StrValue { pub value: String, } #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct MetadataValue { pub key: String, pub value: String, } #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct NumValue { pub number: MinorUnit, pub refinement: Option<NumValueRefinement>, } impl NumValue { pub fn fits(&self, other: &Self) -> bool { let this_num = self.number; let other_num = other.number; match (&self.refinement, &other.refinement) { (None, None) => this_num == other_num, (Some(NumValueRefinement::GreaterThan), None) => other_num > this_num, (Some(NumValueRefinement::LessThan), None) => other_num < this_num, (Some(NumValueRefinement::NotEqual), Some(NumValueRefinement::NotEqual)) => { other_num == this_num } (Some(NumValueRefinement::GreaterThan), Some(NumValueRefinement::GreaterThan)) => { other_num > this_num } (Some(NumValueRefinement::LessThan), Some(NumValueRefinement::LessThan)) => { other_num < this_num } (Some(NumValueRefinement::GreaterThanEqual), None) => other_num >= this_num, (Some(NumValueRefinement::LessThanEqual), None) => other_num <= this_num, ( Some(NumValueRefinement::GreaterThanEqual), Some(NumValueRefinement::GreaterThanEqual), ) => other_num >= this_num, (Some(NumValueRefinement::LessThanEqual), Some(NumValueRefinement::LessThanEqual)) => { other_num <= this_num } _ => false, } } } #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum EuclidValue { PaymentMethod(enums::PaymentMethod), CardBin(StrValue), Metadata(MetadataValue), PaymentMethodType(enums::PaymentMethodType), CardNetwork(enums::CardNetwork), AuthenticationType(enums::AuthenticationType), CaptureMethod(enums::CaptureMethod), PaymentType(enums::PaymentType), MandateAcceptanceType(enums::MandateAcceptanceType), MandateType(enums::MandateType), PaymentAmount(NumValue), PaymentCurrency(enums::Currency), #[cfg(feature = "payouts")] PayoutCurrency(enums::Currency), BusinessCountry(enums::Country), BillingCountry(enums::Country), BusinessLabel(StrValue), SetupFutureUsage(enums::SetupFutureUsage), IssuerName(StrValue), IssuerCountry(enums::Country), AcquirerCountry(enums::Country), AcquirerFraudRate(NumValue), CustomerDeviceType(CustomerDeviceType), CustomerDeviceDisplaySize(CustomerDeviceDisplaySize), CustomerDevicePlatform(CustomerDevicePlatform), } impl EuclidValue { pub fn get_num_value(&self) -> Option<NumValue> { match self { Self::PaymentAmount(val) => Some(val.clone()), _ => None, } } pub fn get_key(&self) -> EuclidKey { match self { Self::PaymentMethod(_) => EuclidKey::PaymentMethod, Self::CardBin(_) => EuclidKey::CardBin, Self::Metadata(_) => EuclidKey::Metadata, Self::PaymentMethodType(_) => EuclidKey::PaymentMethodType, Self::MandateType(_) => EuclidKey::MandateType, Self::PaymentType(_) => EuclidKey::PaymentType, Self::MandateAcceptanceType(_) => EuclidKey::MandateAcceptanceType, Self::CardNetwork(_) => EuclidKey::CardNetwork, Self::AuthenticationType(_) => EuclidKey::AuthenticationType, Self::CaptureMethod(_) => EuclidKey::CaptureMethod, Self::PaymentAmount(_) => EuclidKey::PaymentAmount, Self::PaymentCurrency(_) => EuclidKey::PaymentCurrency, #[cfg(feature = "payouts")] Self::PayoutCurrency(_) => EuclidKey::PayoutCurrency, Self::BusinessCountry(_) => EuclidKey::BusinessCountry, Self::BillingCountry(_) => EuclidKey::BillingCountry, Self::BusinessLabel(_) => EuclidKey::BusinessLabel, Self::SetupFutureUsage(_) => EuclidKey::SetupFutureUsage, Self::IssuerName(_) => EuclidKey::IssuerName, Self::IssuerCountry(_) => EuclidKey::IssuerCountry, Self::AcquirerCountry(_) => EuclidKey::AcquirerCountry, Self::AcquirerFraudRate(_) => EuclidKey::AcquirerFraudRate, Self::CustomerDeviceType(_) => EuclidKey::CustomerDeviceType, Self::CustomerDeviceDisplaySize(_) => EuclidKey::CustomerDeviceDisplaySize, Self::CustomerDevicePlatform(_) => EuclidKey::CustomerDevicePlatform, } } } #[cfg(test)] mod global_type_tests { use super::*; #[test] fn test_num_value_fits_greater_than() { let val1 = NumValue { number: MinorUnit::new(10), refinement: Some(NumValueRefinement::GreaterThan), }; let val2 = NumValue { number: MinorUnit::new(30), refinement: Some(NumValueRefinement::GreaterThan), }; assert!(val1.fits(&val2)) } #[test] fn test_num_value_fits_less_than() { let val1 = NumValue { number: MinorUnit::new(30), refinement: Some(NumValueRefinement::LessThan), }; let val2 = NumValue { number: MinorUnit::new(10), refinement: Some(NumValueRefinement::LessThan), }; assert!(val1.fits(&val2)); } }
crates/euclid/src/types.rs
euclid::src::types
2,946
true
// File: crates/euclid/src/backend.rs // Module: euclid::src::backend pub mod inputs; pub mod interpreter; #[cfg(feature = "valued_jit")] pub mod vir_interpreter; pub use inputs::BackendInput; pub use interpreter::InterpreterBackend; #[cfg(feature = "valued_jit")] pub use vir_interpreter::VirInterpreterBackend; use crate::frontend::ast; #[derive(Debug, Clone, serde::Serialize)] pub struct BackendOutput<O> { pub rule_name: Option<String>, pub connector_selection: O, } impl<O> BackendOutput<O> { // get_connector_selection pub fn get_output(&self) -> &O { &self.connector_selection } } pub trait EuclidBackend<O>: Sized { type Error: serde::Serialize; fn with_program(program: ast::Program<O>) -> Result<Self, Self::Error>; fn execute(&self, input: BackendInput) -> Result<BackendOutput<O>, Self::Error>; }
crates/euclid/src/backend.rs
euclid::src::backend
213
true
// File: crates/euclid/src/lib.rs // Module: euclid::src::lib #![allow(clippy::result_large_err)] pub mod backend; pub mod dssa; pub mod enums; pub mod frontend; pub mod types;
crates/euclid/src/lib.rs
euclid::src::lib
51
true
// File: crates/euclid/src/enums.rs // Module: euclid::src::enums pub use common_enums::{ AuthenticationType, CaptureMethod, CardNetwork, Country, CountryAlpha2, Currency, FutureUsage as SetupFutureUsage, PaymentMethod, PaymentMethodType, RoutableConnectors, }; use strum::VariantNames; pub trait CollectVariants { fn variants<T: FromIterator<String>>() -> T; } macro_rules! collect_variants { ($the_enum:ident) => { impl $crate::enums::CollectVariants for $the_enum { fn variants<T>() -> T where T: FromIterator<String>, { Self::VARIANTS.iter().map(|s| String::from(*s)).collect() } } }; } pub(crate) use collect_variants; collect_variants!(PaymentMethod); collect_variants!(RoutableConnectors); collect_variants!(PaymentType); collect_variants!(MandateType); collect_variants!(MandateAcceptanceType); collect_variants!(PaymentMethodType); collect_variants!(CardNetwork); collect_variants!(AuthenticationType); collect_variants!(CaptureMethod); collect_variants!(Currency); collect_variants!(Country); collect_variants!(SetupFutureUsage); #[cfg(feature = "payouts")] collect_variants!(PayoutType); #[cfg(feature = "payouts")] collect_variants!(PayoutBankTransferType); #[cfg(feature = "payouts")] collect_variants!(PayoutWalletType); #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateAcceptanceType { Online, Offline, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentType { SetupMandate, NonMandate, NewMandate, UpdateMandate, PptMandate, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateType { SingleUse, MultiUse, } #[cfg(feature = "payouts")] #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutBankTransferType { Ach, Bacs, SepaBankTransfer, } #[cfg(feature = "payouts")] #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutWalletType { Paypal, } #[cfg(feature = "payouts")] #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutType { Card, BankTransfer, Wallet, BankRedirect, }
crates/euclid/src/enums.rs
euclid::src::enums
930
true
// File: crates/euclid/src/dssa.rs // Module: euclid::src::dssa //! Domain Specific Static Analyzer pub mod analyzer; pub mod graph; pub mod state_machine; pub mod truth; pub mod types; pub mod utils;
crates/euclid/src/dssa.rs
euclid::src::dssa
54
true
// File: crates/euclid/src/types/transformers.rs // Module: euclid::src::types::transformers
crates/euclid/src/types/transformers.rs
euclid::src::types::transformers
27
true
// File: crates/euclid/src/frontend/vir.rs // Module: euclid::src::frontend::vir //! Valued Intermediate Representation use serde::{Deserialize, Serialize}; use crate::types::{EuclidValue, Metadata}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ValuedComparisonLogic { NegativeConjunction, PositiveDisjunction, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedComparison { pub values: Vec<EuclidValue>, pub logic: ValuedComparisonLogic, pub metadata: Metadata, } pub type ValuedIfCondition = Vec<ValuedComparison>; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedIfStatement { pub condition: ValuedIfCondition, pub nested: Option<Vec<ValuedIfStatement>>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedRule<O> { pub name: String, pub connector_selection: O, pub statements: Vec<ValuedIfStatement>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedProgram<O> { pub default_selection: O, pub rules: Vec<ValuedRule<O>>, pub metadata: Metadata, }
crates/euclid/src/frontend/vir.rs
euclid::src::frontend::vir
257
true
// File: crates/euclid/src/frontend/dir.rs // Module: euclid::src::frontend::dir //! Domain Intermediate Representation pub mod enums; pub mod lowering; pub mod transformers; use strum::IntoEnumIterator; // use common_utils::types::MinorUnit; use crate::{enums as euclid_enums, frontend::ast, types}; #[macro_export] macro_rules! dirval { (Connector = $name:ident) => { $crate::frontend::dir::DirValue::Connector(Box::new( $crate::frontend::ast::ConnectorChoice { connector: $crate::enums::RoutableConnectors::$name, }, )) }; ($key:ident = $val:ident) => {{ pub use $crate::frontend::dir::enums::*; $crate::frontend::dir::DirValue::$key($key::$val) }}; ($key:ident = $num:literal) => {{ $crate::frontend::dir::DirValue::$key($crate::types::NumValue { number: common_utils::types::MinorUnit::new($num), refinement: None, }) }}; ($key:ident s= $str:literal) => {{ $crate::frontend::dir::DirValue::$key($crate::types::StrValue { value: $str.to_string(), }) }}; ($key:literal = $str:literal) => {{ $crate::frontend::dir::DirValue::MetaData($crate::types::MetadataValue { key: $key.to_string(), value: $str.to_string(), }) }}; } #[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize)] pub struct DirKey { pub kind: DirKeyKind, pub value: Option<String>, } impl DirKey { pub fn new(kind: DirKeyKind, value: Option<String>) -> Self { Self { kind, value } } } #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::EnumIter, strum::VariantNames, strum::EnumString, strum::EnumMessage, strum::EnumProperty, )] pub enum DirKeyKind { #[strum( serialize = "payment_method", detailed_message = "Different modes of payment - eg. cards, wallets, banks", props(Category = "Payment Methods") )] #[serde(rename = "payment_method")] PaymentMethod, #[strum( serialize = "card_bin", detailed_message = "First 4 to 6 digits of a payment card number", props(Category = "Payment Methods") )] #[serde(rename = "card_bin")] CardBin, #[strum( serialize = "card_type", detailed_message = "Type of the payment card - eg. credit, debit", props(Category = "Payment Methods") )] #[serde(rename = "card_type")] CardType, #[strum( serialize = "card_network", detailed_message = "Network that facilitates payment card transactions", props(Category = "Payment Methods") )] #[serde(rename = "card_network")] CardNetwork, #[strum( serialize = "pay_later", detailed_message = "Supported types of Pay Later payment method", props(Category = "Payment Method Types") )] #[serde(rename = "pay_later")] PayLaterType, #[strum( serialize = "gift_card", detailed_message = "Supported types of Gift Card payment method", props(Category = "Payment Method Types") )] #[serde(rename = "gift_card")] GiftCardType, #[strum( serialize = "mandate_acceptance_type", detailed_message = "Mode of customer acceptance for mandates - online and offline", props(Category = "Payments") )] #[serde(rename = "mandate_acceptance_type")] MandateAcceptanceType, #[strum( serialize = "mandate_type", detailed_message = "Type of mandate acceptance - single use and multi use", props(Category = "Payments") )] #[serde(rename = "mandate_type")] MandateType, #[strum( serialize = "payment_type", detailed_message = "Indicates if a payment is mandate or non-mandate", props(Category = "Payments") )] #[serde(rename = "payment_type")] PaymentType, #[strum( serialize = "wallet", detailed_message = "Supported types of Wallet payment method", props(Category = "Payment Method Types") )] #[serde(rename = "wallet")] WalletType, #[strum( serialize = "upi", detailed_message = "Supported types of UPI payment method", props(Category = "Payment Method Types") )] #[serde(rename = "upi")] UpiType, #[strum( serialize = "voucher", detailed_message = "Supported types of Voucher payment method", props(Category = "Payment Method Types") )] #[serde(rename = "voucher")] VoucherType, #[strum( serialize = "bank_transfer", detailed_message = "Supported types of Bank Transfer payment method", props(Category = "Payment Method Types") )] #[serde(rename = "bank_transfer")] BankTransferType, #[strum( serialize = "bank_redirect", detailed_message = "Supported types of Bank Redirect payment methods", props(Category = "Payment Method Types") )] #[serde(rename = "bank_redirect")] BankRedirectType, #[strum( serialize = "bank_debit", detailed_message = "Supported types of Bank Debit payment method", props(Category = "Payment Method Types") )] #[serde(rename = "bank_debit")] BankDebitType, #[strum( serialize = "crypto", detailed_message = "Supported types of Crypto payment method", props(Category = "Payment Method Types") )] #[serde(rename = "crypto")] CryptoType, #[strum( serialize = "metadata", detailed_message = "Aribitrary Key and value pair", props(Category = "Metadata") )] #[serde(rename = "metadata")] MetaData, #[strum( serialize = "reward", detailed_message = "Supported types of Reward payment method", props(Category = "Payment Method Types") )] #[serde(rename = "reward")] RewardType, #[strum( serialize = "amount", detailed_message = "Value of the transaction", props(Category = "Payments") )] #[serde(rename = "amount")] PaymentAmount, #[strum( serialize = "currency", detailed_message = "Currency used for the payment", props(Category = "Payments") )] #[serde(rename = "currency")] PaymentCurrency, #[strum( serialize = "authentication_type", detailed_message = "Type of authentication for the payment", props(Category = "Payments") )] #[serde(rename = "authentication_type")] AuthenticationType, #[strum( serialize = "capture_method", detailed_message = "Modes of capturing a payment", props(Category = "Payments") )] #[serde(rename = "capture_method")] CaptureMethod, #[strum( serialize = "country", serialize = "business_country", detailed_message = "Country of the business unit", props(Category = "Merchant") )] #[serde(rename = "business_country", alias = "country")] BusinessCountry, #[strum( serialize = "billing_country", detailed_message = "Country of the billing address of the customer", props(Category = "Customer") )] #[serde(rename = "billing_country")] BillingCountry, #[serde(skip_deserializing, rename = "connector")] Connector, #[strum( serialize = "business_label", detailed_message = "Identifier for business unit", props(Category = "Merchant") )] #[serde(rename = "business_label")] BusinessLabel, #[strum( serialize = "setup_future_usage", detailed_message = "Identifier for recurring payments", props(Category = "Payments") )] #[serde(rename = "setup_future_usage")] SetupFutureUsage, #[strum( serialize = "card_redirect", detailed_message = "Supported types of Card Redirect payment method", props(Category = "Payment Method Types") )] #[serde(rename = "card_redirect")] CardRedirectType, #[serde(rename = "real_time_payment")] #[strum( serialize = "real_time_payment", detailed_message = "Supported types of real time payment method", props(Category = "Payment Method Types") )] RealTimePaymentType, #[serde(rename = "open_banking")] #[strum( serialize = "open_banking", detailed_message = "Supported types of open banking payment method", props(Category = "Payment Method Types") )] OpenBankingType, #[serde(rename = "mobile_payment")] #[strum( serialize = "mobile_payment", detailed_message = "Supported types of mobile payment method", props(Category = "Payment Method Types") )] MobilePaymentType, #[strum( serialize = "issuer_name", detailed_message = "Name of the card issuing bank", props(Category = "3DS Decision") )] #[serde(rename = "issuer_name")] IssuerName, #[strum( serialize = "issuer_country", detailed_message = "Country of the card issuing bank", props(Category = "3DS Decision") )] #[serde(rename = "issuer_country")] IssuerCountry, #[strum( serialize = "customer_device_platform", detailed_message = "Platform of the customer's device (Web, Android, iOS)", props(Category = "3DS Decision") )] #[serde(rename = "customer_device_platform")] CustomerDevicePlatform, #[strum( serialize = "customer_device_type", detailed_message = "Type of the customer's device (Mobile, Tablet, Desktop, Gaming Console)", props(Category = "3DS Decision") )] #[serde(rename = "customer_device_type")] CustomerDeviceType, #[strum( serialize = "customer_device_display_size", detailed_message = "Display size of the customer's device (e.g., 500x600)", props(Category = "3DS Decision") )] #[serde(rename = "customer_device_display_size")] CustomerDeviceDisplaySize, #[strum( serialize = "acquirer_country", detailed_message = "Country of the acquiring bank", props(Category = "3DS Decision") )] #[serde(rename = "acquirer_country")] AcquirerCountry, #[strum( serialize = "acquirer_fraud_rate", detailed_message = "Fraud rate of the acquiring bank", props(Category = "3DS Decision") )] #[serde(rename = "acquirer_fraud_rate")] AcquirerFraudRate, } pub trait EuclidDirFilter: Sized where Self: 'static, { const ALLOWED: &'static [DirKeyKind]; fn get_allowed_keys() -> &'static [DirKeyKind] { Self::ALLOWED } fn is_key_allowed(key: &DirKeyKind) -> bool { Self::ALLOWED.contains(key) } } impl DirKeyKind { pub fn get_type(&self) -> types::DataType { match self { Self::PaymentMethod => types::DataType::EnumVariant, Self::CardBin => types::DataType::StrValue, Self::CardType => types::DataType::EnumVariant, Self::CardNetwork => types::DataType::EnumVariant, Self::MetaData => types::DataType::MetadataValue, Self::MandateType => types::DataType::EnumVariant, Self::PaymentType => types::DataType::EnumVariant, Self::MandateAcceptanceType => types::DataType::EnumVariant, Self::PayLaterType => types::DataType::EnumVariant, Self::WalletType => types::DataType::EnumVariant, Self::UpiType => types::DataType::EnumVariant, Self::VoucherType => types::DataType::EnumVariant, Self::BankTransferType => types::DataType::EnumVariant, Self::GiftCardType => types::DataType::EnumVariant, Self::BankRedirectType => types::DataType::EnumVariant, Self::CryptoType => types::DataType::EnumVariant, Self::RewardType => types::DataType::EnumVariant, Self::PaymentAmount => types::DataType::Number, Self::PaymentCurrency => types::DataType::EnumVariant, Self::AuthenticationType => types::DataType::EnumVariant, Self::CaptureMethod => types::DataType::EnumVariant, Self::BusinessCountry => types::DataType::EnumVariant, Self::BillingCountry => types::DataType::EnumVariant, Self::Connector => types::DataType::EnumVariant, Self::BankDebitType => types::DataType::EnumVariant, Self::BusinessLabel => types::DataType::StrValue, Self::SetupFutureUsage => types::DataType::EnumVariant, Self::CardRedirectType => types::DataType::EnumVariant, Self::RealTimePaymentType => types::DataType::EnumVariant, Self::OpenBankingType => types::DataType::EnumVariant, Self::MobilePaymentType => types::DataType::EnumVariant, Self::IssuerName => types::DataType::StrValue, Self::IssuerCountry => types::DataType::EnumVariant, Self::CustomerDevicePlatform => types::DataType::EnumVariant, Self::CustomerDeviceType => types::DataType::EnumVariant, Self::CustomerDeviceDisplaySize => types::DataType::EnumVariant, Self::AcquirerCountry => types::DataType::EnumVariant, Self::AcquirerFraudRate => types::DataType::Number, } } pub fn get_value_set(&self) -> Option<Vec<DirValue>> { match self { Self::PaymentMethod => Some( enums::PaymentMethod::iter() .map(DirValue::PaymentMethod) .collect(), ), Self::CardBin => None, Self::CardType => Some(enums::CardType::iter().map(DirValue::CardType).collect()), Self::MandateAcceptanceType => Some( euclid_enums::MandateAcceptanceType::iter() .map(DirValue::MandateAcceptanceType) .collect(), ), Self::PaymentType => Some( euclid_enums::PaymentType::iter() .map(DirValue::PaymentType) .collect(), ), Self::MandateType => Some( euclid_enums::MandateType::iter() .map(DirValue::MandateType) .collect(), ), Self::CardNetwork => Some( enums::CardNetwork::iter() .map(DirValue::CardNetwork) .collect(), ), Self::PayLaterType => Some( enums::PayLaterType::iter() .map(DirValue::PayLaterType) .collect(), ), Self::MetaData => None, Self::WalletType => Some( enums::WalletType::iter() .map(DirValue::WalletType) .collect(), ), Self::UpiType => Some(enums::UpiType::iter().map(DirValue::UpiType).collect()), Self::VoucherType => Some( enums::VoucherType::iter() .map(DirValue::VoucherType) .collect(), ), Self::BankTransferType => Some( enums::BankTransferType::iter() .map(DirValue::BankTransferType) .collect(), ), Self::GiftCardType => Some( enums::GiftCardType::iter() .map(DirValue::GiftCardType) .collect(), ), Self::BankRedirectType => Some( enums::BankRedirectType::iter() .map(DirValue::BankRedirectType) .collect(), ), Self::CryptoType => Some( enums::CryptoType::iter() .map(DirValue::CryptoType) .collect(), ), Self::RewardType => Some( enums::RewardType::iter() .map(DirValue::RewardType) .collect(), ), Self::PaymentAmount => None, Self::PaymentCurrency => Some( enums::PaymentCurrency::iter() .map(DirValue::PaymentCurrency) .collect(), ), Self::AuthenticationType => Some( enums::AuthenticationType::iter() .map(DirValue::AuthenticationType) .collect(), ), Self::CaptureMethod => Some( enums::CaptureMethod::iter() .map(DirValue::CaptureMethod) .collect(), ), Self::BankDebitType => Some( enums::BankDebitType::iter() .map(DirValue::BankDebitType) .collect(), ), Self::BusinessCountry => Some( enums::Country::iter() .map(DirValue::BusinessCountry) .collect(), ), Self::BillingCountry => Some( enums::Country::iter() .map(DirValue::BillingCountry) .collect(), ), Self::Connector => Some( common_enums::RoutableConnectors::iter() .map(|connector| { DirValue::Connector(Box::new(ast::ConnectorChoice { connector })) }) .collect(), ), Self::BusinessLabel => None, Self::SetupFutureUsage => Some( enums::SetupFutureUsage::iter() .map(DirValue::SetupFutureUsage) .collect(), ), Self::CardRedirectType => Some( enums::CardRedirectType::iter() .map(DirValue::CardRedirectType) .collect(), ), Self::RealTimePaymentType => Some( enums::RealTimePaymentType::iter() .map(DirValue::RealTimePaymentType) .collect(), ), Self::OpenBankingType => Some( enums::OpenBankingType::iter() .map(DirValue::OpenBankingType) .collect(), ), Self::MobilePaymentType => Some( enums::MobilePaymentType::iter() .map(DirValue::MobilePaymentType) .collect(), ), Self::IssuerName => None, Self::IssuerCountry => Some( enums::Country::iter() .map(DirValue::IssuerCountry) .collect(), ), Self::CustomerDevicePlatform => Some( enums::CustomerDevicePlatform::iter() .map(DirValue::CustomerDevicePlatform) .collect(), ), Self::CustomerDeviceType => Some( enums::CustomerDeviceType::iter() .map(DirValue::CustomerDeviceType) .collect(), ), Self::CustomerDeviceDisplaySize => Some( enums::CustomerDeviceDisplaySize::iter() .map(DirValue::CustomerDeviceDisplaySize) .collect(), ), Self::AcquirerCountry => Some( enums::Country::iter() .map(DirValue::AcquirerCountry) .collect(), ), Self::AcquirerFraudRate => None, } } } #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::VariantNames, )] #[serde(tag = "key", content = "value")] pub enum DirValue { #[serde(rename = "payment_method")] PaymentMethod(enums::PaymentMethod), #[serde(rename = "card_bin")] CardBin(types::StrValue), #[serde(rename = "card_type")] CardType(enums::CardType), #[serde(rename = "card_network")] CardNetwork(enums::CardNetwork), #[serde(rename = "metadata")] MetaData(types::MetadataValue), #[serde(rename = "pay_later")] PayLaterType(enums::PayLaterType), #[serde(rename = "wallet")] WalletType(enums::WalletType), #[serde(rename = "acceptance_type")] MandateAcceptanceType(euclid_enums::MandateAcceptanceType), #[serde(rename = "mandate_type")] MandateType(euclid_enums::MandateType), #[serde(rename = "payment_type")] PaymentType(euclid_enums::PaymentType), #[serde(rename = "upi")] UpiType(enums::UpiType), #[serde(rename = "voucher")] VoucherType(enums::VoucherType), #[serde(rename = "bank_transfer")] BankTransferType(enums::BankTransferType), #[serde(rename = "bank_redirect")] BankRedirectType(enums::BankRedirectType), #[serde(rename = "bank_debit")] BankDebitType(enums::BankDebitType), #[serde(rename = "crypto")] CryptoType(enums::CryptoType), #[serde(rename = "reward")] RewardType(enums::RewardType), #[serde(rename = "gift_card")] GiftCardType(enums::GiftCardType), #[serde(rename = "amount")] PaymentAmount(types::NumValue), #[serde(rename = "currency")] PaymentCurrency(enums::PaymentCurrency), #[serde(rename = "authentication_type")] AuthenticationType(enums::AuthenticationType), #[serde(rename = "capture_method")] CaptureMethod(enums::CaptureMethod), #[serde(rename = "business_country", alias = "country")] BusinessCountry(enums::Country), #[serde(rename = "billing_country")] BillingCountry(enums::Country), #[serde(skip_deserializing, rename = "connector")] Connector(Box<ast::ConnectorChoice>), #[serde(rename = "business_label")] BusinessLabel(types::StrValue), #[serde(rename = "setup_future_usage")] SetupFutureUsage(enums::SetupFutureUsage), #[serde(rename = "card_redirect")] CardRedirectType(enums::CardRedirectType), #[serde(rename = "real_time_payment")] RealTimePaymentType(enums::RealTimePaymentType), #[serde(rename = "open_banking")] OpenBankingType(enums::OpenBankingType), #[serde(rename = "mobile_payment")] MobilePaymentType(enums::MobilePaymentType), #[serde(rename = "issuer_name")] IssuerName(types::StrValue), #[serde(rename = "issuer_country")] IssuerCountry(enums::Country), #[serde(rename = "customer_device_platform")] CustomerDevicePlatform(enums::CustomerDevicePlatform), #[serde(rename = "customer_device_type")] CustomerDeviceType(enums::CustomerDeviceType), #[serde(rename = "customer_device_display_size")] CustomerDeviceDisplaySize(enums::CustomerDeviceDisplaySize), #[serde(rename = "acquirer_country")] AcquirerCountry(enums::Country), #[serde(rename = "acquirer_fraud_rate")] AcquirerFraudRate(types::NumValue), } impl DirValue { pub fn get_key(&self) -> DirKey { let (kind, data) = match self { Self::PaymentMethod(_) => (DirKeyKind::PaymentMethod, None), Self::CardBin(_) => (DirKeyKind::CardBin, None), Self::RewardType(_) => (DirKeyKind::RewardType, None), Self::BusinessCountry(_) => (DirKeyKind::BusinessCountry, None), Self::BillingCountry(_) => (DirKeyKind::BillingCountry, None), Self::BankTransferType(_) => (DirKeyKind::BankTransferType, None), Self::UpiType(_) => (DirKeyKind::UpiType, None), Self::CardType(_) => (DirKeyKind::CardType, None), Self::CardNetwork(_) => (DirKeyKind::CardNetwork, None), Self::MetaData(met) => (DirKeyKind::MetaData, Some(met.key.clone())), Self::PayLaterType(_) => (DirKeyKind::PayLaterType, None), Self::WalletType(_) => (DirKeyKind::WalletType, None), Self::BankRedirectType(_) => (DirKeyKind::BankRedirectType, None), Self::CryptoType(_) => (DirKeyKind::CryptoType, None), Self::AuthenticationType(_) => (DirKeyKind::AuthenticationType, None), Self::CaptureMethod(_) => (DirKeyKind::CaptureMethod, None), Self::PaymentAmount(_) => (DirKeyKind::PaymentAmount, None), Self::PaymentCurrency(_) => (DirKeyKind::PaymentCurrency, None), Self::Connector(_) => (DirKeyKind::Connector, None), Self::BankDebitType(_) => (DirKeyKind::BankDebitType, None), Self::MandateAcceptanceType(_) => (DirKeyKind::MandateAcceptanceType, None), Self::MandateType(_) => (DirKeyKind::MandateType, None), Self::PaymentType(_) => (DirKeyKind::PaymentType, None), Self::BusinessLabel(_) => (DirKeyKind::BusinessLabel, None), Self::SetupFutureUsage(_) => (DirKeyKind::SetupFutureUsage, None), Self::CardRedirectType(_) => (DirKeyKind::CardRedirectType, None), Self::VoucherType(_) => (DirKeyKind::VoucherType, None), Self::GiftCardType(_) => (DirKeyKind::GiftCardType, None), Self::RealTimePaymentType(_) => (DirKeyKind::RealTimePaymentType, None), Self::OpenBankingType(_) => (DirKeyKind::OpenBankingType, None), Self::MobilePaymentType(_) => (DirKeyKind::MobilePaymentType, None), Self::IssuerName(_) => (DirKeyKind::IssuerName, None), Self::IssuerCountry(_) => (DirKeyKind::IssuerCountry, None), Self::CustomerDevicePlatform(_) => (DirKeyKind::CustomerDevicePlatform, None), Self::CustomerDeviceType(_) => (DirKeyKind::CustomerDeviceType, None), Self::CustomerDeviceDisplaySize(_) => (DirKeyKind::CustomerDeviceDisplaySize, None), Self::AcquirerCountry(_) => (DirKeyKind::AcquirerCountry, None), Self::AcquirerFraudRate(_) => (DirKeyKind::AcquirerFraudRate, None), }; DirKey::new(kind, data) } pub fn get_metadata_val(&self) -> Option<types::MetadataValue> { match self { Self::MetaData(val) => Some(val.clone()), Self::PaymentMethod(_) => None, Self::CardBin(_) => None, Self::CardType(_) => None, Self::CardNetwork(_) => None, Self::PayLaterType(_) => None, Self::WalletType(_) => None, Self::BankRedirectType(_) => None, Self::CryptoType(_) => None, Self::AuthenticationType(_) => None, Self::CaptureMethod(_) => None, Self::GiftCardType(_) => None, Self::PaymentAmount(_) => None, Self::PaymentCurrency(_) => None, Self::BusinessCountry(_) => None, Self::BillingCountry(_) => None, Self::Connector(_) => None, Self::BankTransferType(_) => None, Self::UpiType(_) => None, Self::BankDebitType(_) => None, Self::RewardType(_) => None, Self::VoucherType(_) => None, Self::MandateAcceptanceType(_) => None, Self::MandateType(_) => None, Self::PaymentType(_) => None, Self::BusinessLabel(_) => None, Self::SetupFutureUsage(_) => None, Self::CardRedirectType(_) => None, Self::RealTimePaymentType(_) => None, Self::OpenBankingType(_) => None, Self::MobilePaymentType(_) => None, Self::IssuerName(_) => None, Self::IssuerCountry(_) => None, Self::CustomerDevicePlatform(_) => None, Self::CustomerDeviceType(_) => None, Self::CustomerDeviceDisplaySize(_) => None, Self::AcquirerCountry(_) => None, Self::AcquirerFraudRate(_) => None, } } pub fn get_str_val(&self) -> Option<types::StrValue> { match self { Self::CardBin(val) => Some(val.clone()), Self::IssuerName(val) => Some(val.clone()), _ => None, } } pub fn get_num_value(&self) -> Option<types::NumValue> { match self { Self::PaymentAmount(val) => Some(val.clone()), Self::AcquirerFraudRate(val) => Some(val.clone()), _ => None, } } pub fn check_equality(v1: &Self, v2: &Self) -> bool { match (v1, v2) { (Self::PaymentMethod(pm1), Self::PaymentMethod(pm2)) => pm1 == pm2, (Self::CardType(ct1), Self::CardType(ct2)) => ct1 == ct2, (Self::CardNetwork(cn1), Self::CardNetwork(cn2)) => cn1 == cn2, (Self::MetaData(md1), Self::MetaData(md2)) => md1 == md2, (Self::PayLaterType(plt1), Self::PayLaterType(plt2)) => plt1 == plt2, (Self::WalletType(wt1), Self::WalletType(wt2)) => wt1 == wt2, (Self::BankDebitType(bdt1), Self::BankDebitType(bdt2)) => bdt1 == bdt2, (Self::BankRedirectType(brt1), Self::BankRedirectType(brt2)) => brt1 == brt2, (Self::BankTransferType(btt1), Self::BankTransferType(btt2)) => btt1 == btt2, (Self::GiftCardType(gct1), Self::GiftCardType(gct2)) => gct1 == gct2, (Self::CryptoType(ct1), Self::CryptoType(ct2)) => ct1 == ct2, (Self::AuthenticationType(at1), Self::AuthenticationType(at2)) => at1 == at2, (Self::CaptureMethod(cm1), Self::CaptureMethod(cm2)) => cm1 == cm2, (Self::PaymentCurrency(pc1), Self::PaymentCurrency(pc2)) => pc1 == pc2, (Self::BusinessCountry(c1), Self::BusinessCountry(c2)) => c1 == c2, (Self::BillingCountry(c1), Self::BillingCountry(c2)) => c1 == c2, (Self::PaymentType(pt1), Self::PaymentType(pt2)) => pt1 == pt2, (Self::MandateType(mt1), Self::MandateType(mt2)) => mt1 == mt2, (Self::MandateAcceptanceType(mat1), Self::MandateAcceptanceType(mat2)) => mat1 == mat2, (Self::RewardType(rt1), Self::RewardType(rt2)) => rt1 == rt2, (Self::RealTimePaymentType(rtp1), Self::RealTimePaymentType(rtp2)) => rtp1 == rtp2, (Self::Connector(c1), Self::Connector(c2)) => c1 == c2, (Self::BusinessLabel(bl1), Self::BusinessLabel(bl2)) => bl1 == bl2, (Self::SetupFutureUsage(sfu1), Self::SetupFutureUsage(sfu2)) => sfu1 == sfu2, (Self::UpiType(ut1), Self::UpiType(ut2)) => ut1 == ut2, (Self::VoucherType(vt1), Self::VoucherType(vt2)) => vt1 == vt2, (Self::CardRedirectType(crt1), Self::CardRedirectType(crt2)) => crt1 == crt2, (Self::IssuerName(n1), Self::IssuerName(n2)) => n1 == n2, (Self::IssuerCountry(c1), Self::IssuerCountry(c2)) => c1 == c2, (Self::CustomerDevicePlatform(p1), Self::CustomerDevicePlatform(p2)) => p1 == p2, (Self::CustomerDeviceType(t1), Self::CustomerDeviceType(t2)) => t1 == t2, (Self::CustomerDeviceDisplaySize(s1), Self::CustomerDeviceDisplaySize(s2)) => s1 == s2, (Self::AcquirerCountry(c1), Self::AcquirerCountry(c2)) => c1 == c2, (Self::AcquirerFraudRate(r1), Self::AcquirerFraudRate(r2)) => r1 == r2, _ => false, } } } #[cfg(feature = "payouts")] #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::EnumIter, strum::VariantNames, strum::EnumString, strum::EnumMessage, strum::EnumProperty, )] pub enum PayoutDirKeyKind { #[strum( serialize = "country", serialize = "business_country", detailed_message = "Country of the business unit", props(Category = "Merchant") )] #[serde(rename = "business_country", alias = "country")] BusinessCountry, #[strum( serialize = "billing_country", detailed_message = "Country of the billing address of the customer", props(Category = "Customer") )] #[serde(rename = "billing_country")] BillingCountry, #[strum( serialize = "business_label", detailed_message = "Identifier for business unit", props(Category = "Merchant") )] #[serde(rename = "business_label")] BusinessLabel, #[strum( serialize = "amount", detailed_message = "Value of the transaction", props(Category = "Order details") )] #[serde(rename = "amount")] PayoutAmount, #[strum( serialize = "currency", detailed_message = "Currency used for the payout", props(Category = "Order details") )] #[serde(rename = "currency")] PayoutCurrency, #[strum( serialize = "payment_method", detailed_message = "Different modes of payout - eg. cards, wallets, banks", props(Category = "Payout Methods") )] #[serde(rename = "payment_method")] PayoutType, #[strum( serialize = "wallet", detailed_message = "Supported types of Wallets for payouts", props(Category = "Payout Methods Type") )] #[serde(rename = "wallet")] WalletType, #[strum( serialize = "bank_transfer", detailed_message = "Supported types of Bank transfer types for payouts", props(Category = "Payout Methods Type") )] #[serde(rename = "bank_transfer")] BankTransferType, } #[cfg(feature = "payouts")] #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::VariantNames, )] pub enum PayoutDirValue { #[serde(rename = "business_country", alias = "country")] BusinessCountry(enums::Country), #[serde(rename = "billing_country")] BillingCountry(enums::Country), #[serde(rename = "business_label")] BusinessLabel(types::StrValue), #[serde(rename = "amount")] PayoutAmount(types::NumValue), #[serde(rename = "currency")] PayoutCurrency(enums::PaymentCurrency), #[serde(rename = "payment_method")] PayoutType(common_enums::PayoutType), #[serde(rename = "wallet")] WalletType(enums::PayoutWalletType), #[serde(rename = "bank_transfer")] BankTransferType(enums::PayoutBankTransferType), } #[derive(Debug, Clone)] pub enum DirComparisonLogic { NegativeConjunction, PositiveDisjunction, } #[derive(Debug, Clone)] pub struct DirComparison { pub values: Vec<DirValue>, pub logic: DirComparisonLogic, pub metadata: types::Metadata, } pub type DirIfCondition = Vec<DirComparison>; #[derive(Debug, Clone)] pub struct DirIfStatement { pub condition: DirIfCondition, pub nested: Option<Vec<DirIfStatement>>, } #[derive(Debug, Clone)] pub struct DirRule<O> { pub name: String, pub connector_selection: O, pub statements: Vec<DirIfStatement>, } #[derive(Debug, Clone)] pub struct DirProgram<O> { pub default_selection: O, pub rules: Vec<DirRule<O>>, pub metadata: types::Metadata, } #[cfg(test)] mod test { #![allow(clippy::expect_used)] use rustc_hash::FxHashMap; use strum::IntoEnumIterator; use super::*; #[test] fn test_consistent_dir_key_naming() { let mut key_names: FxHashMap<DirKeyKind, String> = FxHashMap::default(); for key in DirKeyKind::iter() { if matches!(key, DirKeyKind::Connector) { continue; } let json_str = if let DirKeyKind::MetaData = key { r#""metadata""#.to_string() } else { serde_json::to_string(&key).expect("JSON Serialization") }; let display_str = key.to_string(); assert_eq!( json_str.get(1..json_str.len() - 1).expect("Value metadata"), display_str ); key_names.insert(key, display_str); } let values = vec![ dirval!(PaymentMethod = Card), dirval!(CardBin s= "123456"), dirval!(CardType = Credit), dirval!(CardNetwork = Visa), dirval!(PayLaterType = Klarna), dirval!(WalletType = Paypal), dirval!(BankRedirectType = Sofort), dirval!(BankDebitType = Bacs), dirval!(CryptoType = CryptoCurrency), dirval!("" = "metadata"), dirval!(PaymentAmount = 100), dirval!(PaymentCurrency = USD), dirval!(CardRedirectType = Benefit), dirval!(AuthenticationType = ThreeDs), dirval!(CaptureMethod = Manual), dirval!(BillingCountry = UnitedStatesOfAmerica), dirval!(BusinessCountry = France), ]; for val in values { let json_val = serde_json::to_value(&val).expect("JSON Value Serialization"); let json_key = json_val .as_object() .expect("Serialized Object") .get("key") .expect("Object Key"); let value_str = json_key.as_str().expect("Value string"); let dir_key = val.get_key(); let key_name = key_names.get(&dir_key.kind).expect("Key name"); assert_eq!(key_name, value_str); } } #[cfg(feature = "ast_parser")] #[test] fn test_allowed_dir_keys() { use crate::types::DummyOutput; let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { payment_method = card } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let out = ast::lowering::lower_program::<DummyOutput>(program); assert!(out.is_ok()) } #[cfg(feature = "ast_parser")] #[test] fn test_not_allowed_dir_keys() { use crate::types::DummyOutput; let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { bank_debit = ach } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let out = ast::lowering::lower_program::<DummyOutput>(program); assert!(out.is_err()) } }
crates/euclid/src/frontend/dir.rs
euclid::src::frontend::dir
8,744
true
// File: crates/euclid/src/frontend/ast.rs // Module: euclid::src::frontend::ast pub mod lowering; #[cfg(feature = "ast_parser")] pub mod parser; use common_enums::RoutableConnectors; use common_utils::types::MinorUnit; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::types::{DataType, Metadata}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct ConnectorChoice { pub connector: RoutableConnectors, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] pub struct MetadataValue { pub key: String, pub value: String, } /// Represents a value in the DSL #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum ValueType { /// Represents a number literal Number(MinorUnit), /// Represents an enum variant EnumVariant(String), /// Represents a Metadata variant MetadataVariant(MetadataValue), /// Represents a arbitrary String value StrValue(String), /// Represents an array of numbers. This is basically used for /// "one of the given numbers" operations /// eg: payment.method.amount = (1, 2, 3) NumberArray(Vec<MinorUnit>), /// Similar to NumberArray but for enum variants /// eg: payment.method.cardtype = (debit, credit) EnumVariantArray(Vec<String>), /// Like a number array but can include comparisons. Useful for /// conditions like "500 < amount < 1000" /// eg: payment.amount = (> 500, < 1000) NumberComparisonArray(Vec<NumberComparison>), } impl ValueType { pub fn get_type(&self) -> DataType { match self { Self::Number(_) => DataType::Number, Self::StrValue(_) => DataType::StrValue, Self::MetadataVariant(_) => DataType::MetadataValue, Self::EnumVariant(_) => DataType::EnumVariant, Self::NumberComparisonArray(_) => DataType::Number, Self::NumberArray(_) => DataType::Number, Self::EnumVariantArray(_) => DataType::EnumVariant, } } } /// Represents a number comparison for "NumberComparisonArrayValue" #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct NumberComparison { pub comparison_type: ComparisonType, pub number: MinorUnit, } /// Conditional comparison type #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ComparisonType { Equal, NotEqual, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, } /// Represents a single comparison condition. #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct Comparison { /// The left hand side which will always be a domain input identifier like "payment.method.cardtype" pub lhs: String, /// The comparison operator pub comparison: ComparisonType, /// The value to compare against pub value: ValueType, /// Additional metadata that the Static Analyzer and Backend does not touch. /// This can be used to store useful information for the frontend and is required for communication /// between the static analyzer and the frontend. #[schema(value_type=HashMap<String, serde_json::Value>)] pub metadata: Metadata, } /// Represents all the conditions of an IF statement /// eg: /// /// ```text /// payment.method = card & payment.method.cardtype = debit & payment.method.network = diners /// ``` pub type IfCondition = Vec<Comparison>; /// Represents an IF statement with conditions and optional nested IF statements /// /// ```text /// payment.method = card { /// payment.method.cardtype = (credit, debit) { /// payment.method.network = (amex, rupay, diners) /// } /// } /// ``` #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct IfStatement { #[schema(value_type=Vec<Comparison>)] pub condition: IfCondition, pub nested: Option<Vec<IfStatement>>, } /// Represents a rule /// /// ```text /// rule_name: [stripe, adyen, checkout] /// { /// payment.method = card { /// payment.method.cardtype = (credit, debit) { /// payment.method.network = (amex, rupay, diners) /// } /// /// payment.method.cardtype = credit /// } /// } /// ``` #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] #[aliases(RuleConnectorSelection = Rule<ConnectorSelection>)] pub struct Rule<O> { pub name: String, #[serde(alias = "routingOutput")] pub connector_selection: O, pub statements: Vec<IfStatement>, } /// The program, having a default connector selection and /// a bunch of rules. Also can hold arbitrary metadata. #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] #[aliases(ProgramConnectorSelection = Program<ConnectorSelection>)] pub struct Program<O> { pub default_selection: O, #[schema(value_type=RuleConnectorSelection)] pub rules: Vec<Rule<O>>, #[schema(value_type=HashMap<String, serde_json::Value>)] pub metadata: Metadata, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct RoutableConnectorChoice { #[serde(skip)] pub choice_kind: RoutableChoiceKind, pub connector: RoutableConnectors, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub enum RoutableChoiceKind { OnlyConnector, #[default] FullStruct, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ConnectorVolumeSplit { pub connector: RoutableConnectorChoice, pub split: u8, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum ConnectorSelection { Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), }
crates/euclid/src/frontend/ast.rs
euclid::src::frontend::ast
1,391
true
// File: crates/euclid/src/frontend/dir/lowering.rs // Module: euclid::src::frontend::dir::lowering //! Analysis of the lowering logic for the DIR //! //! Consists of certain functions that supports the lowering logic from DIR to VIR. //! These includes the lowering of the DIR program and vector of rules , and the lowering of ifstatements //! ,and comparisonsLogic and also the lowering of the enums of value variants from DIR to VIR. use super::enums; use crate::{ dssa::types::{AnalysisError, AnalysisErrorType}, enums as global_enums, frontend::{dir, vir}, types::EuclidValue, }; impl From<enums::CardType> for global_enums::PaymentMethodType { fn from(value: enums::CardType) -> Self { match value { enums::CardType::Credit => Self::Credit, enums::CardType::Debit => Self::Debit, #[cfg(feature = "v2")] enums::CardType::Card => Self::Card, } } } impl From<enums::PayLaterType> for global_enums::PaymentMethodType { fn from(value: enums::PayLaterType) -> Self { match value { enums::PayLaterType::Affirm => Self::Affirm, enums::PayLaterType::AfterpayClearpay => Self::AfterpayClearpay, enums::PayLaterType::Alma => Self::Alma, enums::PayLaterType::Flexiti => Self::Flexiti, enums::PayLaterType::Klarna => Self::Klarna, enums::PayLaterType::PayBright => Self::PayBright, enums::PayLaterType::Walley => Self::Walley, enums::PayLaterType::Atome => Self::Atome, enums::PayLaterType::Breadpay => Self::Breadpay, } } } impl From<enums::WalletType> for global_enums::PaymentMethodType { fn from(value: enums::WalletType) -> Self { match value { enums::WalletType::Bluecode => Self::Bluecode, enums::WalletType::GooglePay => Self::GooglePay, enums::WalletType::AmazonPay => Self::AmazonPay, enums::WalletType::Skrill => Self::Skrill, enums::WalletType::Paysera => Self::Paysera, enums::WalletType::ApplePay => Self::ApplePay, enums::WalletType::Paypal => Self::Paypal, enums::WalletType::AliPay => Self::AliPay, enums::WalletType::AliPayHk => Self::AliPayHk, enums::WalletType::MbWay => Self::MbWay, enums::WalletType::MobilePay => Self::MobilePay, enums::WalletType::WeChatPay => Self::WeChatPay, enums::WalletType::SamsungPay => Self::SamsungPay, enums::WalletType::GoPay => Self::GoPay, enums::WalletType::KakaoPay => Self::KakaoPay, enums::WalletType::Twint => Self::Twint, enums::WalletType::Gcash => Self::Gcash, enums::WalletType::Vipps => Self::Vipps, enums::WalletType::Momo => Self::Momo, enums::WalletType::Dana => Self::Dana, enums::WalletType::TouchNGo => Self::TouchNGo, enums::WalletType::Swish => Self::Swish, enums::WalletType::Cashapp => Self::Cashapp, enums::WalletType::Venmo => Self::Venmo, enums::WalletType::Mifinity => Self::Mifinity, enums::WalletType::Paze => Self::Paze, enums::WalletType::RevolutPay => Self::RevolutPay, } } } impl From<enums::BankDebitType> for global_enums::PaymentMethodType { fn from(value: enums::BankDebitType) -> Self { match value { enums::BankDebitType::Ach => Self::Ach, enums::BankDebitType::Sepa => Self::Sepa, enums::BankDebitType::SepaGuarenteedDebit => Self::SepaGuarenteedDebit, enums::BankDebitType::Bacs => Self::Bacs, enums::BankDebitType::Becs => Self::Becs, } } } impl From<enums::UpiType> for global_enums::PaymentMethodType { fn from(value: enums::UpiType) -> Self { match value { enums::UpiType::UpiCollect => Self::UpiCollect, enums::UpiType::UpiIntent => Self::UpiIntent, enums::UpiType::UpiQr => Self::UpiQr, } } } impl From<enums::VoucherType> for global_enums::PaymentMethodType { fn from(value: enums::VoucherType) -> Self { match value { enums::VoucherType::Boleto => Self::Boleto, enums::VoucherType::Efecty => Self::Efecty, enums::VoucherType::PagoEfectivo => Self::PagoEfectivo, enums::VoucherType::RedCompra => Self::RedCompra, enums::VoucherType::RedPagos => Self::RedPagos, enums::VoucherType::Alfamart => Self::Alfamart, enums::VoucherType::Indomaret => Self::Indomaret, enums::VoucherType::SevenEleven => Self::SevenEleven, enums::VoucherType::Lawson => Self::Lawson, enums::VoucherType::MiniStop => Self::MiniStop, enums::VoucherType::FamilyMart => Self::FamilyMart, enums::VoucherType::Seicomart => Self::Seicomart, enums::VoucherType::PayEasy => Self::PayEasy, enums::VoucherType::Oxxo => Self::Oxxo, } } } impl From<enums::BankTransferType> for global_enums::PaymentMethodType { fn from(value: enums::BankTransferType) -> Self { match value { enums::BankTransferType::Multibanco => Self::Multibanco, enums::BankTransferType::Pix => Self::Pix, enums::BankTransferType::Pse => Self::Pse, enums::BankTransferType::Ach => Self::Ach, enums::BankTransferType::SepaBankTransfer => Self::Sepa, enums::BankTransferType::Bacs => Self::Bacs, enums::BankTransferType::BcaBankTransfer => Self::BcaBankTransfer, enums::BankTransferType::BniVa => Self::BniVa, enums::BankTransferType::BriVa => Self::BriVa, enums::BankTransferType::CimbVa => Self::CimbVa, enums::BankTransferType::DanamonVa => Self::DanamonVa, enums::BankTransferType::MandiriVa => Self::MandiriVa, enums::BankTransferType::PermataBankTransfer => Self::PermataBankTransfer, enums::BankTransferType::LocalBankTransfer => Self::LocalBankTransfer, enums::BankTransferType::InstantBankTransfer => Self::InstantBankTransfer, enums::BankTransferType::InstantBankTransferFinland => Self::InstantBankTransferFinland, enums::BankTransferType::InstantBankTransferPoland => Self::InstantBankTransferPoland, enums::BankTransferType::IndonesianBankTransfer => Self::IndonesianBankTransfer, } } } impl From<enums::GiftCardType> for global_enums::PaymentMethodType { fn from(value: enums::GiftCardType) -> Self { match value { enums::GiftCardType::PaySafeCard => Self::PaySafeCard, enums::GiftCardType::Givex => Self::Givex, enums::GiftCardType::BhnCardNetwork => Self::BhnCardNetwork, } } } impl From<enums::CardRedirectType> for global_enums::PaymentMethodType { fn from(value: enums::CardRedirectType) -> Self { match value { enums::CardRedirectType::Benefit => Self::Benefit, enums::CardRedirectType::Knet => Self::Knet, enums::CardRedirectType::MomoAtm => Self::MomoAtm, enums::CardRedirectType::CardRedirect => Self::CardRedirect, } } } impl From<enums::MobilePaymentType> for global_enums::PaymentMethodType { fn from(value: enums::MobilePaymentType) -> Self { match value { enums::MobilePaymentType::DirectCarrierBilling => Self::DirectCarrierBilling, } } } impl From<enums::BankRedirectType> for global_enums::PaymentMethodType { fn from(value: enums::BankRedirectType) -> Self { match value { enums::BankRedirectType::Bizum => Self::Bizum, enums::BankRedirectType::Giropay => Self::Giropay, enums::BankRedirectType::Ideal => Self::Ideal, enums::BankRedirectType::Sofort => Self::Sofort, enums::BankRedirectType::Eft => Self::Eft, enums::BankRedirectType::Eps => Self::Eps, enums::BankRedirectType::BancontactCard => Self::BancontactCard, enums::BankRedirectType::Blik => Self::Blik, enums::BankRedirectType::Interac => Self::Interac, enums::BankRedirectType::LocalBankRedirect => Self::LocalBankRedirect, enums::BankRedirectType::OnlineBankingCzechRepublic => Self::OnlineBankingCzechRepublic, enums::BankRedirectType::OnlineBankingFinland => Self::OnlineBankingFinland, enums::BankRedirectType::OnlineBankingPoland => Self::OnlineBankingPoland, enums::BankRedirectType::OnlineBankingSlovakia => Self::OnlineBankingSlovakia, enums::BankRedirectType::OnlineBankingFpx => Self::OnlineBankingFpx, enums::BankRedirectType::OnlineBankingThailand => Self::OnlineBankingThailand, enums::BankRedirectType::OpenBankingUk => Self::OpenBankingUk, enums::BankRedirectType::Przelewy24 => Self::Przelewy24, enums::BankRedirectType::Trustly => Self::Trustly, } } } impl From<enums::OpenBankingType> for global_enums::PaymentMethodType { fn from(value: enums::OpenBankingType) -> Self { match value { enums::OpenBankingType::OpenBankingPIS => Self::OpenBankingPIS, } } } impl From<enums::CryptoType> for global_enums::PaymentMethodType { fn from(value: enums::CryptoType) -> Self { match value { enums::CryptoType::CryptoCurrency => Self::CryptoCurrency, } } } impl From<enums::RewardType> for global_enums::PaymentMethodType { fn from(value: enums::RewardType) -> Self { match value { enums::RewardType::ClassicReward => Self::ClassicReward, enums::RewardType::Evoucher => Self::Evoucher, } } } impl From<enums::RealTimePaymentType> for global_enums::PaymentMethodType { fn from(value: enums::RealTimePaymentType) -> Self { match value { enums::RealTimePaymentType::Fps => Self::Fps, enums::RealTimePaymentType::DuitNow => Self::DuitNow, enums::RealTimePaymentType::PromptPay => Self::PromptPay, enums::RealTimePaymentType::VietQr => Self::VietQr, } } } /// Analyses of the lowering of the DirValues to EuclidValues . /// /// For example, /// ```notrust /// DirValue::PaymentMethod::Cards -> EuclidValue::PaymentMethod::Cards /// ```notrust /// This is a function that lowers the Values of the DIR variants into the Value of the VIR variants. /// The function for each DirValue variant creates a corresponding EuclidValue variants and if there /// lacks any direct mapping, it return an Error. fn lower_value(dir_value: dir::DirValue) -> Result<EuclidValue, AnalysisErrorType> { Ok(match dir_value { dir::DirValue::PaymentMethod(pm) => EuclidValue::PaymentMethod(pm), dir::DirValue::CardBin(ci) => EuclidValue::CardBin(ci), dir::DirValue::CardType(ct) => EuclidValue::PaymentMethodType(ct.into()), dir::DirValue::CardNetwork(cn) => EuclidValue::CardNetwork(cn), dir::DirValue::MetaData(md) => EuclidValue::Metadata(md), dir::DirValue::PayLaterType(plt) => EuclidValue::PaymentMethodType(plt.into()), dir::DirValue::WalletType(wt) => EuclidValue::PaymentMethodType(wt.into()), dir::DirValue::UpiType(ut) => EuclidValue::PaymentMethodType(ut.into()), dir::DirValue::VoucherType(vt) => EuclidValue::PaymentMethodType(vt.into()), dir::DirValue::BankTransferType(btt) => EuclidValue::PaymentMethodType(btt.into()), dir::DirValue::GiftCardType(gct) => EuclidValue::PaymentMethodType(gct.into()), dir::DirValue::CardRedirectType(crt) => EuclidValue::PaymentMethodType(crt.into()), dir::DirValue::BankRedirectType(brt) => EuclidValue::PaymentMethodType(brt.into()), dir::DirValue::CryptoType(ct) => EuclidValue::PaymentMethodType(ct.into()), dir::DirValue::RealTimePaymentType(rtpt) => EuclidValue::PaymentMethodType(rtpt.into()), dir::DirValue::AuthenticationType(at) => EuclidValue::AuthenticationType(at), dir::DirValue::CaptureMethod(cm) => EuclidValue::CaptureMethod(cm), dir::DirValue::PaymentAmount(pa) => EuclidValue::PaymentAmount(pa), dir::DirValue::PaymentCurrency(pc) => EuclidValue::PaymentCurrency(pc), dir::DirValue::BusinessCountry(buc) => EuclidValue::BusinessCountry(buc), dir::DirValue::BillingCountry(bic) => EuclidValue::BillingCountry(bic), dir::DirValue::MandateAcceptanceType(mat) => EuclidValue::MandateAcceptanceType(mat), dir::DirValue::MandateType(mt) => EuclidValue::MandateType(mt), dir::DirValue::PaymentType(pt) => EuclidValue::PaymentType(pt), dir::DirValue::Connector(_) => Err(AnalysisErrorType::UnsupportedProgramKey( dir::DirKeyKind::Connector, ))?, dir::DirValue::BankDebitType(bdt) => EuclidValue::PaymentMethodType(bdt.into()), dir::DirValue::RewardType(rt) => EuclidValue::PaymentMethodType(rt.into()), dir::DirValue::BusinessLabel(bl) => EuclidValue::BusinessLabel(bl), dir::DirValue::SetupFutureUsage(sfu) => EuclidValue::SetupFutureUsage(sfu), dir::DirValue::OpenBankingType(ob) => EuclidValue::PaymentMethodType(ob.into()), dir::DirValue::MobilePaymentType(mp) => EuclidValue::PaymentMethodType(mp.into()), dir::DirValue::IssuerName(str_value) => EuclidValue::IssuerName(str_value), dir::DirValue::IssuerCountry(country) => EuclidValue::IssuerCountry(country), dir::DirValue::CustomerDevicePlatform(customer_device_platform) => { EuclidValue::CustomerDevicePlatform(customer_device_platform) } dir::DirValue::CustomerDeviceType(customer_device_type) => { EuclidValue::CustomerDeviceType(customer_device_type) } dir::DirValue::CustomerDeviceDisplaySize(customer_device_display_size) => { EuclidValue::CustomerDeviceDisplaySize(customer_device_display_size) } dir::DirValue::AcquirerCountry(country) => EuclidValue::AcquirerCountry(country), dir::DirValue::AcquirerFraudRate(num_value) => EuclidValue::AcquirerFraudRate(num_value), }) } fn lower_comparison( dir_comparison: dir::DirComparison, ) -> Result<vir::ValuedComparison, AnalysisErrorType> { Ok(vir::ValuedComparison { values: dir_comparison .values .into_iter() .map(lower_value) .collect::<Result<_, _>>()?, logic: match dir_comparison.logic { dir::DirComparisonLogic::NegativeConjunction => { vir::ValuedComparisonLogic::NegativeConjunction } dir::DirComparisonLogic::PositiveDisjunction => { vir::ValuedComparisonLogic::PositiveDisjunction } }, metadata: dir_comparison.metadata, }) } fn lower_if_statement( dir_if_statement: dir::DirIfStatement, ) -> Result<vir::ValuedIfStatement, AnalysisErrorType> { Ok(vir::ValuedIfStatement { condition: dir_if_statement .condition .into_iter() .map(lower_comparison) .collect::<Result<_, _>>()?, nested: dir_if_statement .nested .map(|v| { v.into_iter() .map(lower_if_statement) .collect::<Result<_, _>>() }) .transpose()?, }) } fn lower_rule<O>(dir_rule: dir::DirRule<O>) -> Result<vir::ValuedRule<O>, AnalysisErrorType> { Ok(vir::ValuedRule { name: dir_rule.name, connector_selection: dir_rule.connector_selection, statements: dir_rule .statements .into_iter() .map(lower_if_statement) .collect::<Result<_, _>>()?, }) } pub fn lower_program<O>( dir_program: dir::DirProgram<O>, ) -> Result<vir::ValuedProgram<O>, AnalysisError> { Ok(vir::ValuedProgram { default_selection: dir_program.default_selection, rules: dir_program .rules .into_iter() .map(lower_rule) .collect::<Result<_, _>>() .map_err(|e| AnalysisError { error_type: e, metadata: Default::default(), })?, metadata: dir_program.metadata, }) }
crates/euclid/src/frontend/dir/lowering.rs
euclid::src::frontend::dir::lowering
4,105
true
// File: crates/euclid/src/frontend/dir/transformers.rs // Module: euclid::src::frontend::dir::transformers use crate::{dirval, dssa::types::AnalysisErrorType, enums as global_enums, frontend::dir}; pub trait IntoDirValue { fn into_dir_value(self) -> Result<dir::DirValue, AnalysisErrorType>; } impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMethod) { fn into_dir_value(self) -> Result<dir::DirValue, AnalysisErrorType> { match self.0 { global_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), global_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), #[cfg(feature = "v2")] global_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)), global_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), global_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), global_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), global_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)), global_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)), global_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)), global_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)), global_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)), global_enums::PaymentMethodType::AfterpayClearpay => { Ok(dirval!(PayLaterType = AfterpayClearpay)) } global_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)), global_enums::PaymentMethodType::Skrill => Ok(dirval!(WalletType = Skrill)), global_enums::PaymentMethodType::Paysera => Ok(dirval!(WalletType = Paysera)), global_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)), global_enums::PaymentMethodType::Bluecode => Ok(dirval!(WalletType = Bluecode)), global_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)), global_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)), global_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)), global_enums::PaymentMethodType::CryptoCurrency => { Ok(dirval!(CryptoType = CryptoCurrency)) } global_enums::PaymentMethodType::Ach => match self.1 { global_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Ach)), global_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Ach)), global_enums::PaymentMethod::PayLater | global_enums::PaymentMethod::Card | global_enums::PaymentMethod::CardRedirect | global_enums::PaymentMethod::Wallet | global_enums::PaymentMethod::BankRedirect | global_enums::PaymentMethod::Crypto | global_enums::PaymentMethod::Reward | global_enums::PaymentMethod::RealTimePayment | global_enums::PaymentMethod::Upi | global_enums::PaymentMethod::Voucher | global_enums::PaymentMethod::OpenBanking | global_enums::PaymentMethod::MobilePayment | global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported), }, global_enums::PaymentMethodType::Bacs => match self.1 { global_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Bacs)), global_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Bacs)), global_enums::PaymentMethod::PayLater | global_enums::PaymentMethod::Card | global_enums::PaymentMethod::CardRedirect | global_enums::PaymentMethod::Wallet | global_enums::PaymentMethod::BankRedirect | global_enums::PaymentMethod::Crypto | global_enums::PaymentMethod::Reward | global_enums::PaymentMethod::RealTimePayment | global_enums::PaymentMethod::Upi | global_enums::PaymentMethod::Voucher | global_enums::PaymentMethod::OpenBanking | global_enums::PaymentMethod::MobilePayment | global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported), }, global_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)), global_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)), global_enums::PaymentMethodType::SepaGuarenteedDebit => { Ok(dirval!(BankDebitType = SepaGuarenteedDebit)) } global_enums::PaymentMethodType::SepaBankTransfer => { Ok(dirval!(BankTransferType = SepaBankTransfer)) } global_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)), global_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)), global_enums::PaymentMethodType::BancontactCard => { Ok(dirval!(BankRedirectType = BancontactCard)) } global_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)), global_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)), global_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)), global_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)), global_enums::PaymentMethodType::Multibanco => { Ok(dirval!(BankTransferType = Multibanco)) } global_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)), global_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)), global_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)), global_enums::PaymentMethodType::OnlineBankingCzechRepublic => { Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic)) } global_enums::PaymentMethodType::OnlineBankingFinland => { Ok(dirval!(BankRedirectType = OnlineBankingFinland)) } global_enums::PaymentMethodType::OnlineBankingPoland => { Ok(dirval!(BankRedirectType = OnlineBankingPoland)) } global_enums::PaymentMethodType::OnlineBankingSlovakia => { Ok(dirval!(BankRedirectType = OnlineBankingSlovakia)) } global_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)), global_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)), global_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)), global_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)), global_enums::PaymentMethodType::Flexiti => Ok(dirval!(PayLaterType = Flexiti)), global_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)), global_enums::PaymentMethodType::Breadpay => Ok(dirval!(PayLaterType = Breadpay)), global_enums::PaymentMethodType::Przelewy24 => { Ok(dirval!(BankRedirectType = Przelewy24)) } global_enums::PaymentMethodType::PromptPay => { Ok(dirval!(RealTimePaymentType = PromptPay)) } global_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)), global_enums::PaymentMethodType::ClassicReward => { Ok(dirval!(RewardType = ClassicReward)) } global_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), global_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), global_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)), global_enums::PaymentMethodType::UpiQr => Ok(dirval!(UpiType = UpiQr)), global_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), global_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), global_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), global_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)), global_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)), global_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)), global_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)), global_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)), global_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)), global_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)), global_enums::PaymentMethodType::OnlineBankingFpx => { Ok(dirval!(BankRedirectType = OnlineBankingFpx)) } global_enums::PaymentMethodType::LocalBankRedirect => { Ok(dirval!(BankRedirectType = LocalBankRedirect)) } global_enums::PaymentMethodType::OnlineBankingThailand => { Ok(dirval!(BankRedirectType = OnlineBankingThailand)) } global_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)), global_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)), global_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)), global_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)), global_enums::PaymentMethodType::PagoEfectivo => { Ok(dirval!(VoucherType = PagoEfectivo)) } global_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)), global_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)), global_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)), global_enums::PaymentMethodType::BcaBankTransfer => { Ok(dirval!(BankTransferType = BcaBankTransfer)) } global_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)), global_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)), global_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)), global_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)), global_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)), global_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)), global_enums::PaymentMethodType::LocalBankTransfer => { Ok(dirval!(BankTransferType = LocalBankTransfer)) } global_enums::PaymentMethodType::InstantBankTransfer => { Ok(dirval!(BankTransferType = InstantBankTransfer)) } global_enums::PaymentMethodType::InstantBankTransferFinland => { Ok(dirval!(BankTransferType = InstantBankTransferFinland)) } global_enums::PaymentMethodType::InstantBankTransferPoland => { Ok(dirval!(BankTransferType = InstantBankTransferPoland)) } global_enums::PaymentMethodType::PermataBankTransfer => { Ok(dirval!(BankTransferType = PermataBankTransfer)) } global_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)), global_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)), global_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)), global_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)), global_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)), global_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)), global_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)), global_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)), global_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)), global_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)), global_enums::PaymentMethodType::OpenBankingUk => { Ok(dirval!(BankRedirectType = OpenBankingUk)) } global_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)), global_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)), global_enums::PaymentMethodType::CardRedirect => { Ok(dirval!(CardRedirectType = CardRedirect)) } global_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)), global_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)), global_enums::PaymentMethodType::OpenBankingPIS => { Ok(dirval!(OpenBankingType = OpenBankingPIS)) } global_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)), global_enums::PaymentMethodType::DirectCarrierBilling => { Ok(dirval!(MobilePaymentType = DirectCarrierBilling)) } global_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)), global_enums::PaymentMethodType::IndonesianBankTransfer => { Ok(dirval!(BankTransferType = IndonesianBankTransfer)) } global_enums::PaymentMethodType::BhnCardNetwork => { Ok(dirval!(GiftCardType = BhnCardNetwork)) } } } }
crates/euclid/src/frontend/dir/transformers.rs
euclid::src::frontend::dir::transformers
3,401
true
// File: crates/euclid/src/frontend/dir/enums.rs // Module: euclid::src::frontend::dir::enums use strum::VariantNames; use utoipa::ToSchema; use crate::enums::collect_variants; pub use crate::enums::{ AuthenticationType, CaptureMethod, CardNetwork, Country, Country as BusinessCountry, Country as BillingCountry, Country as IssuerCountry, Country as AcquirerCountry, CountryAlpha2, Currency as PaymentCurrency, MandateAcceptanceType, MandateType, PaymentMethod, PaymentType, RoutableConnectors, SetupFutureUsage, }; #[cfg(feature = "payouts")] pub use crate::enums::{PayoutBankTransferType, PayoutType, PayoutWalletType}; #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardType { Credit, Debit, #[cfg(feature = "v2")] Card, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayLaterType { Affirm, AfterpayClearpay, Alma, Klarna, PayBright, Walley, Flexiti, Atome, Breadpay, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum WalletType { Bluecode, GooglePay, AmazonPay, Skrill, Paysera, ApplePay, Paypal, AliPay, AliPayHk, MbWay, MobilePay, WeChatPay, SamsungPay, GoPay, KakaoPay, Twint, Gcash, Vipps, Momo, Dana, TouchNGo, Swish, Cashapp, Venmo, Mifinity, Paze, RevolutPay, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum VoucherType { Boleto, Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart, Indomaret, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, Oxxo, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BankRedirectType { Bizum, Giropay, Ideal, Sofort, Eft, Eps, BancontactCard, Blik, Interac, LocalBankRedirect, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingPoland, OnlineBankingSlovakia, OnlineBankingFpx, OnlineBankingThailand, OpenBankingUk, Przelewy24, Trustly, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OpenBankingType { OpenBankingPIS, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BankTransferType { Multibanco, Ach, SepaBankTransfer, Bacs, BcaBankTransfer, BniVa, BriVa, CimbVa, DanamonVa, MandiriVa, PermataBankTransfer, Pix, Pse, LocalBankTransfer, InstantBankTransfer, InstantBankTransferFinland, InstantBankTransferPoland, IndonesianBankTransfer, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GiftCardType { PaySafeCard, Givex, BhnCardNetwork, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CardRedirectType { Benefit, Knet, MomoAtm, CardRedirect, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MobilePaymentType { DirectCarrierBilling, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CryptoType { CryptoCurrency, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RealTimePaymentType { Fps, DuitNow, PromptPay, VietQr, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UpiType { UpiCollect, UpiIntent, UpiQr, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum BankDebitType { Ach, Sepa, SepaGuarenteedDebit, Bacs, Becs, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RewardType { ClassicReward, Evoucher, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CustomerDevicePlatform { Web, Android, Ios, } #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CustomerDeviceType { Mobile, Tablet, Desktop, GamingConsole, } // Common display sizes for different device types #[derive( Clone, Debug, Hash, PartialEq, Eq, strum::Display, strum::VariantNames, strum::EnumIter, strum::EnumString, serde::Serialize, serde::Deserialize, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CustomerDeviceDisplaySize { // Mobile sizes Size320x568, // iPhone SE Size375x667, // iPhone 8 Size390x844, // iPhone 12/13 Size414x896, // iPhone XR/11 Size428x926, // iPhone 12/13 Pro Max // Tablet sizes Size768x1024, // iPad Size834x1112, // iPad Pro 10.5 Size834x1194, // iPad Pro 11 Size1024x1366, // iPad Pro 12.9 // Desktop sizes Size1280x720, // HD Size1366x768, // Common laptop Size1440x900, // MacBook Air Size1920x1080, // Full HD Size2560x1440, // QHD Size3840x2160, // 4K // Custom sizes Size500x600, Size600x400, // Other common sizes Size360x640, // Common Android Size412x915, // Pixel 6 Size800x1280, // Common Android tablet } collect_variants!(CardType); collect_variants!(PayLaterType); collect_variants!(WalletType); collect_variants!(BankRedirectType); collect_variants!(BankDebitType); collect_variants!(CryptoType); collect_variants!(RewardType); collect_variants!(RealTimePaymentType); collect_variants!(UpiType); collect_variants!(VoucherType); collect_variants!(GiftCardType); collect_variants!(BankTransferType); collect_variants!(CardRedirectType); collect_variants!(OpenBankingType); collect_variants!(MobilePaymentType); collect_variants!(CustomerDeviceType); collect_variants!(CustomerDevicePlatform); collect_variants!(CustomerDeviceDisplaySize);
crates/euclid/src/frontend/dir/enums.rs
euclid::src::frontend::dir::enums
2,741
true
// File: crates/euclid/src/frontend/ast/lowering.rs // Module: euclid::src::frontend::ast::lowering //! Analysis for the Lowering logic in ast //! //!Certain functions that can be used to perform the complete lowering of ast to dir. //!This includes lowering of enums, numbers, strings as well as Comparison logics. use std::str::FromStr; use crate::{ dssa::types::{AnalysisError, AnalysisErrorType}, enums::CollectVariants, frontend::{ ast, dir::{self, enums as dir_enums, EuclidDirFilter}, }, types::{self, DataType}, }; /// lowers the provided key (enum variant) & value to the respective DirValue /// /// For example /// ```notrust /// CardType = Visa /// ```notrust /// /// This serves for the purpose were we have the DirKey as an explicit Enum type and value as one /// of the member of the same Enum. /// So particularly it lowers a predefined Enum from DirKey to an Enum of DirValue. macro_rules! lower_enum { ($key:ident, $value:ident) => { match $value { ast::ValueType::EnumVariant(ev) => Ok(vec![dir::DirValue::$key( dir_enums::$key::from_str(&ev).map_err(|_| AnalysisErrorType::InvalidVariant { key: dir::DirKeyKind::$key.to_string(), got: ev, expected: dir_enums::$key::variants(), })?, )]), ast::ValueType::EnumVariantArray(eva) => eva .into_iter() .map(|ev| { Ok(dir::DirValue::$key( dir_enums::$key::from_str(&ev).map_err(|_| { AnalysisErrorType::InvalidVariant { key: dir::DirKeyKind::$key.to_string(), got: ev, expected: dir_enums::$key::variants(), } })?, )) }) .collect(), _ => Err(AnalysisErrorType::InvalidType { key: dir::DirKeyKind::$key.to_string(), expected: DataType::EnumVariant, got: $value.get_type(), }), } }; } /// lowers the provided key for a numerical value /// /// For example /// ```notrust /// payment_amount = 17052001 /// ```notrust /// This is for the cases in which there are numerical values involved and they are lowered /// accordingly on basis of the supplied key, currently payment_amount is the only key having this /// use case macro_rules! lower_number { ($key:ident, $value:ident, $comp:ident) => { match $value { ast::ValueType::Number(num) => Ok(vec![dir::DirValue::$key(types::NumValue { number: num, refinement: $comp.into(), })]), ast::ValueType::NumberArray(na) => na .into_iter() .map(|num| { Ok(dir::DirValue::$key(types::NumValue { number: num, refinement: $comp.clone().into(), })) }) .collect(), ast::ValueType::NumberComparisonArray(nca) => nca .into_iter() .map(|nc| { Ok(dir::DirValue::$key(types::NumValue { number: nc.number, refinement: nc.comparison_type.into(), })) }) .collect(), _ => Err(AnalysisErrorType::InvalidType { key: dir::DirKeyKind::$key.to_string(), expected: DataType::Number, got: $value.get_type(), }), } }; } /// lowers the provided key & value to the respective DirValue /// /// For example /// ```notrust /// card_bin = "123456" /// ```notrust /// /// This serves for the purpose were we have the DirKey as Card_bin and value as an arbitrary string /// So particularly it lowers an arbitrary value to a predefined key. macro_rules! lower_str { ($key:ident, $value:ident $(, $validation_closure:expr)?) => { match $value { ast::ValueType::StrValue(st) => { $($validation_closure(&st)?;)? Ok(vec![dir::DirValue::$key(types::StrValue { value: st })]) } _ => Err(AnalysisErrorType::InvalidType { key: dir::DirKeyKind::$key.to_string(), expected: DataType::StrValue, got: $value.get_type(), }), } }; } macro_rules! lower_metadata { ($key:ident, $value:ident) => { match $value { ast::ValueType::MetadataVariant(md) => { Ok(vec![dir::DirValue::$key(types::MetadataValue { key: md.key, value: md.value, })]) } _ => Err(AnalysisErrorType::InvalidType { key: dir::DirKeyKind::$key.to_string(), expected: DataType::MetadataValue, got: $value.get_type(), }), } }; } /// lowers the comparison operators for different subtle value types present /// by throwing required errors for comparisons that can't be performed for a certain value type /// for example /// can't have greater/less than operations on enum types fn lower_comparison_inner<O: EuclidDirFilter>( comp: ast::Comparison, ) -> Result<Vec<dir::DirValue>, AnalysisErrorType> { let key_enum = dir::DirKeyKind::from_str(comp.lhs.as_str()) .map_err(|_| AnalysisErrorType::InvalidKey(comp.lhs.clone()))?; if !O::is_key_allowed(&key_enum) { return Err(AnalysisErrorType::InvalidKey(key_enum.to_string())); } match (&comp.comparison, &comp.value) { ( ast::ComparisonType::LessThan | ast::ComparisonType::GreaterThan | ast::ComparisonType::GreaterThanEqual | ast::ComparisonType::LessThanEqual, ast::ValueType::EnumVariant(_), ) => { Err(AnalysisErrorType::InvalidComparison { operator: comp.comparison.clone(), value_type: DataType::EnumVariant, })?; } ( ast::ComparisonType::LessThan | ast::ComparisonType::GreaterThan | ast::ComparisonType::GreaterThanEqual | ast::ComparisonType::LessThanEqual, ast::ValueType::NumberArray(_), ) => { Err(AnalysisErrorType::InvalidComparison { operator: comp.comparison.clone(), value_type: DataType::Number, })?; } ( ast::ComparisonType::LessThan | ast::ComparisonType::GreaterThan | ast::ComparisonType::GreaterThanEqual | ast::ComparisonType::LessThanEqual, ast::ValueType::EnumVariantArray(_), ) => { Err(AnalysisErrorType::InvalidComparison { operator: comp.comparison.clone(), value_type: DataType::EnumVariant, })?; } ( ast::ComparisonType::LessThan | ast::ComparisonType::GreaterThan | ast::ComparisonType::GreaterThanEqual | ast::ComparisonType::LessThanEqual, ast::ValueType::NumberComparisonArray(_), ) => { Err(AnalysisErrorType::InvalidComparison { operator: comp.comparison.clone(), value_type: DataType::Number, })?; } _ => {} } let value = comp.value; let comparison = comp.comparison; match key_enum { dir::DirKeyKind::PaymentMethod => lower_enum!(PaymentMethod, value), dir::DirKeyKind::CardType => lower_enum!(CardType, value), dir::DirKeyKind::CardNetwork => lower_enum!(CardNetwork, value), dir::DirKeyKind::PayLaterType => lower_enum!(PayLaterType, value), dir::DirKeyKind::WalletType => lower_enum!(WalletType, value), dir::DirKeyKind::BankDebitType => lower_enum!(BankDebitType, value), dir::DirKeyKind::BankRedirectType => lower_enum!(BankRedirectType, value), dir::DirKeyKind::CryptoType => lower_enum!(CryptoType, value), dir::DirKeyKind::PaymentType => lower_enum!(PaymentType, value), dir::DirKeyKind::MandateType => lower_enum!(MandateType, value), dir::DirKeyKind::MandateAcceptanceType => lower_enum!(MandateAcceptanceType, value), dir::DirKeyKind::RewardType => lower_enum!(RewardType, value), dir::DirKeyKind::PaymentCurrency => lower_enum!(PaymentCurrency, value), dir::DirKeyKind::AuthenticationType => lower_enum!(AuthenticationType, value), dir::DirKeyKind::CaptureMethod => lower_enum!(CaptureMethod, value), dir::DirKeyKind::BusinessCountry => lower_enum!(BusinessCountry, value), dir::DirKeyKind::BillingCountry => lower_enum!(BillingCountry, value), dir::DirKeyKind::SetupFutureUsage => lower_enum!(SetupFutureUsage, value), dir::DirKeyKind::UpiType => lower_enum!(UpiType, value), dir::DirKeyKind::OpenBankingType => lower_enum!(OpenBankingType, value), dir::DirKeyKind::VoucherType => lower_enum!(VoucherType, value), dir::DirKeyKind::GiftCardType => lower_enum!(GiftCardType, value), dir::DirKeyKind::BankTransferType => lower_enum!(BankTransferType, value), dir::DirKeyKind::CardRedirectType => lower_enum!(CardRedirectType, value), dir::DirKeyKind::MobilePaymentType => lower_enum!(MobilePaymentType, value), dir::DirKeyKind::RealTimePaymentType => lower_enum!(RealTimePaymentType, value), dir::DirKeyKind::CardBin => { let validation_closure = |st: &String| -> Result<(), AnalysisErrorType> { if st.len() == 6 && st.chars().all(|x| x.is_ascii_digit()) { Ok(()) } else { Err(AnalysisErrorType::InvalidValue { key: dir::DirKeyKind::CardBin, value: st.clone(), message: Some("Expected 6 digits".to_string()), }) } }; lower_str!(CardBin, value, validation_closure) } dir::DirKeyKind::BusinessLabel => lower_str!(BusinessLabel, value), dir::DirKeyKind::MetaData => lower_metadata!(MetaData, value), dir::DirKeyKind::PaymentAmount => lower_number!(PaymentAmount, value, comparison), dir::DirKeyKind::Connector => Err(AnalysisErrorType::InvalidKey( dir::DirKeyKind::Connector.to_string(), )), dir::DirKeyKind::IssuerName => lower_str!(IssuerName, value), dir::DirKeyKind::IssuerCountry => lower_enum!(IssuerCountry, value), dir::DirKeyKind::CustomerDevicePlatform => lower_enum!(CustomerDevicePlatform, value), dir::DirKeyKind::CustomerDeviceType => lower_enum!(CustomerDeviceType, value), dir::DirKeyKind::CustomerDeviceDisplaySize => lower_enum!(CustomerDeviceDisplaySize, value), dir::DirKeyKind::AcquirerCountry => lower_enum!(AcquirerCountry, value), dir::DirKeyKind::AcquirerFraudRate => lower_number!(AcquirerFraudRate, value, comparison), } } /// returns all the comparison values by matching them appropriately to ComparisonTypes and in turn /// calls the lower_comparison_inner function fn lower_comparison<O: EuclidDirFilter>( comp: ast::Comparison, ) -> Result<dir::DirComparison, AnalysisError> { let metadata = comp.metadata.clone(); let logic = match &comp.comparison { ast::ComparisonType::Equal => dir::DirComparisonLogic::PositiveDisjunction, ast::ComparisonType::NotEqual => dir::DirComparisonLogic::NegativeConjunction, ast::ComparisonType::LessThan => dir::DirComparisonLogic::PositiveDisjunction, ast::ComparisonType::LessThanEqual => dir::DirComparisonLogic::PositiveDisjunction, ast::ComparisonType::GreaterThanEqual => dir::DirComparisonLogic::PositiveDisjunction, ast::ComparisonType::GreaterThan => dir::DirComparisonLogic::PositiveDisjunction, }; let values = lower_comparison_inner::<O>(comp).map_err(|etype| AnalysisError { error_type: etype, metadata: metadata.clone(), })?; Ok(dir::DirComparison { values, logic, metadata, }) } /// lowers the if statement accordingly with a condition and following nested if statements (if /// present) fn lower_if_statement<O: EuclidDirFilter>( stmt: ast::IfStatement, ) -> Result<dir::DirIfStatement, AnalysisError> { Ok(dir::DirIfStatement { condition: stmt .condition .into_iter() .map(lower_comparison::<O>) .collect::<Result<_, _>>()?, nested: stmt .nested .map(|n| n.into_iter().map(lower_if_statement::<O>).collect()) .transpose()?, }) } /// lowers the rules supplied accordingly to DirRule struct by specifying the rule_name, /// connector_selection and statements that are a bunch of if statements pub fn lower_rule<O: EuclidDirFilter>( rule: ast::Rule<O>, ) -> Result<dir::DirRule<O>, AnalysisError> { Ok(dir::DirRule { name: rule.name, connector_selection: rule.connector_selection, statements: rule .statements .into_iter() .map(lower_if_statement::<O>) .collect::<Result<_, _>>()?, }) } /// uses the above rules and lowers the whole ast Program into DirProgram by specifying /// default_selection that is ast ConnectorSelection, a vector of DirRules and clones the metadata /// whatever comes in the ast_program pub fn lower_program<O: EuclidDirFilter>( program: ast::Program<O>, ) -> Result<dir::DirProgram<O>, AnalysisError> { Ok(dir::DirProgram { default_selection: program.default_selection, rules: program .rules .into_iter() .map(lower_rule) .collect::<Result<_, _>>()?, metadata: program.metadata, }) }
crates/euclid/src/frontend/ast/lowering.rs
euclid::src::frontend::ast::lowering
3,123
true
// File: crates/euclid/src/frontend/ast/parser.rs // Module: euclid::src::frontend::ast::parser use common_utils::types::MinorUnit; use nom::{ branch, bytes::complete, character::complete as pchar, combinator, error, multi, sequence, }; use crate::{frontend::ast, types::DummyOutput}; pub type ParseResult<T, U> = nom::IResult<T, U, error::VerboseError<T>>; pub enum EuclidError { InvalidPercentage(String), InvalidConnector(String), InvalidOperator(String), InvalidNumber(String), } pub trait EuclidParsable: Sized { fn parse_output(input: &str) -> ParseResult<&str, Self>; } impl EuclidParsable for DummyOutput { fn parse_output(input: &str) -> ParseResult<&str, Self> { let string_w = sequence::delimited( skip_ws(complete::tag("\"")), complete::take_while(|c| c != '"'), skip_ws(complete::tag("\"")), ); let full_sequence = multi::many0(sequence::preceded( skip_ws(complete::tag(",")), sequence::delimited( skip_ws(complete::tag("\"")), complete::take_while(|c| c != '"'), skip_ws(complete::tag("\"")), ), )); let sequence = sequence::pair(string_w, full_sequence); error::context( "dummy_strings", combinator::map( sequence::delimited( skip_ws(complete::tag("[")), sequence, skip_ws(complete::tag("]")), ), |out: (&str, Vec<&str>)| { let mut first = out.1; first.insert(0, out.0); let v = first.iter().map(|s| s.to_string()).collect(); Self { outputs: v } }, ), )(input) } } pub fn skip_ws<'a, F, O>(inner: F) -> impl FnMut(&'a str) -> ParseResult<&'a str, O> where F: FnMut(&'a str) -> ParseResult<&'a str, O> + 'a, { sequence::preceded(pchar::multispace0, inner) } pub fn num_i64(input: &str) -> ParseResult<&str, i64> { error::context( "num_i32", combinator::map_res( complete::take_while1(|c: char| c.is_ascii_digit()), |o: &str| { o.parse::<i64>() .map_err(|_| EuclidError::InvalidNumber(o.to_string())) }, ), )(input) } pub fn string_str(input: &str) -> ParseResult<&str, String> { error::context( "String", combinator::map( sequence::delimited( complete::tag("\""), complete::take_while1(|c: char| c != '"'), complete::tag("\""), ), |val: &str| val.to_string(), ), )(input) } pub fn identifier(input: &str) -> ParseResult<&str, String> { error::context( "identifier", combinator::map( sequence::pair( complete::take_while1(|c: char| c.is_ascii_alphabetic() || c == '_'), complete::take_while(|c: char| c.is_ascii_alphanumeric() || c == '_'), ), |out: (&str, &str)| out.0.to_string() + out.1, ), )(input) } pub fn percentage(input: &str) -> ParseResult<&str, u8> { error::context( "volume_split_percentage", combinator::map_res( sequence::terminated( complete::take_while_m_n(1, 2, |c: char| c.is_ascii_digit()), complete::tag("%"), ), |o: &str| { o.parse::<u8>() .map_err(|_| EuclidError::InvalidPercentage(o.to_string())) }, ), )(input) } pub fn number_value(input: &str) -> ParseResult<&str, ast::ValueType> { error::context( "number_value", combinator::map(num_i64, |n| ast::ValueType::Number(MinorUnit::new(n))), )(input) } pub fn str_value(input: &str) -> ParseResult<&str, ast::ValueType> { error::context( "str_value", combinator::map(string_str, ast::ValueType::StrValue), )(input) } pub fn enum_value_string(input: &str) -> ParseResult<&str, String> { combinator::map( sequence::pair( complete::take_while1(|c: char| c.is_ascii_alphabetic() || c == '_'), complete::take_while(|c: char| c.is_ascii_alphanumeric() || c == '_'), ), |out: (&str, &str)| out.0.to_string() + out.1, )(input) } pub fn enum_variant_value(input: &str) -> ParseResult<&str, ast::ValueType> { error::context( "enum_variant_value", combinator::map(enum_value_string, ast::ValueType::EnumVariant), )(input) } pub fn number_array_value(input: &str) -> ParseResult<&str, ast::ValueType> { fn num_minor_unit(input: &str) -> ParseResult<&str, MinorUnit> { combinator::map(num_i64, MinorUnit::new)(input) } let many_with_comma = multi::many0(sequence::preceded( skip_ws(complete::tag(",")), skip_ws(num_minor_unit), )); let full_sequence = sequence::pair(skip_ws(num_minor_unit), many_with_comma); error::context( "number_array_value", combinator::map( sequence::delimited( skip_ws(complete::tag("(")), full_sequence, skip_ws(complete::tag(")")), ), |tup: (MinorUnit, Vec<MinorUnit>)| { let mut rest = tup.1; rest.insert(0, tup.0); ast::ValueType::NumberArray(rest) }, ), )(input) } pub fn enum_variant_array_value(input: &str) -> ParseResult<&str, ast::ValueType> { let many_with_comma = multi::many0(sequence::preceded( skip_ws(complete::tag(",")), skip_ws(enum_value_string), )); let full_sequence = sequence::pair(skip_ws(enum_value_string), many_with_comma); error::context( "enum_variant_array_value", combinator::map( sequence::delimited( skip_ws(complete::tag("(")), full_sequence, skip_ws(complete::tag(")")), ), |tup: (String, Vec<String>)| { let mut rest = tup.1; rest.insert(0, tup.0); ast::ValueType::EnumVariantArray(rest) }, ), )(input) } pub fn number_comparison(input: &str) -> ParseResult<&str, ast::NumberComparison> { let operator = combinator::map_res( branch::alt(( complete::tag(">="), complete::tag("<="), complete::tag(">"), complete::tag("<"), )), |s: &str| match s { ">=" => Ok(ast::ComparisonType::GreaterThanEqual), "<=" => Ok(ast::ComparisonType::LessThanEqual), ">" => Ok(ast::ComparisonType::GreaterThan), "<" => Ok(ast::ComparisonType::LessThan), _ => Err(EuclidError::InvalidOperator(s.to_string())), }, ); error::context( "number_comparison", combinator::map( sequence::pair(operator, num_i64), |tup: (ast::ComparisonType, i64)| ast::NumberComparison { comparison_type: tup.0, number: MinorUnit::new(tup.1), }, ), )(input) } pub fn number_comparison_array_value(input: &str) -> ParseResult<&str, ast::ValueType> { let many_with_comma = multi::many0(sequence::preceded( skip_ws(complete::tag(",")), skip_ws(number_comparison), )); let full_sequence = sequence::pair(skip_ws(number_comparison), many_with_comma); error::context( "number_comparison_array_value", combinator::map( sequence::delimited( skip_ws(complete::tag("(")), full_sequence, skip_ws(complete::tag(")")), ), |tup: (ast::NumberComparison, Vec<ast::NumberComparison>)| { let mut rest = tup.1; rest.insert(0, tup.0); ast::ValueType::NumberComparisonArray(rest) }, ), )(input) } pub fn value_type(input: &str) -> ParseResult<&str, ast::ValueType> { error::context( "value_type", branch::alt(( number_value, enum_variant_value, enum_variant_array_value, number_array_value, number_comparison_array_value, str_value, )), )(input) } pub fn comparison_type(input: &str) -> ParseResult<&str, ast::ComparisonType> { error::context( "comparison_operator", combinator::map_res( branch::alt(( complete::tag("/="), complete::tag(">="), complete::tag("<="), complete::tag("="), complete::tag(">"), complete::tag("<"), )), |s: &str| match s { "/=" => Ok(ast::ComparisonType::NotEqual), ">=" => Ok(ast::ComparisonType::GreaterThanEqual), "<=" => Ok(ast::ComparisonType::LessThanEqual), "=" => Ok(ast::ComparisonType::Equal), ">" => Ok(ast::ComparisonType::GreaterThan), "<" => Ok(ast::ComparisonType::LessThan), _ => Err(EuclidError::InvalidOperator(s.to_string())), }, ), )(input) } pub fn comparison(input: &str) -> ParseResult<&str, ast::Comparison> { error::context( "condition", combinator::map( sequence::tuple(( skip_ws(complete::take_while1(|c: char| { c.is_ascii_alphabetic() || c == '.' || c == '_' })), skip_ws(comparison_type), skip_ws(value_type), )), |tup: (&str, ast::ComparisonType, ast::ValueType)| ast::Comparison { lhs: tup.0.to_string(), comparison: tup.1, value: tup.2, metadata: std::collections::HashMap::new(), }, ), )(input) } pub fn arbitrary_comparison(input: &str) -> ParseResult<&str, ast::Comparison> { error::context( "condition", combinator::map( sequence::tuple(( skip_ws(string_str), skip_ws(comparison_type), skip_ws(string_str), )), |tup: (String, ast::ComparisonType, String)| ast::Comparison { lhs: "metadata".to_string(), comparison: tup.1, value: ast::ValueType::MetadataVariant(ast::MetadataValue { key: tup.0, value: tup.2, }), metadata: std::collections::HashMap::new(), }, ), )(input) } pub fn comparison_array(input: &str) -> ParseResult<&str, Vec<ast::Comparison>> { let many_with_ampersand = error::context( "many_with_amp", multi::many0(sequence::preceded(skip_ws(complete::tag("&")), comparison)), ); let full_sequence = sequence::pair( skip_ws(branch::alt((comparison, arbitrary_comparison))), many_with_ampersand, ); error::context( "comparison_array", combinator::map( full_sequence, |tup: (ast::Comparison, Vec<ast::Comparison>)| { let mut rest = tup.1; rest.insert(0, tup.0); rest }, ), )(input) } pub fn if_statement(input: &str) -> ParseResult<&str, ast::IfStatement> { let nested_block = sequence::delimited( skip_ws(complete::tag("{")), multi::many0(if_statement), skip_ws(complete::tag("}")), ); error::context( "if_statement", combinator::map( sequence::pair(comparison_array, combinator::opt(nested_block)), |tup: (ast::IfCondition, Option<Vec<ast::IfStatement>>)| ast::IfStatement { condition: tup.0, nested: tup.1, }, ), )(input) } pub fn rule_conditions_array(input: &str) -> ParseResult<&str, Vec<ast::IfStatement>> { error::context( "rules_array", sequence::delimited( skip_ws(complete::tag("{")), multi::many1(if_statement), skip_ws(complete::tag("}")), ), )(input) } pub fn rule<O: EuclidParsable>(input: &str) -> ParseResult<&str, ast::Rule<O>> { let rule_name = error::context( "rule_name", combinator::map( skip_ws(sequence::pair( complete::take_while1(|c: char| c.is_ascii_alphabetic() || c == '_'), complete::take_while(|c: char| c.is_ascii_alphanumeric() || c == '_'), )), |out: (&str, &str)| out.0.to_string() + out.1, ), ); let connector_selection = error::context( "parse_output", sequence::preceded(skip_ws(complete::tag(":")), output), ); error::context( "rule", combinator::map( sequence::tuple((rule_name, connector_selection, rule_conditions_array)), |tup: (String, O, Vec<ast::IfStatement>)| ast::Rule { name: tup.0, connector_selection: tup.1, statements: tup.2, }, ), )(input) } pub fn output<O: EuclidParsable>(input: &str) -> ParseResult<&str, O> { O::parse_output(input) } pub fn default_output<O: EuclidParsable + 'static>(input: &str) -> ParseResult<&str, O> { error::context( "default_output", sequence::preceded( sequence::pair(skip_ws(complete::tag("default")), skip_ws(pchar::char(':'))), skip_ws(output), ), )(input) } pub fn program<O: EuclidParsable + 'static>(input: &str) -> ParseResult<&str, ast::Program<O>> { error::context( "program", combinator::map( sequence::pair(default_output, multi::many1(skip_ws(rule::<O>))), |tup: (O, Vec<ast::Rule<O>>)| ast::Program { default_selection: tup.0, rules: tup.1, metadata: std::collections::HashMap::new(), }, ), )(input) }
crates/euclid/src/frontend/ast/parser.rs
euclid::src::frontend::ast::parser
3,362
true
// File: crates/euclid/src/backend/vir_interpreter.rs // Module: euclid::src::backend::vir_interpreter pub mod types; use std::fmt::Debug; use serde::{Deserialize, Serialize}; use crate::{ backend::{self, inputs, EuclidBackend}, frontend::{ ast, dir::{self, EuclidDirFilter}, vir, }, }; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct VirInterpreterBackend<O> { program: vir::ValuedProgram<O>, } impl<O> VirInterpreterBackend<O> where O: Clone, { #[inline] fn eval_comparison(comp: &vir::ValuedComparison, ctx: &types::Context) -> bool { match &comp.logic { vir::ValuedComparisonLogic::PositiveDisjunction => { comp.values.iter().any(|v| ctx.check_presence(v)) } vir::ValuedComparisonLogic::NegativeConjunction => { comp.values.iter().all(|v| !ctx.check_presence(v)) } } } #[inline] fn eval_condition(cond: &vir::ValuedIfCondition, ctx: &types::Context) -> bool { cond.iter().all(|comp| Self::eval_comparison(comp, ctx)) } fn eval_statement(stmt: &vir::ValuedIfStatement, ctx: &types::Context) -> bool { if Self::eval_condition(&stmt.condition, ctx) { { stmt.nested.as_ref().is_none_or(|nested_stmts| { nested_stmts.iter().any(|s| Self::eval_statement(s, ctx)) }) } } else { false } } fn eval_rule(rule: &vir::ValuedRule<O>, ctx: &types::Context) -> bool { rule.statements .iter() .any(|stmt| Self::eval_statement(stmt, ctx)) } fn eval_program( program: &vir::ValuedProgram<O>, ctx: &types::Context, ) -> backend::BackendOutput<O> { program .rules .iter() .find(|rule| Self::eval_rule(rule, ctx)) .map_or_else( || backend::BackendOutput { connector_selection: program.default_selection.clone(), rule_name: None, }, |rule| backend::BackendOutput { connector_selection: rule.connector_selection.clone(), rule_name: Some(rule.name.clone()), }, ) } } impl<O> EuclidBackend<O> for VirInterpreterBackend<O> where O: Clone + EuclidDirFilter, { type Error = types::VirInterpreterError; fn with_program(program: ast::Program<O>) -> Result<Self, Self::Error> { let dir_program = ast::lowering::lower_program(program) .map_err(types::VirInterpreterError::LoweringError)?; let vir_program = dir::lowering::lower_program(dir_program) .map_err(types::VirInterpreterError::LoweringError)?; Ok(Self { program: vir_program, }) } fn execute( &self, input: inputs::BackendInput, ) -> Result<backend::BackendOutput<O>, Self::Error> { let ctx = types::Context::from_input(input); Ok(Self::eval_program(&self.program, &ctx)) } } #[cfg(all(test, feature = "ast_parser"))] mod test { #![allow(clippy::expect_used)] use common_utils::types::MinorUnit; use rustc_hash::FxHashMap; use super::*; use crate::{enums, types::DummyOutput}; #[test] fn test_execution() { let program_str = r#" default: [ "stripe", "adyen"] rule_1: ["stripe"] { pay_later = klarna } rule_2: ["adyen"] { pay_later = affirm } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), card_bin: None, currency: enums::Currency::USD, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_2"); } #[test] fn test_payment_type() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { payment_type = setup_mandate } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: Some("123456".to_string()), authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: Some(enums::PaymentType::SetupMandate), }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_ppt_flow() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { payment_type = ppt_mandate } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: Some("123456".to_string()), authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: Some(enums::PaymentType::PptMandate), }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_mandate_type() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { mandate_type = single_use } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: Some("123456".to_string()), authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: Some(enums::MandateType::SingleUse), payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_mandate_acceptance_type() { let program_str = r#" default: ["stripe","adyen"] rule_1: ["stripe"] { mandate_acceptance_type = online } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: Some("123456".to_string()), authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: Some(enums::MandateAcceptanceType::Online), mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_card_bin() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { card_bin="123456" } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: Some("123456".to_string()), authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_payment_amount() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { amount = 32 } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: None, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_payment_method() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { payment_method = pay_later } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: None, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_future_usage() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { setup_future_usage = off_session } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(32), currency: enums::Currency::USD, card_bin: None, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: Some(enums::SetupFutureUsage::OffSession), }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_metadata_execution() { let program_str = r#" default: ["stripe"," adyen"] rule_1: ["stripe"] { "metadata_key" = "arbitrary meta" } "#; let mut meta_map = FxHashMap::default(); meta_map.insert("metadata_key".to_string(), "arbitrary meta".to_string()); let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp = inputs::BackendInput { metadata: Some(meta_map), payment: inputs::PaymentInput { amount: MinorUnit::new(32), card_bin: None, currency: enums::Currency::USD, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result = backend.execute(inp).expect("Execution"); assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1"); } #[test] fn test_less_than_operator() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { amount>=123 } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp_greater = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(150), card_bin: None, currency: enums::Currency::USD, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let mut inp_equal = inp_greater.clone(); inp_equal.payment.amount = MinorUnit::new(123); let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result_greater = backend.execute(inp_greater).expect("Execution"); let result_equal = backend.execute(inp_equal).expect("Execution"); assert_eq!( result_equal.rule_name.expect("Rule Name").as_str(), "rule_1" ); assert_eq!( result_greater.rule_name.expect("Rule Name").as_str(), "rule_1" ); } #[test] fn test_greater_than_operator() { let program_str = r#" default: ["stripe", "adyen"] rule_1: ["stripe"] { amount<=123 } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let inp_lower = inputs::BackendInput { metadata: None, payment: inputs::PaymentInput { amount: MinorUnit::new(120), card_bin: None, currency: enums::Currency::USD, authentication_type: Some(enums::AuthenticationType::NoThreeDs), capture_method: Some(enums::CaptureMethod::Automatic), business_country: Some(enums::Country::UnitedStatesOfAmerica), billing_country: Some(enums::Country::France), business_label: None, setup_future_usage: None, }, payment_method: inputs::PaymentMethodInput { payment_method: Some(enums::PaymentMethod::PayLater), payment_method_type: Some(enums::PaymentMethodType::Affirm), card_network: None, }, mandate: inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, acquirer_data: None, customer_device_data: None, issuer_data: None, }; let mut inp_equal = inp_lower.clone(); inp_equal.payment.amount = MinorUnit::new(123); let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program"); let result_equal = backend.execute(inp_equal).expect("Execution"); let result_lower = backend.execute(inp_lower).expect("Execution"); assert_eq!( result_equal.rule_name.expect("Rule Name").as_str(), "rule_1" ); assert_eq!( result_lower.rule_name.expect("Rule Name").as_str(), "rule_1" ); } }
crates/euclid/src/backend/vir_interpreter.rs
euclid::src::backend::vir_interpreter
5,255
true
// File: crates/euclid/src/backend/inputs.rs // Module: euclid::src::backend::inputs use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use crate::{ enums, frontend::dir::enums::{CustomerDeviceDisplaySize, CustomerDevicePlatform, CustomerDeviceType}, }; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MandateData { pub mandate_acceptance_type: Option<enums::MandateAcceptanceType>, pub mandate_type: Option<enums::MandateType>, pub payment_type: Option<enums::PaymentType>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentMethodInput { pub payment_method: Option<enums::PaymentMethod>, pub payment_method_type: Option<enums::PaymentMethodType>, pub card_network: Option<enums::CardNetwork>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentInput { pub amount: common_utils::types::MinorUnit, pub currency: enums::Currency, pub authentication_type: Option<enums::AuthenticationType>, pub card_bin: Option<String>, pub capture_method: Option<enums::CaptureMethod>, pub business_country: Option<enums::Country>, pub billing_country: Option<enums::Country>, pub business_label: Option<String>, pub setup_future_usage: Option<enums::SetupFutureUsage>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AcquirerDataInput { pub country: Option<enums::Country>, pub fraud_rate: Option<f64>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CustomerDeviceDataInput { pub platform: Option<CustomerDevicePlatform>, pub device_type: Option<CustomerDeviceType>, pub display_size: Option<CustomerDeviceDisplaySize>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct IssuerDataInput { pub name: Option<String>, pub country: Option<enums::Country>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BackendInput { pub metadata: Option<FxHashMap<String, String>>, pub payment: PaymentInput, pub payment_method: PaymentMethodInput, pub acquirer_data: Option<AcquirerDataInput>, pub customer_device_data: Option<CustomerDeviceDataInput>, pub issuer_data: Option<IssuerDataInput>, pub mandate: MandateData, }
crates/euclid/src/backend/inputs.rs
euclid::src::backend::inputs
505
true
// File: crates/euclid/src/backend/interpreter.rs // Module: euclid::src::backend::interpreter pub mod types; use common_utils::types::MinorUnit; use crate::{ backend::{self, inputs, EuclidBackend}, frontend::ast, }; pub struct InterpreterBackend<O> { program: ast::Program<O>, } impl<O> InterpreterBackend<O> where O: Clone, { fn eval_number_comparison_array( num: MinorUnit, array: &[ast::NumberComparison], ) -> Result<bool, types::InterpreterError> { for comparison in array { let other = comparison.number; let res = match comparison.comparison_type { ast::ComparisonType::GreaterThan => num > other, ast::ComparisonType::LessThan => num < other, ast::ComparisonType::LessThanEqual => num <= other, ast::ComparisonType::GreaterThanEqual => num >= other, ast::ComparisonType::Equal => num == other, ast::ComparisonType::NotEqual => num != other, }; if res { return Ok(true); } } Ok(false) } fn eval_comparison( comparison: &ast::Comparison, ctx: &types::Context, ) -> Result<bool, types::InterpreterError> { use ast::{ComparisonType::*, ValueType::*}; let value = ctx .get(&comparison.lhs) .ok_or_else(|| types::InterpreterError { error_type: types::InterpreterErrorType::InvalidKey(comparison.lhs.clone()), metadata: comparison.metadata.clone(), })?; if let Some(val) = value { match (val, &comparison.comparison, &comparison.value) { (EnumVariant(e1), Equal, EnumVariant(e2)) => Ok(e1 == e2), (EnumVariant(e1), NotEqual, EnumVariant(e2)) => Ok(e1 != e2), (EnumVariant(e), Equal, EnumVariantArray(evec)) => Ok(evec.iter().any(|v| e == v)), (EnumVariant(e), NotEqual, EnumVariantArray(evec)) => { Ok(evec.iter().all(|v| e != v)) } (Number(n1), Equal, Number(n2)) => Ok(n1 == n2), (Number(n1), NotEqual, Number(n2)) => Ok(n1 != n2), (Number(n1), LessThanEqual, Number(n2)) => Ok(n1 <= n2), (Number(n1), GreaterThanEqual, Number(n2)) => Ok(n1 >= n2), (Number(n1), LessThan, Number(n2)) => Ok(n1 < n2), (Number(n1), GreaterThan, Number(n2)) => Ok(n1 > n2), (Number(n), Equal, NumberArray(nvec)) => Ok(nvec.iter().any(|v| v == n)), (Number(n), NotEqual, NumberArray(nvec)) => Ok(nvec.iter().all(|v| v != n)), (Number(n), Equal, NumberComparisonArray(ncvec)) => { Self::eval_number_comparison_array(*n, ncvec) } _ => Err(types::InterpreterError { error_type: types::InterpreterErrorType::InvalidComparison, metadata: comparison.metadata.clone(), }), } } else { Ok(false) } } fn eval_if_condition( condition: &ast::IfCondition, ctx: &types::Context, ) -> Result<bool, types::InterpreterError> { for comparison in condition { let res = Self::eval_comparison(comparison, ctx)?; if !res { return Ok(false); } } Ok(true) } fn eval_if_statement( stmt: &ast::IfStatement, ctx: &types::Context, ) -> Result<bool, types::InterpreterError> { let cond_res = Self::eval_if_condition(&stmt.condition, ctx)?; if !cond_res { return Ok(false); } if let Some(ref nested) = stmt.nested { for nested_if in nested { let res = Self::eval_if_statement(nested_if, ctx)?; if res { return Ok(true); } } return Ok(false); } Ok(true) } fn eval_rule_statements( statements: &[ast::IfStatement], ctx: &types::Context, ) -> Result<bool, types::InterpreterError> { for stmt in statements { let res = Self::eval_if_statement(stmt, ctx)?; if res { return Ok(true); } } Ok(false) } #[inline] fn eval_rule( rule: &ast::Rule<O>, ctx: &types::Context, ) -> Result<bool, types::InterpreterError> { Self::eval_rule_statements(&rule.statements, ctx) } fn eval_program( program: &ast::Program<O>, ctx: &types::Context, ) -> Result<backend::BackendOutput<O>, types::InterpreterError> { for rule in &program.rules { let res = Self::eval_rule(rule, ctx)?; if res { return Ok(backend::BackendOutput { connector_selection: rule.connector_selection.clone(), rule_name: Some(rule.name.clone()), }); } } Ok(backend::BackendOutput { connector_selection: program.default_selection.clone(), rule_name: None, }) } } impl<O> EuclidBackend<O> for InterpreterBackend<O> where O: Clone, { type Error = types::InterpreterError; fn with_program(program: ast::Program<O>) -> Result<Self, Self::Error> { Ok(Self { program }) } fn execute(&self, input: inputs::BackendInput) -> Result<super::BackendOutput<O>, Self::Error> { let ctx: types::Context = input.into(); Self::eval_program(&self.program, &ctx) } }
crates/euclid/src/backend/interpreter.rs
euclid::src::backend::interpreter
1,287
true
// File: crates/euclid/src/backend/interpreter/types.rs // Module: euclid::src::backend::interpreter::types use std::{collections::HashMap, fmt, ops::Deref, string::ToString}; use serde::Serialize; use crate::{backend::inputs, frontend::ast::ValueType, types::EuclidKey}; #[derive(Debug, Clone, Serialize, thiserror::Error)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum InterpreterErrorType { #[error("Invalid key received '{0}'")] InvalidKey(String), #[error("Invalid Comparison")] InvalidComparison, } #[derive(Debug, Clone, Serialize, thiserror::Error)] pub struct InterpreterError { pub error_type: InterpreterErrorType, pub metadata: HashMap<String, serde_json::Value>, } impl fmt::Display for InterpreterError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { InterpreterErrorType::fmt(&self.error_type, f) } } pub struct Context(HashMap<String, Option<ValueType>>); impl Deref for Context { type Target = HashMap<String, Option<ValueType>>; fn deref(&self) -> &Self::Target { &self.0 } } impl From<inputs::BackendInput> for Context { fn from(input: inputs::BackendInput) -> Self { let ctx = HashMap::<String, Option<ValueType>>::from_iter([ ( EuclidKey::PaymentMethod.to_string(), input .payment_method .payment_method .map(|pm| ValueType::EnumVariant(pm.to_string())), ), ( EuclidKey::PaymentMethodType.to_string(), input .payment_method .payment_method_type .map(|pt| ValueType::EnumVariant(pt.to_string())), ), ( EuclidKey::AuthenticationType.to_string(), input .payment .authentication_type .map(|at| ValueType::EnumVariant(at.to_string())), ), ( EuclidKey::CaptureMethod.to_string(), input .payment .capture_method .map(|cm| ValueType::EnumVariant(cm.to_string())), ), ( EuclidKey::PaymentAmount.to_string(), Some(ValueType::Number(input.payment.amount)), ), ( EuclidKey::PaymentCurrency.to_string(), Some(ValueType::EnumVariant(input.payment.currency.to_string())), ), ]); Self(ctx) } }
crates/euclid/src/backend/interpreter/types.rs
euclid::src::backend::interpreter::types
536
true
// File: crates/euclid/src/backend/vir_interpreter/types.rs // Module: euclid::src::backend::vir_interpreter::types use rustc_hash::{FxHashMap, FxHashSet}; use crate::{ backend::inputs::BackendInput, dssa, types::{self, EuclidKey, EuclidValue, MetadataValue, NumValueRefinement, StrValue}, }; #[derive(Debug, Clone, serde::Serialize, thiserror::Error)] pub enum VirInterpreterError { #[error("Error when lowering the program: {0:?}")] LoweringError(dssa::types::AnalysisError), } pub struct Context { atomic_values: FxHashSet<EuclidValue>, numeric_values: FxHashMap<EuclidKey, EuclidValue>, } impl Context { pub fn check_presence(&self, value: &EuclidValue) -> bool { let key = value.get_key(); match key.key_type() { types::DataType::MetadataValue => self.atomic_values.contains(value), types::DataType::StrValue => self.atomic_values.contains(value), types::DataType::EnumVariant => self.atomic_values.contains(value), types::DataType::Number => { let ctx_num_value = self .numeric_values .get(&key) .and_then(|value| value.get_num_value()); value.get_num_value().zip(ctx_num_value).is_some_and( |(program_value, ctx_value)| { let program_num = program_value.number; let ctx_num = ctx_value.number; match &program_value.refinement { None => program_num == ctx_num, Some(NumValueRefinement::NotEqual) => ctx_num != program_num, Some(NumValueRefinement::GreaterThan) => ctx_num > program_num, Some(NumValueRefinement::GreaterThanEqual) => ctx_num >= program_num, Some(NumValueRefinement::LessThanEqual) => ctx_num <= program_num, Some(NumValueRefinement::LessThan) => ctx_num < program_num, } }, ) } } } pub fn from_input(input: BackendInput) -> Self { let payment = input.payment; let payment_method = input.payment_method; let meta_data = input.metadata; let acquirer_data = input.acquirer_data; let customer_device_data = input.customer_device_data; let issuer_data = input.issuer_data; let payment_mandate = input.mandate; let mut enum_values: FxHashSet<EuclidValue> = FxHashSet::from_iter([EuclidValue::PaymentCurrency(payment.currency)]); if let Some(pm) = payment_method.payment_method { enum_values.insert(EuclidValue::PaymentMethod(pm)); } if let Some(pmt) = payment_method.payment_method_type { enum_values.insert(EuclidValue::PaymentMethodType(pmt)); } if let Some(met) = meta_data { for (key, value) in met.into_iter() { enum_values.insert(EuclidValue::Metadata(MetadataValue { key, value })); } } if let Some(card_network) = payment_method.card_network { enum_values.insert(EuclidValue::CardNetwork(card_network)); } if let Some(at) = payment.authentication_type { enum_values.insert(EuclidValue::AuthenticationType(at)); } if let Some(capture_method) = payment.capture_method { enum_values.insert(EuclidValue::CaptureMethod(capture_method)); } if let Some(country) = payment.business_country { enum_values.insert(EuclidValue::BusinessCountry(country)); } if let Some(country) = payment.billing_country { enum_values.insert(EuclidValue::BillingCountry(country)); } if let Some(card_bin) = payment.card_bin { enum_values.insert(EuclidValue::CardBin(StrValue { value: card_bin })); } if let Some(business_label) = payment.business_label { enum_values.insert(EuclidValue::BusinessLabel(StrValue { value: business_label, })); } if let Some(setup_future_usage) = payment.setup_future_usage { enum_values.insert(EuclidValue::SetupFutureUsage(setup_future_usage)); } if let Some(payment_type) = payment_mandate.payment_type { enum_values.insert(EuclidValue::PaymentType(payment_type)); } if let Some(mandate_type) = payment_mandate.mandate_type { enum_values.insert(EuclidValue::MandateType(mandate_type)); } if let Some(mandate_acceptance_type) = payment_mandate.mandate_acceptance_type { enum_values.insert(EuclidValue::MandateAcceptanceType(mandate_acceptance_type)); } if let Some(acquirer_country) = acquirer_data.clone().and_then(|data| data.country) { enum_values.insert(EuclidValue::AcquirerCountry(acquirer_country)); } // Handle customer device data if let Some(device_data) = customer_device_data { if let Some(platform) = device_data.platform { enum_values.insert(EuclidValue::CustomerDevicePlatform(platform)); } if let Some(device_type) = device_data.device_type { enum_values.insert(EuclidValue::CustomerDeviceType(device_type)); } if let Some(display_size) = device_data.display_size { enum_values.insert(EuclidValue::CustomerDeviceDisplaySize(display_size)); } } // Handle issuer data if let Some(issuer) = issuer_data { if let Some(name) = issuer.name { enum_values.insert(EuclidValue::IssuerName(StrValue { value: name })); } if let Some(country) = issuer.country { enum_values.insert(EuclidValue::IssuerCountry(country)); } } let numeric_values: FxHashMap<EuclidKey, EuclidValue> = FxHashMap::from_iter([( EuclidKey::PaymentAmount, EuclidValue::PaymentAmount(types::NumValue { number: payment.amount, refinement: None, }), )]); Self { atomic_values: enum_values, numeric_values, } } }
crates/euclid/src/backend/vir_interpreter/types.rs
euclid::src::backend::vir_interpreter::types
1,326
true
// File: crates/euclid/src/dssa/state_machine.rs // Module: euclid::src::dssa::state_machine use super::types::EuclidAnalysable; use crate::{dssa::types, frontend::dir, types::Metadata}; #[derive(Debug, Clone, serde::Serialize, thiserror::Error)] #[serde(tag = "type", content = "info", rename_all = "snake_case")] pub enum StateMachineError { #[error("Index out of bounds: {0}")] IndexOutOfBounds(&'static str), } #[derive(Debug)] struct ComparisonStateMachine<'a> { values: &'a [dir::DirValue], logic: &'a dir::DirComparisonLogic, metadata: &'a Metadata, count: usize, ctx_idx: usize, } impl<'a> ComparisonStateMachine<'a> { #[inline] fn is_finished(&self) -> bool { self.count + 1 >= self.values.len() || matches!(self.logic, dir::DirComparisonLogic::NegativeConjunction) } #[inline] fn advance(&mut self) { if let dir::DirComparisonLogic::PositiveDisjunction = self.logic { self.count = (self.count + 1) % self.values.len(); } } #[inline] fn reset(&mut self) { self.count = 0; } #[inline] fn put(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> { if let dir::DirComparisonLogic::PositiveDisjunction = self.logic { *context .get_mut(self.ctx_idx) .ok_or(StateMachineError::IndexOutOfBounds( "in ComparisonStateMachine while indexing into context", ))? = types::ContextValue::assertion( self.values .get(self.count) .ok_or(StateMachineError::IndexOutOfBounds( "in ComparisonStateMachine while indexing into values", ))?, self.metadata, ); } Ok(()) } #[inline] fn push(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> { match self.logic { dir::DirComparisonLogic::PositiveDisjunction => { context.push(types::ContextValue::assertion( self.values .get(self.count) .ok_or(StateMachineError::IndexOutOfBounds( "in ComparisonStateMachine while pushing", ))?, self.metadata, )); } dir::DirComparisonLogic::NegativeConjunction => { context.push(types::ContextValue::negation(self.values, self.metadata)); } } Ok(()) } } #[derive(Debug)] struct ConditionStateMachine<'a> { state_machines: Vec<ComparisonStateMachine<'a>>, start_ctx_idx: usize, } impl<'a> ConditionStateMachine<'a> { fn new(condition: &'a [dir::DirComparison], start_idx: usize) -> Self { let mut machines = Vec::<ComparisonStateMachine<'a>>::with_capacity(condition.len()); let mut machine_idx = start_idx; for cond in condition { let machine = ComparisonStateMachine { values: &cond.values, logic: &cond.logic, metadata: &cond.metadata, count: 0, ctx_idx: machine_idx, }; machines.push(machine); machine_idx += 1; } Self { state_machines: machines, start_ctx_idx: start_idx, } } fn init(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> { for machine in &self.state_machines { machine.push(context)?; } Ok(()) } #[inline] fn destroy(&self, context: &mut types::ConjunctiveContext<'a>) { context.truncate(self.start_ctx_idx); } #[inline] fn is_finished(&self) -> bool { !self .state_machines .iter() .any(|machine| !machine.is_finished()) } #[inline] fn get_next_ctx_idx(&self) -> usize { self.start_ctx_idx + self.state_machines.len() } fn advance( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { for machine in self.state_machines.iter_mut().rev() { if machine.is_finished() { machine.reset(); machine.put(context)?; } else { machine.advance(); machine.put(context)?; break; } } Ok(()) } } #[derive(Debug)] struct IfStmtStateMachine<'a> { condition_machine: ConditionStateMachine<'a>, nested: Vec<&'a dir::DirIfStatement>, nested_idx: usize, } impl<'a> IfStmtStateMachine<'a> { fn new(stmt: &'a dir::DirIfStatement, ctx_start_idx: usize) -> Self { let condition_machine = ConditionStateMachine::new(&stmt.condition, ctx_start_idx); let nested: Vec<&'a dir::DirIfStatement> = match &stmt.nested { None => Vec::new(), Some(nested_stmts) => nested_stmts.iter().collect(), }; Self { condition_machine, nested, nested_idx: 0, } } fn init( &self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<Option<Self>, StateMachineError> { self.condition_machine.init(context)?; Ok(self .nested .first() .map(|nested| Self::new(nested, self.condition_machine.get_next_ctx_idx()))) } #[inline] fn is_finished(&self) -> bool { self.nested_idx + 1 >= self.nested.len() } #[inline] fn is_condition_machine_finished(&self) -> bool { self.condition_machine.is_finished() } #[inline] fn destroy(&self, context: &mut types::ConjunctiveContext<'a>) { self.condition_machine.destroy(context); } #[inline] fn advance_condition_machine( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { self.condition_machine.advance(context)?; Ok(()) } fn advance(&mut self) -> Result<Option<Self>, StateMachineError> { if self.nested.is_empty() { Ok(None) } else { self.nested_idx = (self.nested_idx + 1) % self.nested.len(); Ok(Some(Self::new( self.nested .get(self.nested_idx) .ok_or(StateMachineError::IndexOutOfBounds( "in IfStmtStateMachine while advancing", ))?, self.condition_machine.get_next_ctx_idx(), ))) } } } #[derive(Debug)] struct RuleStateMachine<'a> { connector_selection_data: &'a [(dir::DirValue, Metadata)], connectors_added: bool, if_stmt_machines: Vec<IfStmtStateMachine<'a>>, running_stack: Vec<IfStmtStateMachine<'a>>, } impl<'a> RuleStateMachine<'a> { fn new<O>( rule: &'a dir::DirRule<O>, connector_selection_data: &'a [(dir::DirValue, Metadata)], ) -> Self { let mut if_stmt_machines: Vec<IfStmtStateMachine<'a>> = Vec::with_capacity(rule.statements.len()); for stmt in rule.statements.iter().rev() { if_stmt_machines.push(IfStmtStateMachine::new( stmt, connector_selection_data.len(), )); } Self { connector_selection_data, connectors_added: false, if_stmt_machines, running_stack: Vec::new(), } } fn is_finished(&self) -> bool { self.if_stmt_machines.is_empty() && self.running_stack.is_empty() } fn init_next( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { if self.if_stmt_machines.is_empty() || !self.running_stack.is_empty() { return Ok(()); } if !self.connectors_added { for (dir_val, metadata) in self.connector_selection_data { context.push(types::ContextValue::assertion(dir_val, metadata)); } self.connectors_added = true; } context.truncate(self.connector_selection_data.len()); if let Some(mut next_running) = self.if_stmt_machines.pop() { while let Some(nested_running) = next_running.init(context)? { self.running_stack.push(next_running); next_running = nested_running; } self.running_stack.push(next_running); } Ok(()) } fn advance( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { let mut condition_machines_finished = true; for stmt_machine in self.running_stack.iter_mut().rev() { if !stmt_machine.is_condition_machine_finished() { condition_machines_finished = false; stmt_machine.advance_condition_machine(context)?; break; } else { stmt_machine.advance_condition_machine(context)?; } } if !condition_machines_finished { return Ok(()); } let mut maybe_next_running: Option<IfStmtStateMachine<'a>> = None; while let Some(last) = self.running_stack.last_mut() { if !last.is_finished() { maybe_next_running = last.advance()?; break; } else { last.destroy(context); self.running_stack.pop(); } } if let Some(mut next_running) = maybe_next_running { while let Some(nested_running) = next_running.init(context)? { self.running_stack.push(next_running); next_running = nested_running; } self.running_stack.push(next_running); } else { self.init_next(context)?; } Ok(()) } } #[derive(Debug)] pub struct RuleContextManager<'a> { context: types::ConjunctiveContext<'a>, machine: RuleStateMachine<'a>, init: bool, } impl<'a> RuleContextManager<'a> { pub fn new<O>( rule: &'a dir::DirRule<O>, connector_selection_data: &'a [(dir::DirValue, Metadata)], ) -> Self { Self { context: Vec::new(), machine: RuleStateMachine::new(rule, connector_selection_data), init: false, } } pub fn advance(&mut self) -> Result<Option<&types::ConjunctiveContext<'a>>, StateMachineError> { if !self.init { self.init = true; self.machine.init_next(&mut self.context)?; Ok(Some(&self.context)) } else if self.machine.is_finished() { Ok(None) } else { self.machine.advance(&mut self.context)?; if self.machine.is_finished() { Ok(None) } else { Ok(Some(&self.context)) } } } pub fn advance_mut( &mut self, ) -> Result<Option<&mut types::ConjunctiveContext<'a>>, StateMachineError> { if !self.init { self.init = true; self.machine.init_next(&mut self.context)?; Ok(Some(&mut self.context)) } else if self.machine.is_finished() { Ok(None) } else { self.machine.advance(&mut self.context)?; if self.machine.is_finished() { Ok(None) } else { Ok(Some(&mut self.context)) } } } } #[derive(Debug)] pub struct ProgramStateMachine<'a> { rule_machines: Vec<RuleStateMachine<'a>>, current_rule_machine: Option<RuleStateMachine<'a>>, is_init: bool, } impl<'a> ProgramStateMachine<'a> { pub fn new<O>( program: &'a dir::DirProgram<O>, connector_selection_data: &'a [Vec<(dir::DirValue, Metadata)>], ) -> Self { let mut rule_machines: Vec<RuleStateMachine<'a>> = program .rules .iter() .zip(connector_selection_data.iter()) .rev() .map(|(rule, connector_selection_data)| { RuleStateMachine::new(rule, connector_selection_data) }) .collect(); Self { current_rule_machine: rule_machines.pop(), rule_machines, is_init: false, } } pub fn is_finished(&self) -> bool { self.current_rule_machine .as_ref() .is_none_or(|rsm| rsm.is_finished()) && self.rule_machines.is_empty() } pub fn init( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { if !self.is_init { if let Some(rsm) = self.current_rule_machine.as_mut() { rsm.init_next(context)?; } self.is_init = true; } Ok(()) } pub fn advance( &mut self, context: &mut types::ConjunctiveContext<'a>, ) -> Result<(), StateMachineError> { if self .current_rule_machine .as_ref() .is_none_or(|rsm| rsm.is_finished()) { self.current_rule_machine = self.rule_machines.pop(); context.clear(); if let Some(rsm) = self.current_rule_machine.as_mut() { rsm.init_next(context)?; } } else if let Some(rsm) = self.current_rule_machine.as_mut() { rsm.advance(context)?; } Ok(()) } } pub struct AnalysisContextManager<'a> { context: types::ConjunctiveContext<'a>, machine: ProgramStateMachine<'a>, init: bool, } impl<'a> AnalysisContextManager<'a> { pub fn new<O>( program: &'a dir::DirProgram<O>, connector_selection_data: &'a [Vec<(dir::DirValue, Metadata)>], ) -> Self { let machine = ProgramStateMachine::new(program, connector_selection_data); let context: types::ConjunctiveContext<'a> = Vec::new(); Self { context, machine, init: false, } } pub fn advance(&mut self) -> Result<Option<&types::ConjunctiveContext<'a>>, StateMachineError> { if !self.init { self.init = true; self.machine.init(&mut self.context)?; Ok(Some(&self.context)) } else if self.machine.is_finished() { Ok(None) } else { self.machine.advance(&mut self.context)?; if self.machine.is_finished() { Ok(None) } else { Ok(Some(&self.context)) } } } } pub fn make_connector_selection_data<O: EuclidAnalysable>( program: &dir::DirProgram<O>, ) -> Vec<Vec<(dir::DirValue, Metadata)>> { program .rules .iter() .map(|rule| { rule.connector_selection .get_dir_value_for_analysis(rule.name.clone()) }) .collect() } #[cfg(all(test, feature = "ast_parser"))] mod tests { #![allow(clippy::expect_used)] use super::*; use crate::{dirval, frontend::ast, types::DummyOutput}; #[test] fn test_correct_contexts() { let program_str = r#" default: ["stripe", "adyen"] stripe_first: ["stripe", "adyen"] { payment_method = wallet { payment_method = (card, bank_redirect) { currency = USD currency = GBP } payment_method = pay_later { capture_method = automatic capture_method = manual } } payment_method = card { payment_method = (card, bank_redirect) & capture_method = (automatic, manual) { currency = (USD, GBP) } } } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let lowered = ast::lowering::lower_program(program).expect("Lowering"); let selection_data = make_connector_selection_data(&lowered); let mut state_machine = ProgramStateMachine::new(&lowered, &selection_data); let mut ctx: types::ConjunctiveContext<'_> = Vec::new(); state_machine.init(&mut ctx).expect("State machine init"); let expected_contexts: Vec<Vec<dir::DirValue>> = vec![ vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = Card), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = BankRedirect), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = Card), dirval!(PaymentCurrency = GBP), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = BankRedirect), dirval!(PaymentCurrency = GBP), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = PayLater), dirval!(CaptureMethod = Automatic), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = PayLater), dirval!(CaptureMethod = Manual), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Card), dirval!(CaptureMethod = Automatic), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Card), dirval!(CaptureMethod = Automatic), dirval!(PaymentCurrency = GBP), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Card), dirval!(CaptureMethod = Manual), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Card), dirval!(CaptureMethod = Manual), dirval!(PaymentCurrency = GBP), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = BankRedirect), dirval!(CaptureMethod = Automatic), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = BankRedirect), dirval!(CaptureMethod = Automatic), dirval!(PaymentCurrency = GBP), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = BankRedirect), dirval!(CaptureMethod = Manual), dirval!(PaymentCurrency = USD), ], vec![ dirval!("MetadataKey" = "stripe"), dirval!("MetadataKey" = "adyen"), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = BankRedirect), dirval!(CaptureMethod = Manual), dirval!(PaymentCurrency = GBP), ], ]; let mut expected_idx = 0usize; while !state_machine.is_finished() { let values = ctx .iter() .flat_map(|c| match c.value { types::CtxValueKind::Assertion(val) => vec![val], types::CtxValueKind::Negation(vals) => vals.iter().collect(), }) .collect::<Vec<&dir::DirValue>>(); assert_eq!( values, expected_contexts .get(expected_idx) .expect("Error deriving contexts") .iter() .collect::<Vec<&dir::DirValue>>() ); expected_idx += 1; state_machine .advance(&mut ctx) .expect("State Machine advance"); } assert_eq!(expected_idx, 14); let mut ctx_manager = AnalysisContextManager::new(&lowered, &selection_data); expected_idx = 0; while let Some(ctx) = ctx_manager.advance().expect("Context Manager Context") { let values = ctx .iter() .flat_map(|c| match c.value { types::CtxValueKind::Assertion(val) => vec![val], types::CtxValueKind::Negation(vals) => vals.iter().collect(), }) .collect::<Vec<&dir::DirValue>>(); assert_eq!( values, expected_contexts .get(expected_idx) .expect("Error deriving contexts") .iter() .collect::<Vec<&dir::DirValue>>() ); expected_idx += 1; } assert_eq!(expected_idx, 14); } }
crates/euclid/src/dssa/state_machine.rs
euclid::src::dssa::state_machine
4,790
true
// File: crates/euclid/src/dssa/types.rs // Module: euclid::src::dssa::types use std::{collections::HashMap, fmt}; use serde::Serialize; use crate::{ dssa::{self, graph}, frontend::{ast, dir}, types::{DataType, EuclidValue, Metadata}, }; pub trait EuclidAnalysable: Sized { fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(dir::DirValue, Metadata)>; } #[derive(Debug, Clone)] pub enum CtxValueKind<'a> { Assertion(&'a dir::DirValue), Negation(&'a [dir::DirValue]), } impl CtxValueKind<'_> { pub fn get_assertion(&self) -> Option<&dir::DirValue> { if let Self::Assertion(val) = self { Some(val) } else { None } } pub fn get_negation(&self) -> Option<&[dir::DirValue]> { if let Self::Negation(vals) = self { Some(vals) } else { None } } pub fn get_key(&self) -> Option<dir::DirKey> { match self { Self::Assertion(val) => Some(val.get_key()), Self::Negation(vals) => vals.first().map(|v| (*v).get_key()), } } } #[derive(Debug, Clone)] pub struct ContextValue<'a> { pub value: CtxValueKind<'a>, pub metadata: &'a Metadata, } impl<'a> ContextValue<'a> { #[inline] pub fn assertion(value: &'a dir::DirValue, metadata: &'a Metadata) -> Self { Self { value: CtxValueKind::Assertion(value), metadata, } } #[inline] pub fn negation(values: &'a [dir::DirValue], metadata: &'a Metadata) -> Self { Self { value: CtxValueKind::Negation(values), metadata, } } } pub type ConjunctiveContext<'a> = Vec<ContextValue<'a>>; #[derive(Clone, Serialize)] pub enum AnalyzeResult { AllOk, } #[derive(Debug, Clone, Serialize, thiserror::Error)] pub struct AnalysisError { #[serde(flatten)] pub error_type: AnalysisErrorType, pub metadata: Metadata, } impl fmt::Display for AnalysisError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.error_type.fmt(f) } } #[derive(Debug, Clone, Serialize)] pub struct ValueData { pub value: dir::DirValue, pub metadata: Metadata, } #[derive(Debug, Clone, Serialize, thiserror::Error)] #[serde(tag = "type", content = "info", rename_all = "snake_case")] pub enum AnalysisErrorType { #[error("Invalid program key given: '{0}'")] InvalidKey(String), #[error("Invalid variant '{got}' received for key '{key}'")] InvalidVariant { key: String, expected: Vec<String>, got: String, }, #[error( "Invalid data type for value '{}' (expected {expected}, got {got})", key )] InvalidType { key: String, expected: DataType, got: DataType, }, #[error("Invalid comparison '{operator:?}' for value type {value_type}")] InvalidComparison { operator: ast::ComparisonType, value_type: DataType, }, #[error("Invalid value received for length as '{value}: {:?}'", message)] InvalidValue { key: dir::DirKeyKind, value: String, message: Option<String>, }, #[error("Conflicting assertions received for key '{}'", .key.kind)] ConflictingAssertions { key: dir::DirKey, values: Vec<ValueData>, }, #[error("Key '{}' exhaustively negated", .key.kind)] ExhaustiveNegation { key: dir::DirKey, metadata: Vec<Metadata>, }, #[error("The condition '{value}' was asserted and negated in the same condition")] NegatedAssertion { value: dir::DirValue, assertion_metadata: Metadata, negation_metadata: Metadata, }, #[error("Graph analysis error: {0:#?}")] GraphAnalysis( graph::AnalysisError<dir::DirValue>, hyperswitch_constraint_graph::Memoization<dir::DirValue>, ), #[error("State machine error")] StateMachine(dssa::state_machine::StateMachineError), #[error("Unsupported program key '{0}'")] UnsupportedProgramKey(dir::DirKeyKind), #[error("Ran into an unimplemented feature")] NotImplemented, #[error("The payment method type is not supported under the payment method")] NotSupported, } #[derive(Debug, Clone)] pub enum ValueType { EnumVariants(Vec<EuclidValue>), Number, } impl EuclidAnalysable for common_enums::AuthenticationType { fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(dir::DirValue, Metadata)> { let auth = self.to_string(); let dir_value = match self { Self::ThreeDs => dir::DirValue::AuthenticationType(Self::ThreeDs), Self::NoThreeDs => dir::DirValue::AuthenticationType(Self::NoThreeDs), }; vec![( dir_value, HashMap::from_iter([( "AUTHENTICATION_TYPE".to_string(), serde_json::json!({ "rule_name": rule_name, "Authentication_type": auth, }), )]), )] } }
crates/euclid/src/dssa/types.rs
euclid::src::dssa::types
1,233
true
// File: crates/euclid/src/dssa/analyzer.rs // Module: euclid::src::dssa::analyzer //! Static Analysis for the Euclid Rule DSL //! //! Exposes certain functions that can be used to perform static analysis over programs //! in the Euclid Rule DSL. These include standard control flow analyses like testing //! conflicting assertions, to Domain Specific Analyses making use of the //! [`Knowledge Graph Framework`](crate::dssa::graph). use hyperswitch_constraint_graph::{ConstraintGraph, Memoization}; use rustc_hash::{FxHashMap, FxHashSet}; use crate::{ dssa::{ graph::CgraphExt, state_machine, truth, types::{self, EuclidAnalysable}, }, frontend::{ ast, dir::{self, EuclidDirFilter}, vir, }, types::{DataType, Metadata}, }; /// Analyses conflicting assertions on the same key in a conjunctive context. /// /// For example, /// ```notrust /// payment_method = card && ... && payment_method = bank_debit /// ```notrust /// This is a condition that will never evaluate to `true` given a single /// payment method and needs to be caught in analysis. pub fn analyze_conflicting_assertions( keywise_assertions: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>, assertion_metadata: &FxHashMap<&dir::DirValue, &Metadata>, ) -> Result<(), types::AnalysisError> { for (key, value_set) in keywise_assertions { if value_set.len() > 1 { let err_type = types::AnalysisErrorType::ConflictingAssertions { key: key.clone(), values: value_set .iter() .map(|val| types::ValueData { value: (*val).clone(), metadata: assertion_metadata .get(val) .map(|meta| (*meta).clone()) .unwrap_or_default(), }) .collect(), }; Err(types::AnalysisError { error_type: err_type, metadata: Default::default(), })?; } } Ok(()) } /// Analyses exhaustive negations on the same key in a conjunctive context. /// /// For example, /// ```notrust /// authentication_type /= three_ds && ... && authentication_type /= no_three_ds /// ```notrust /// This is a condition that will never evaluate to `true` given any authentication_type /// since all the possible values authentication_type can take have been negated. pub fn analyze_exhaustive_negations( keywise_negations: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>, keywise_negation_metadata: &FxHashMap<dir::DirKey, Vec<&Metadata>>, ) -> Result<(), types::AnalysisError> { for (key, negation_set) in keywise_negations { let mut value_set = if let Some(set) = key.kind.get_value_set() { set } else { continue; }; value_set.retain(|val| !negation_set.contains(val)); if value_set.is_empty() { let error_type = types::AnalysisErrorType::ExhaustiveNegation { key: key.clone(), metadata: keywise_negation_metadata .get(key) .cloned() .unwrap_or_default() .iter() .copied() .cloned() .collect(), }; Err(types::AnalysisError { error_type, metadata: Default::default(), })?; } } Ok(()) } fn analyze_negated_assertions( keywise_assertions: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>, assertion_metadata: &FxHashMap<&dir::DirValue, &Metadata>, keywise_negations: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>, negation_metadata: &FxHashMap<&dir::DirValue, &Metadata>, ) -> Result<(), types::AnalysisError> { for (key, negation_set) in keywise_negations { let assertion_set = if let Some(set) = keywise_assertions.get(key) { set } else { continue; }; let intersection = negation_set & assertion_set; intersection.iter().next().map_or(Ok(()), |val| { let error_type = types::AnalysisErrorType::NegatedAssertion { value: (*val).clone(), assertion_metadata: assertion_metadata .get(*val) .copied() .cloned() .unwrap_or_default(), negation_metadata: negation_metadata .get(*val) .copied() .cloned() .unwrap_or_default(), }; Err(types::AnalysisError { error_type, metadata: Default::default(), }) })?; } Ok(()) } fn perform_condition_analyses( context: &types::ConjunctiveContext<'_>, ) -> Result<(), types::AnalysisError> { let mut assertion_metadata: FxHashMap<&dir::DirValue, &Metadata> = FxHashMap::default(); let mut keywise_assertions: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> = FxHashMap::default(); let mut negation_metadata: FxHashMap<&dir::DirValue, &Metadata> = FxHashMap::default(); let mut keywise_negation_metadata: FxHashMap<dir::DirKey, Vec<&Metadata>> = FxHashMap::default(); let mut keywise_negations: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> = FxHashMap::default(); for ctx_val in context { let key = if let Some(k) = ctx_val.value.get_key() { k } else { continue; }; if let dir::DirKeyKind::Connector = key.kind { continue; } if !matches!(key.kind.get_type(), DataType::EnumVariant) { continue; } match ctx_val.value { types::CtxValueKind::Assertion(val) => { keywise_assertions .entry(key.clone()) .or_default() .insert(val); assertion_metadata.insert(val, ctx_val.metadata); } types::CtxValueKind::Negation(vals) => { let negation_set = keywise_negations.entry(key.clone()).or_default(); for val in vals { negation_set.insert(val); negation_metadata.insert(val, ctx_val.metadata); } keywise_negation_metadata .entry(key.clone()) .or_default() .push(ctx_val.metadata); } } } analyze_conflicting_assertions(&keywise_assertions, &assertion_metadata)?; analyze_exhaustive_negations(&keywise_negations, &keywise_negation_metadata)?; analyze_negated_assertions( &keywise_assertions, &assertion_metadata, &keywise_negations, &negation_metadata, )?; Ok(()) } fn perform_context_analyses( context: &types::ConjunctiveContext<'_>, knowledge_graph: &ConstraintGraph<dir::DirValue>, ) -> Result<(), types::AnalysisError> { perform_condition_analyses(context)?; let mut memo = Memoization::new(); knowledge_graph .perform_context_analysis(context, &mut memo, None) .map_err(|err| types::AnalysisError { error_type: types::AnalysisErrorType::GraphAnalysis(err, memo), metadata: Default::default(), })?; Ok(()) } pub fn analyze<O: EuclidAnalysable + EuclidDirFilter>( program: ast::Program<O>, knowledge_graph: Option<&ConstraintGraph<dir::DirValue>>, ) -> Result<vir::ValuedProgram<O>, types::AnalysisError> { let dir_program = ast::lowering::lower_program(program)?; let selection_data = state_machine::make_connector_selection_data(&dir_program); let mut ctx_manager = state_machine::AnalysisContextManager::new(&dir_program, &selection_data); while let Some(ctx) = ctx_manager.advance().map_err(|err| types::AnalysisError { metadata: Default::default(), error_type: types::AnalysisErrorType::StateMachine(err), })? { perform_context_analyses(ctx, knowledge_graph.unwrap_or(&truth::ANALYSIS_GRAPH))?; } dir::lowering::lower_program(dir_program) } #[cfg(all(test, feature = "ast_parser"))] mod tests { #![allow(clippy::panic, clippy::expect_used)] use std::{ops::Deref, sync::Weak}; use euclid_macros::knowledge; use hyperswitch_constraint_graph as cgraph; use super::*; use crate::{ dirval, dssa::graph::{self, euclid_graph_prelude}, types::DummyOutput, }; #[test] fn test_conflicting_assertion_detection() { let program_str = r#" default: ["stripe", "adyen"] stripe_first: ["stripe", "adyen"] { payment_method = wallet { amount > 500 & capture_method = automatic amount < 500 & payment_method = card } } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let analysis_result = analyze(program, None); if let Err(types::AnalysisError { error_type: types::AnalysisErrorType::ConflictingAssertions { key, values }, .. }) = analysis_result { assert!( matches!(key.kind, dir::DirKeyKind::PaymentMethod), "Key should be payment_method" ); let values: Vec<dir::DirValue> = values.into_iter().map(|v| v.value).collect(); assert_eq!(values.len(), 2, "There should be 2 conflicting conditions"); assert!( values.contains(&dirval!(PaymentMethod = Wallet)), "Condition should include payment_method = wallet" ); assert!( values.contains(&dirval!(PaymentMethod = Card)), "Condition should include payment_method = card" ); } else { panic!("Did not receive conflicting assertions error"); } } #[test] fn test_exhaustive_negation_detection() { let program_str = r#" default: ["stripe"] rule_1: ["adyen"] { payment_method /= wallet { capture_method = manual & payment_method /= card { authentication_type = three_ds & payment_method /= pay_later { amount > 1000 & payment_method /= bank_redirect { payment_method /= crypto & payment_method /= bank_debit & payment_method /= bank_transfer & payment_method /= upi & payment_method /= reward & payment_method /= voucher & payment_method /= gift_card & payment_method /= card_redirect & payment_method /= real_time_payment & payment_method /= open_banking & payment_method /= mobile_payment } } } } } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let analysis_result = analyze(program, None); if let Err(types::AnalysisError { error_type: types::AnalysisErrorType::ExhaustiveNegation { key, .. }, .. }) = analysis_result { assert!( matches!(key.kind, dir::DirKeyKind::PaymentMethod), "Expected key to be payment_method" ); } else { panic!("Expected exhaustive negation error"); } } #[test] fn test_negated_assertions_detection() { let program_str = r#" default: ["stripe"] rule_1: ["adyen"] { payment_method = wallet { amount > 500 { capture_method = automatic } amount < 501 { payment_method /= wallet } } } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program"); let analysis_result = analyze(program, None); if let Err(types::AnalysisError { error_type: types::AnalysisErrorType::NegatedAssertion { value, .. }, .. }) = analysis_result { assert_eq!( value, dirval!(PaymentMethod = Wallet), "Expected to catch payment_method = wallet as conflict" ); } else { panic!("Expected negated assertion error"); } } #[test] fn test_negation_graph_analysis() { let graph = knowledge! { CaptureMethod(Automatic) ->> PaymentMethod(Card); }; let program_str = r#" default: ["stripe"] rule_1: ["adyen"] { amount > 500 { payment_method = pay_later } amount < 500 { payment_method /= wallet & payment_method /= pay_later } } "#; let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Graph"); let analysis_result = analyze(program, Some(&graph)); let error_type = match analysis_result { Err(types::AnalysisError { error_type, .. }) => error_type, _ => panic!("Error_type not found"), }; let a_err = match error_type { types::AnalysisErrorType::GraphAnalysis(trace, memo) => (trace, memo), _ => panic!("Graph Analysis not found"), }; let (trace, metadata) = match a_err.0 { graph::AnalysisError::NegationTrace { trace, metadata } => (trace, metadata), _ => panic!("Negation Trace not found"), }; let predecessor = match Weak::upgrade(&trace) .expect("Expected Arc not found") .deref() .clone() { cgraph::AnalysisTrace::Value { predecessors, .. } => { let _value = cgraph::NodeValue::Value(dir::DirValue::PaymentMethod( dir::enums::PaymentMethod::Card, )); let _relation = cgraph::Relation::Positive; predecessors } _ => panic!("Expected Negation Trace for payment method = card"), }; let pred = match predecessor { Some(cgraph::error::ValueTracePredecessor::Mandatory(predecessor)) => predecessor, _ => panic!("No predecessor found"), }; assert_eq!( metadata.len(), 2, "Expected two metadats for wallet and pay_later" ); assert!(matches!( *Weak::upgrade(&pred) .expect("Expected Arc not found") .deref(), cgraph::AnalysisTrace::Value { value: cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( dir::enums::CaptureMethod::Automatic )), relation: cgraph::Relation::Positive, info: None, metadata: None, predecessors: None, } )); } }
crates/euclid/src/dssa/analyzer.rs
euclid::src::dssa::analyzer
3,271
true
// File: crates/euclid/src/dssa/graph.rs // Module: euclid::src::dssa::graph use std::{fmt::Debug, sync::Weak}; use hyperswitch_constraint_graph as cgraph; use rustc_hash::{FxHashMap, FxHashSet}; use crate::{ dssa::types, frontend::dir, types::{DataType, Metadata}, }; pub mod euclid_graph_prelude { pub use hyperswitch_constraint_graph as cgraph; pub use rustc_hash::{FxHashMap, FxHashSet}; pub use strum::EnumIter; pub use crate::{ dssa::graph::*, frontend::dir::{enums::*, DirKey, DirKeyKind, DirValue}, types::*, }; } impl cgraph::KeyNode for dir::DirKey {} impl cgraph::NodeViz for dir::DirKey { fn viz(&self) -> String { self.kind.to_string() } } impl cgraph::ValueNode for dir::DirValue { type Key = dir::DirKey; fn get_key(&self) -> Self::Key { Self::get_key(self) } } impl cgraph::NodeViz for dir::DirValue { fn viz(&self) -> String { match self { Self::PaymentMethod(pm) => pm.to_string(), Self::CardBin(bin) => bin.value.clone(), Self::CardType(ct) => ct.to_string(), Self::CardNetwork(cn) => cn.to_string(), Self::PayLaterType(plt) => plt.to_string(), Self::WalletType(wt) => wt.to_string(), Self::UpiType(ut) => ut.to_string(), Self::BankTransferType(btt) => btt.to_string(), Self::BankRedirectType(brt) => brt.to_string(), Self::BankDebitType(bdt) => bdt.to_string(), Self::CryptoType(ct) => ct.to_string(), Self::RewardType(rt) => rt.to_string(), Self::PaymentAmount(amt) => amt.number.to_string(), Self::PaymentCurrency(curr) => curr.to_string(), Self::AuthenticationType(at) => at.to_string(), Self::CaptureMethod(cm) => cm.to_string(), Self::BusinessCountry(bc) => bc.to_string(), Self::BillingCountry(bc) => bc.to_string(), Self::Connector(conn) => conn.connector.to_string(), Self::MetaData(mv) => format!("[{} = {}]", mv.key, mv.value), Self::MandateAcceptanceType(mat) => mat.to_string(), Self::MandateType(mt) => mt.to_string(), Self::PaymentType(pt) => pt.to_string(), Self::VoucherType(vt) => vt.to_string(), Self::GiftCardType(gct) => gct.to_string(), Self::BusinessLabel(bl) => bl.value.to_string(), Self::SetupFutureUsage(sfu) => sfu.to_string(), Self::CardRedirectType(crt) => crt.to_string(), Self::RealTimePaymentType(rtpt) => rtpt.to_string(), Self::OpenBankingType(ob) => ob.to_string(), Self::MobilePaymentType(mpt) => mpt.to_string(), Self::IssuerName(issuer_name) => issuer_name.value.clone(), Self::IssuerCountry(issuer_country) => issuer_country.to_string(), Self::CustomerDevicePlatform(customer_device_platform) => { customer_device_platform.to_string() } Self::CustomerDeviceType(customer_device_type) => customer_device_type.to_string(), Self::CustomerDeviceDisplaySize(customer_device_display_size) => { customer_device_display_size.to_string() } Self::AcquirerCountry(acquirer_country) => acquirer_country.to_string(), Self::AcquirerFraudRate(acquirer_fraud_rate) => acquirer_fraud_rate.number.to_string(), } } } #[derive(Debug, Clone, serde::Serialize)] #[serde(tag = "type", content = "details", rename_all = "snake_case")] pub enum AnalysisError<V: cgraph::ValueNode> { Graph(cgraph::GraphError<V>), AssertionTrace { trace: Weak<cgraph::AnalysisTrace<V>>, metadata: Metadata, }, NegationTrace { trace: Weak<cgraph::AnalysisTrace<V>>, metadata: Vec<Metadata>, }, } impl<V: cgraph::ValueNode> AnalysisError<V> { fn assertion_from_graph_error(metadata: &Metadata, graph_error: cgraph::GraphError<V>) -> Self { match graph_error { cgraph::GraphError::AnalysisError(trace) => Self::AssertionTrace { trace, metadata: metadata.clone(), }, other => Self::Graph(other), } } fn negation_from_graph_error( metadata: Vec<&Metadata>, graph_error: cgraph::GraphError<V>, ) -> Self { match graph_error { cgraph::GraphError::AnalysisError(trace) => Self::NegationTrace { trace, metadata: metadata.iter().map(|m| (*m).clone()).collect(), }, other => Self::Graph(other), } } } #[derive(Debug)] pub struct AnalysisContext { keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>>, } impl AnalysisContext { pub fn from_dir_values(vals: impl IntoIterator<Item = dir::DirValue>) -> Self { let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> = FxHashMap::default(); for dir_val in vals { let key = dir_val.get_key(); let set = keywise_values.entry(key).or_default(); set.insert(dir_val); } Self { keywise_values } } pub fn insert(&mut self, value: dir::DirValue) { self.keywise_values .entry(value.get_key()) .or_default() .insert(value); } pub fn remove(&mut self, value: dir::DirValue) { let set = self.keywise_values.entry(value.get_key()).or_default(); set.remove(&value); if set.is_empty() { self.keywise_values.remove(&value.get_key()); } } } impl cgraph::CheckingContext for AnalysisContext { type Value = dir::DirValue; fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self where L: Into<Self::Value>, { let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> = FxHashMap::default(); for dir_val in vals.into_iter().map(L::into) { let key = dir_val.get_key(); let set = keywise_values.entry(key).or_default(); set.insert(dir_val); } Self { keywise_values } } fn check_presence( &self, value: &cgraph::NodeValue<dir::DirValue>, strength: cgraph::Strength, ) -> bool { match value { cgraph::NodeValue::Key(k) => { self.keywise_values.contains_key(k) || matches!(strength, cgraph::Strength::Weak) } cgraph::NodeValue::Value(val) => { let key = val.get_key(); let value_set = if let Some(set) = self.keywise_values.get(&key) { set } else { return matches!(strength, cgraph::Strength::Weak); }; match key.kind.get_type() { DataType::EnumVariant | DataType::StrValue | DataType::MetadataValue => { value_set.contains(val) } DataType::Number => val.get_num_value().is_some_and(|num_val| { value_set.iter().any(|ctx_val| { ctx_val .get_num_value() .is_some_and(|ctx_num_val| num_val.fits(&ctx_num_val)) }) }), } } } } fn get_values_by_key( &self, key: &<Self::Value as cgraph::ValueNode>::Key, ) -> Option<Vec<Self::Value>> { self.keywise_values .get(key) .map(|set| set.iter().cloned().collect()) } } pub trait CgraphExt { fn key_analysis( &self, key: dir::DirKey, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>>; fn value_analysis( &self, val: dir::DirValue, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>>; fn check_value_validity( &self, val: dir::DirValue, analysis_ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<bool, cgraph::GraphError<dir::DirValue>>; fn key_value_analysis( &self, val: dir::DirValue, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>>; fn assertion_analysis( &self, positive_ctx: &[(&dir::DirValue, &Metadata)], analysis_ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>>; fn negation_analysis( &self, negative_ctx: &[(&[dir::DirValue], &Metadata)], analysis_ctx: &mut AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>>; fn perform_context_analysis( &self, ctx: &types::ConjunctiveContext<'_>, memo: &mut cgraph::Memoization<dir::DirValue>, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>>; } impl CgraphExt for cgraph::ConstraintGraph<dir::DirValue> { fn key_analysis( &self, key: dir::DirKey, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>> { self.value_map .get(&cgraph::NodeValue::Key(key)) .map_or(Ok(()), |node_id| { self.check_node( ctx, *node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, memo, cycle_map, domains, ) }) } fn value_analysis( &self, val: dir::DirValue, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>> { self.value_map .get(&cgraph::NodeValue::Value(val)) .map_or(Ok(()), |node_id| { self.check_node( ctx, *node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, memo, cycle_map, domains, ) }) } fn check_value_validity( &self, val: dir::DirValue, analysis_ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<bool, cgraph::GraphError<dir::DirValue>> { let maybe_node_id = self.value_map.get(&cgraph::NodeValue::Value(val)); let node_id = if let Some(nid) = maybe_node_id { nid } else { return Ok(false); }; let result = self.check_node( analysis_ctx, *node_id, cgraph::Relation::Positive, cgraph::Strength::Weak, memo, cycle_map, domains, ); match result { Ok(_) => Ok(true), Err(e) => { e.get_analysis_trace()?; Ok(false) } } } fn key_value_analysis( &self, val: dir::DirValue, ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), cgraph::GraphError<dir::DirValue>> { self.key_analysis(val.get_key(), ctx, memo, cycle_map, domains) .and_then(|_| self.value_analysis(val, ctx, memo, cycle_map, domains)) } fn assertion_analysis( &self, positive_ctx: &[(&dir::DirValue, &Metadata)], analysis_ctx: &AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>> { positive_ctx.iter().try_for_each(|(value, metadata)| { self.key_value_analysis((*value).clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| AnalysisError::assertion_from_graph_error(metadata, e)) }) } fn negation_analysis( &self, negative_ctx: &[(&[dir::DirValue], &Metadata)], analysis_ctx: &mut AnalysisContext, memo: &mut cgraph::Memoization<dir::DirValue>, cycle_map: &mut cgraph::CycleCheck, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>> { let mut keywise_metadata: FxHashMap<dir::DirKey, Vec<&Metadata>> = FxHashMap::default(); let mut keywise_negation: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> = FxHashMap::default(); for (values, metadata) in negative_ctx { let mut metadata_added = false; for dir_value in *values { if !metadata_added { keywise_metadata .entry(dir_value.get_key()) .or_default() .push(metadata); metadata_added = true; } keywise_negation .entry(dir_value.get_key()) .or_default() .insert(dir_value); } } for (key, negation_set) in keywise_negation { let all_metadata = keywise_metadata.remove(&key).unwrap_or_default(); let first_metadata = all_metadata.first().copied().cloned().unwrap_or_default(); self.key_analysis(key.clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| AnalysisError::assertion_from_graph_error(&first_metadata, e))?; let mut value_set = if let Some(set) = key.kind.get_value_set() { set } else { continue; }; value_set.retain(|v| !negation_set.contains(v)); for value in value_set { analysis_ctx.insert(value.clone()); self.value_analysis(value.clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| { AnalysisError::negation_from_graph_error(all_metadata.clone(), e) })?; analysis_ctx.remove(value); } } Ok(()) } fn perform_context_analysis( &self, ctx: &types::ConjunctiveContext<'_>, memo: &mut cgraph::Memoization<dir::DirValue>, domains: Option<&[String]>, ) -> Result<(), AnalysisError<dir::DirValue>> { let mut analysis_ctx = AnalysisContext::from_dir_values( ctx.iter() .filter_map(|ctx_val| ctx_val.value.get_assertion().cloned()), ); let positive_ctx = ctx .iter() .filter_map(|ctx_val| { ctx_val .value .get_assertion() .map(|val| (val, ctx_val.metadata)) }) .collect::<Vec<_>>(); self.assertion_analysis( &positive_ctx, &analysis_ctx, memo, &mut cgraph::CycleCheck::new(), domains, )?; let negative_ctx = ctx .iter() .filter_map(|ctx_val| { ctx_val .value .get_negation() .map(|vals| (vals, ctx_val.metadata)) }) .collect::<Vec<_>>(); self.negation_analysis( &negative_ctx, &mut analysis_ctx, memo, &mut cgraph::CycleCheck::new(), domains, )?; Ok(()) } } #[cfg(test)] mod test { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::ops::Deref; use euclid_macros::knowledge; use hyperswitch_constraint_graph::CycleCheck; use super::*; use crate::{dirval, frontend::dir::enums}; #[test] fn test_strong_positive_relation_success() { let graph = knowledge! { PaymentMethod(Card) ->> CaptureMethod(Automatic); PaymentMethod(not Wallet) & PaymentMethod(not PayLater) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Card), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_strong_positive_relation_failure() { let graph = knowledge! { PaymentMethod(Card) ->> CaptureMethod(Automatic); PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([dirval!(CaptureMethod = Automatic)]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_strong_negative_relation_success() { let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Card), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_strong_negative_relation_failure() { let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Wallet), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_normal_one_of_failure() { let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(Wallet) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = PayLater), ]), memo, &mut CycleCheck::new(), None, ); assert!(matches!( *Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected Arc"), cgraph::AnalysisTrace::Value { predecessors: Some(cgraph::error::ValueTracePredecessor::OneOf(_)), .. } )); } #[test] fn test_all_aggregator_success() { let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(PaymentMethod = Card), dirval!(CaptureMethod = Automatic), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_all_aggregator_failure() { let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = PayLater), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_all_aggregator_mandatory_failure() { let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; let mut memo = cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = PayLater), ]), &mut memo, &mut CycleCheck::new(), None, ); assert!(matches!( *Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected Arc"), cgraph::AnalysisTrace::Value { predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(_)), .. } )); } #[test] fn test_in_aggregator_success() { let graph = knowledge! { PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Wallet), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_in_aggregator_failure() { let graph = knowledge! { PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = PayLater), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_not_in_aggregator_success() { let graph = knowledge! { PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = PayLater), dirval!(PaymentMethod = BankRedirect), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_not_in_aggregator_failure() { let graph = knowledge! { PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = PayLater), dirval!(PaymentMethod = BankRedirect), dirval!(PaymentMethod = Card), ]), memo, &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_in_aggregator_failure_trace() { let graph = knowledge! { PaymentMethod(in [Card, Wallet]) ->> CaptureMethod(Automatic); }; let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(CaptureMethod = Automatic), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = PayLater), ]), memo, &mut CycleCheck::new(), None, ); if let cgraph::AnalysisTrace::Value { predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(agg_error)), .. } = Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected arc") .deref() { assert!(matches!( *Weak::upgrade(agg_error.deref()).expect("Expected Arc"), cgraph::AnalysisTrace::InAggregation { found: Some(dir::DirValue::PaymentMethod(enums::PaymentMethod::PayLater)), .. } )); } else { panic!("Failed unwrapping OnlyInAggregation trace from AnalysisTrace"); } } #[test] fn test_memoization_in_kgraph() { let mut builder = cgraph::ConstraintGraphBuilder::new(); let _node_1 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), None, None::<()>, ); let _node_2 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::BillingCountry(enums::BillingCountry::India)), None, None::<()>, ); let _node_3 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::BusinessCountry( enums::BusinessCountry::UnitedStatesOfAmerica, )), None, None::<()>, ); let mut memo = cgraph::Memoization::new(); let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( _node_1, _node_2, cgraph::Strength::Strong, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_2 = builder .make_edge( _node_2, _node_3, cgraph::Strength::Strong, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to an edge"); let graph = builder.build(); let _result = graph.key_value_analysis( dirval!(BusinessCountry = UnitedStatesOfAmerica), &AnalysisContext::from_dir_values([ dirval!(PaymentMethod = Wallet), dirval!(BillingCountry = India), dirval!(BusinessCountry = UnitedStatesOfAmerica), ]), &mut memo, &mut cycle_map, None, ); let _answer = memo .get(&( _node_3, cgraph::Relation::Positive, cgraph::Strength::Strong, )) .expect("Memoization not workng"); matches!(_answer, Ok(())); } #[test] fn test_cycle_resolution_in_graph() { let mut builder = cgraph::ConstraintGraphBuilder::new(); let _node_1 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), None, None::<()>, ); let _node_2 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), None, None::<()>, ); let mut memo = cgraph::Memoization::new(); let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( _node_1, _node_2, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_2 = builder .make_edge( _node_2, _node_1, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to an edge"); let graph = builder.build(); let _result = graph.key_value_analysis( dirval!(PaymentMethod = Wallet), &AnalysisContext::from_dir_values([ dirval!(PaymentMethod = Wallet), dirval!(PaymentMethod = Card), ]), &mut memo, &mut cycle_map, None, ); assert!(_result.is_ok()); } #[test] fn test_cycle_resolution_in_graph1() { let mut builder = cgraph::ConstraintGraphBuilder::new(); let _node_1 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( enums::CaptureMethod::Automatic, )), None, None::<()>, ); let _node_2 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), None, None::<()>, ); let _node_3 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), None, None::<()>, ); let mut memo = cgraph::Memoization::new(); let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( _node_1, _node_2, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_2 = builder .make_edge( _node_1, _node_3, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_3 = builder .make_edge( _node_2, _node_1, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_4 = builder .make_edge( _node_3, _node_1, cgraph::Strength::Strong, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let graph = builder.build(); let _result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Wallet), dirval!(CaptureMethod = Automatic), ]), &mut memo, &mut cycle_map, None, ); assert!(_result.is_ok()); } #[test] fn test_cycle_resolution_in_graph2() { let mut builder = cgraph::ConstraintGraphBuilder::new(); let _node_0 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::BillingCountry( enums::BillingCountry::Afghanistan, )), None, None::<()>, ); let _node_1 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( enums::CaptureMethod::Automatic, )), None, None::<()>, ); let _node_2 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), None, None::<()>, ); let _node_3 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), None, None::<()>, ); let _node_4 = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentCurrency(enums::PaymentCurrency::USD)), None, None::<()>, ); let mut memo = cgraph::Memoization::new(); let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( _node_0, _node_1, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_2 = builder .make_edge( _node_1, _node_2, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_3 = builder .make_edge( _node_1, _node_3, cgraph::Strength::Weak, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_4 = builder .make_edge( _node_3, _node_4, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_5 = builder .make_edge( _node_2, _node_4, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_6 = builder .make_edge( _node_4, _node_1, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_7 = builder .make_edge( _node_4, _node_0, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let graph = builder.build(); let _result = graph.key_value_analysis( dirval!(BillingCountry = Afghanistan), &AnalysisContext::from_dir_values([ dirval!(PaymentCurrency = USD), dirval!(PaymentMethod = Card), dirval!(PaymentMethod = Wallet), dirval!(CaptureMethod = Automatic), dirval!(BillingCountry = Afghanistan), ]), &mut memo, &mut cycle_map, None, ); assert!(_result.is_ok()); } }
crates/euclid/src/dssa/graph.rs
euclid::src::dssa::graph
8,128
true
// File: crates/euclid/src/dssa/utils.rs // Module: euclid::src::dssa::utils pub struct Unpacker;
crates/euclid/src/dssa/utils.rs
euclid::src::dssa::utils
32
true
// File: crates/euclid/src/dssa/truth.rs // Module: euclid::src::dssa::truth use std::sync::LazyLock; use euclid_macros::knowledge; use crate::{dssa::graph::euclid_graph_prelude, frontend::dir}; pub static ANALYSIS_GRAPH: LazyLock<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>> = LazyLock::new(|| { knowledge! { // Payment Method should be `Card` for a CardType to be present PaymentMethod(Card) ->> CardType(any); // Payment Method should be `PayLater` for a PayLaterType to be present PaymentMethod(PayLater) ->> PayLaterType(any); // Payment Method should be `Wallet` for a WalletType to be present PaymentMethod(Wallet) ->> WalletType(any); // Payment Method should be `BankRedirect` for a BankRedirectType to // be present PaymentMethod(BankRedirect) ->> BankRedirectType(any); // Payment Method should be `BankTransfer` for a BankTransferType to // be present PaymentMethod(BankTransfer) ->> BankTransferType(any); // Payment Method should be `GiftCard` for a GiftCardType to // be present PaymentMethod(GiftCard) ->> GiftCardType(any); // Payment Method should be `RealTimePayment` for a RealTimePaymentType to // be present PaymentMethod(RealTimePayment) ->> RealTimePaymentType(any); } });
crates/euclid/src/dssa/truth.rs
euclid::src::dssa::truth
337
true
// File: crates/api_models/src/tokenization.rs // Module: api_models::src::tokenization use common_enums; use common_utils::id_type; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::{schema, ToSchema}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct GenericTokenizationResponse { /// Unique identifier returned by the tokenization service #[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalTokenId, /// Created time of the tokenization id #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] pub created_at: PrimitiveDateTime, /// Status of the tokenization id created #[schema(value_type = String,example = "enabled")] pub flag: common_enums::TokenizationFlag, } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct GenericTokenizationRequest { /// Customer ID for which the tokenization is requested #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] pub customer_id: id_type::GlobalCustomerId, /// Request for tokenization which contains the data to be tokenized #[schema(value_type = Object,example = json!({ "city": "NY", "unit": "245" }))] pub token_request: masking::Secret<serde_json::Value>, } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct DeleteTokenDataRequest { /// Customer ID for which the tokenization is requested #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] pub customer_id: id_type::GlobalCustomerId, /// Session ID associated with the tokenization request #[schema(value_type = String, example = "12345_pms_01926c58bc6e77c09e809964e72af8c8")] pub session_id: id_type::GlobalPaymentMethodSessionId, } #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct DeleteTokenDataResponse { /// Unique identifier returned by the tokenization service #[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalTokenId, }
crates/api_models/src/tokenization.rs
api_models::src::tokenization
698
true
// File: crates/api_models/src/locker_migration.rs // Module: api_models::src::locker_migration #[derive(Debug, Clone, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct MigrateCardResponse { pub status_message: String, pub status_code: String, pub customers_moved: usize, pub cards_moved: usize, }
crates/api_models/src/locker_migration.rs
api_models::src::locker_migration
80
true
// File: crates/api_models/src/consts.rs // Module: api_models::src::consts /// Max payment intent fulfillment expiry pub const MAX_ORDER_FULFILLMENT_EXPIRY: i64 = 1800; /// Min payment intent fulfillment expiry pub const MIN_ORDER_FULFILLMENT_EXPIRY: i64 = 60;
crates/api_models/src/consts.rs
api_models::src::consts
77
true
// File: crates/api_models/src/payment_methods.rs // Module: api_models::src::payment_methods use std::collections::{HashMap, HashSet}; #[cfg(feature = "v2")] use std::str::FromStr; use cards::CardNumber; #[cfg(feature = "v1")] use common_utils::crypto::OptionalEncryptableName; use common_utils::{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH, errors, ext_traits::OptionExt, id_type, link_utils, pii, types::{MinorUnit, Percentage, Surcharge}, }; use masking::PeekInterface; use serde::de; use utoipa::{schema, ToSchema}; #[cfg(feature = "v1")] use crate::payments::BankCodeResponse; #[cfg(feature = "payouts")] use crate::payouts; use crate::{admin, enums as api_enums, open_router, payments}; #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodCreate { /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>,example = "credit")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user #[schema(example = "Citibank")] pub payment_method_issuer: Option<String>, /// A standard code representing the issuer of payment method #[schema(value_type = Option<PaymentMethodIssuerCode>,example = "jp_applepay")] pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, /// Card Details #[schema(example = json!({ "card_number": "4111111145551142", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "John Doe"}))] pub card: Option<CardDetail>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The card network #[schema(example = "Visa")] pub card_network: Option<String>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] pub bank_transfer: Option<payouts::Bank>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Wallet>)] pub wallet: Option<payouts::Wallet>, /// For Client based calls, SDK will use the client_secret /// in order to call /payment_methods /// Client secret will be generated whenever a new /// payment method is created pub client_secret: Option<String>, /// Payment method data to be passed in case of client /// based flow pub payment_method_data: Option<PaymentMethodCreateData>, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, #[serde(skip_deserializing)] /// The connector mandate details of the payment method, this is added only for cards migration /// api and is skipped during deserialization of the payment method create request as this /// it should not be passed in the request pub connector_mandate_details: Option<PaymentsMandateReference>, #[serde(skip_deserializing)] /// The transaction id of a CIT (customer initiated transaction) associated with the payment method, /// this is added only for cards migration api and is skipped during deserialization of the /// payment method create request as it should not be passed in the request pub network_transaction_id: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodCreate { /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "google_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// Payment method data to be passed pub payment_method_data: PaymentMethodCreateData, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodIntentCreate { /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodIntentConfirm { /// The unique identifier of the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Payment method data to be passed pub payment_method_data: PaymentMethodCreateData, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "credit")] pub payment_method_subtype: api_enums::PaymentMethodType, } #[cfg(feature = "v2")] impl PaymentMethodIntentConfirm { pub fn validate_payment_method_data_against_payment_method( payment_method_type: api_enums::PaymentMethod, payment_method_data: PaymentMethodCreateData, ) -> bool { match payment_method_type { api_enums::PaymentMethod::Card => { matches!( payment_method_data, PaymentMethodCreateData::Card(_) | PaymentMethodCreateData::ProxyCard(_) ) } _ => false, } } } /// This struct is used internally only #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentMethodIntentConfirmInternal { pub id: id_type::GlobalPaymentMethodId, pub request: PaymentMethodIntentConfirm, } #[cfg(feature = "v2")] impl From<PaymentMethodIntentConfirmInternal> for PaymentMethodIntentConfirm { fn from(item: PaymentMethodIntentConfirmInternal) -> Self { item.request } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] /// This struct is only used by and internal api to migrate payment method pub struct PaymentMethodMigrate { /// Merchant id pub merchant_id: id_type::MerchantId, /// The type of payment method use for the payment. pub payment_method: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user pub payment_method_issuer: Option<String>, /// A standard code representing the issuer of payment method pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, /// Card Details pub card: Option<MigrateCardDetail>, /// Network token details pub network_token: Option<MigrateNetworkTokenDetail>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the customer. pub customer_id: Option<id_type::CustomerId>, /// The card network pub card_network: Option<String>, /// Payment method details from locker #[cfg(feature = "payouts")] pub bank_transfer: Option<payouts::Bank>, /// Payment method details from locker #[cfg(feature = "payouts")] pub wallet: Option<payouts::Wallet>, /// Payment method data to be passed in case of client /// based flow pub payment_method_data: Option<PaymentMethodCreateData>, /// The billing details of the payment method pub billing: Option<payments::Address>, /// The connector mandate details of the payment method #[serde(deserialize_with = "deserialize_connector_mandate_details")] pub connector_mandate_details: Option<CommonMandateReference>, // The CIT (customer initiated transaction) transaction id associated with the payment method pub network_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodMigrateResponse { //payment method response when payment method entry is created pub payment_method_response: PaymentMethodResponse, //card data migration status pub card_migrated: Option<bool>, //network token data migration status pub network_token_migrated: Option<bool>, //connector mandate details migration status pub connector_mandate_details_migrated: Option<bool>, //network transaction id migration status pub network_transaction_id_migrated: Option<bool>, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodRecordUpdateResponse { pub payment_method_id: String, pub status: common_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub connector_mandate_details: Option<pii::SecretSerdeValue>, pub updated_payment_method_data: Option<bool>, pub connector_customer: Option<pii::SecretSerdeValue>, } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsMandateReference( pub HashMap<id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>, ); #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PayoutsMandateReference( pub HashMap<id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>, ); #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PayoutsMandateReferenceRecord { pub transfer_method_id: Option<String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PaymentsMandateReferenceRecord { pub connector_mandate_id: String, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::Currency>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct CommonMandateReference { pub payments: Option<PaymentsMandateReference>, pub payouts: Option<PayoutsMandateReference>, } impl From<CommonMandateReference> for PaymentsMandateReference { fn from(common_mandate: CommonMandateReference) -> Self { common_mandate.payments.unwrap_or_default() } } impl From<PaymentsMandateReference> for CommonMandateReference { fn from(payments_reference: PaymentsMandateReference) -> Self { Self { payments: Some(payments_reference), payouts: None, } } } fn deserialize_connector_mandate_details<'de, D>( deserializer: D, ) -> Result<Option<CommonMandateReference>, D::Error> where D: serde::Deserializer<'de>, { let value: Option<serde_json::Value> = <Option<serde_json::Value> as de::Deserialize>::deserialize(deserializer)?; let payments_data = value .clone() .map(|mut mandate_details| { mandate_details .as_object_mut() .map(|obj| obj.remove("payouts")); serde_json::from_value::<PaymentsMandateReference>(mandate_details) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize PaymentsMandateReference `{err_msg}`", )) })?; let payouts_data = value .clone() .map(|mandate_details| { serde_json::from_value::<Option<CommonMandateReference>>(mandate_details).map( |optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) }, ) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize CommonMandateReference `{err_msg}`", )) })? .flatten(); Ok(Some(CommonMandateReference { payments: payments_data, payouts: payouts_data, })) } #[cfg(feature = "v1")] impl PaymentMethodCreate { pub fn get_payment_method_create_from_payment_method_migrate( card_number: CardNumber, payment_method_migrate: &PaymentMethodMigrate, ) -> Self { let card_details = payment_method_migrate .card .as_ref() .map(|payment_method_migrate_card| CardDetail { card_number, card_exp_month: payment_method_migrate_card.card_exp_month.clone(), card_exp_year: payment_method_migrate_card.card_exp_year.clone(), card_holder_name: payment_method_migrate_card.card_holder_name.clone(), nick_name: payment_method_migrate_card.nick_name.clone(), card_issuing_country: payment_method_migrate_card.card_issuing_country.clone(), card_network: payment_method_migrate_card.card_network.clone(), card_issuer: payment_method_migrate_card.card_issuer.clone(), card_type: payment_method_migrate_card.card_type.clone(), }); Self { customer_id: payment_method_migrate.customer_id.clone(), payment_method: payment_method_migrate.payment_method, payment_method_type: payment_method_migrate.payment_method_type, payment_method_issuer: payment_method_migrate.payment_method_issuer.clone(), payment_method_issuer_code: payment_method_migrate.payment_method_issuer_code, metadata: payment_method_migrate.metadata.clone(), payment_method_data: payment_method_migrate.payment_method_data.clone(), connector_mandate_details: payment_method_migrate .connector_mandate_details .clone() .map(|common_mandate_reference| { PaymentsMandateReference::from(common_mandate_reference) }), client_secret: None, billing: payment_method_migrate.billing.clone(), card: card_details, card_network: payment_method_migrate.card_network.clone(), #[cfg(feature = "payouts")] bank_transfer: payment_method_migrate.bank_transfer.clone(), #[cfg(feature = "payouts")] wallet: payment_method_migrate.wallet.clone(), network_transaction_id: payment_method_migrate.network_transaction_id.clone(), } } } #[cfg(feature = "v2")] impl PaymentMethodCreate { pub fn validate_payment_method_data_against_payment_method( payment_method_type: api_enums::PaymentMethod, payment_method_data: PaymentMethodCreateData, ) -> bool { match payment_method_type { api_enums::PaymentMethod::Card => { matches!( payment_method_data, PaymentMethodCreateData::Card(_) | PaymentMethodCreateData::ProxyCard(_) ) } _ => false, } } pub fn get_tokenize_connector_id( &self, ) -> Result<id_type::MerchantConnectorAccountId, error_stack::Report<errors::ValidationError>> { self.psp_tokenization .clone() .get_required_value("psp_tokenization") .map(|psp| psp.connector_id) } } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodUpdate { /// Card Details #[schema(example = json!({ "card_number": "4111111145551142", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "John Doe"}))] pub card: Option<CardDetailUpdate>, /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodUpdate { /// Payment method details to be updated for the payment_method pub payment_method_data: Option<PaymentMethodUpdateData>, /// The connector token details to be updated for the payment_method pub connector_token_details: Option<ConnectorTokenDetails>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodUpdateData { Card(CardDetailUpdate), } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodCreateData { Card(CardDetail), ProxyCard(ProxyCardDetails), } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodCreateData { Card(CardDetail), } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } #[derive( Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, strum::EnumString, strum::Display, Eq, PartialEq, )] #[serde(rename_all = "snake_case")] pub enum CardType { Credit, Debit, } // We cannot use the card struct that we have for payments for the following reason // The card struct used for payments has card_cvc as mandatory // but when vaulting the card, we do not need cvc to be collected from the user // This is because, the vaulted payment method can be used for future transactions in the presence of the customer // when the customer is on_session again, the cvc can be collected from the customer #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country #[schema(value_type = CountryAlpha2)] pub card_issuing_country: Option<api_enums::CountryAlpha2>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<CardType>, /// The CVC number for the card /// This is optional in case the card needs to be vaulted #[schema(value_type = String, example = "242")] pub card_cvc: Option<masking::Secret<String>>, } // This struct is for collecting Proxy Card Data // All card related data present in this struct are tokenzied // No strict type is present to accept tokenized data #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ProxyCardDetails { /// Tokenized Card Number #[schema(value_type = String,example = "tok_sjfowhoejsldj")] pub card_number: masking::Secret<String>, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// First Six Digit of Card Number pub bin_number: Option<String>, ///Last Four Digit of Card Number pub last_four: Option<String>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<common_enums::CardNetwork>, /// Card Type pub card_type: Option<String>, /// Issuing Country of the Card pub card_issuing_country: Option<String>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// The CVC number for the card /// This is optional in case the card needs to be vaulted #[schema(value_type = String, example = "242")] pub card_cvc: Option<masking::Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MigrateCardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: masking::Secret<String>, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MigrateNetworkTokenData { /// Network Token Number #[schema(value_type = String,example = "4111111145551142")] pub network_token_number: CardNumber, /// Network Token Expiry Month #[schema(value_type = String,example = "10")] pub network_token_exp_month: masking::Secret<String>, /// Network Token Expiry Year #[schema(value_type = String,example = "25")] pub network_token_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MigrateNetworkTokenDetail { /// Network token details pub network_token_data: MigrateNetworkTokenData, /// Network token requestor reference id pub network_token_requestor_ref_id: String, } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetailUpdate { /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: Option<masking::Secret<String>>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: Option<masking::Secret<String>>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, } #[cfg(feature = "v1")] impl CardDetailUpdate { pub fn apply(&self, card_data_from_locker: Card) -> CardDetail { CardDetail { card_number: card_data_from_locker.card_number, card_exp_month: self .card_exp_month .clone() .unwrap_or(card_data_from_locker.card_exp_month), card_exp_year: self .card_exp_year .clone() .unwrap_or(card_data_from_locker.card_exp_year), card_holder_name: self .card_holder_name .clone() .or(card_data_from_locker.name_on_card), nick_name: self .nick_name .clone() .or(card_data_from_locker.nick_name.map(masking::Secret::new)), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, } } } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetailUpdate { /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, } #[cfg(feature = "v2")] impl CardDetailUpdate { pub fn apply(&self, card_data_from_locker: Card) -> CardDetail { CardDetail { card_number: card_data_from_locker.card_number, card_exp_month: card_data_from_locker.card_exp_month, card_exp_year: card_data_from_locker.card_exp_year, card_holder_name: self .card_holder_name .clone() .or(card_data_from_locker.name_on_card), nick_name: self .nick_name .clone() .or(card_data_from_locker.nick_name.map(masking::Secret::new)), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, card_cvc: None, } } } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodResponseData { Card(CardDetailFromLocker), } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodResponse { /// Unique identifier for a merchant #[schema(example = "merchant_1671528864", value_type = String)] pub merchant_id: id_type::MerchantId, /// The unique identifier of the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The unique identifier of the Payment method #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] pub payment_method_id: String, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>, example = "credit")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Card details from card locker #[schema(example = json!({"last4": "1142","exp_month": "03","exp_year": "2030"}))] pub card: Option<CardDetailFromLocker>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional. #[schema(example = true)] pub installment_payment_enabled: Option<bool>, /// Type of payment experience enabled with the connector #[schema(value_type = Option<Vec<PaymentExperience>>, example = json!(["redirect_to_url"]))] pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = Option<PrimitiveDateTime>, example = "2023-01-18T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] #[serde(skip_serializing_if = "Option::is_none")] pub bank_transfer: Option<payouts::Bank>, #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_used_at: Option<time::PrimitiveDateTime>, /// For Client based calls pub client_secret: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema, Clone)] pub struct ConnectorTokenDetails { /// The unique identifier of the connector account through which the token was generated #[schema(value_type = String, example = "mca_")] pub connector_id: id_type::MerchantConnectorAccountId, #[schema(value_type = TokenizationType)] pub token_type: common_enums::TokenizationType, /// The status of connector token if it is active or inactive #[schema(value_type = ConnectorTokenStatus)] pub status: common_enums::ConnectorTokenStatus, /// The reference id of the connector token /// This is the reference that was passed to connector when creating the token pub connector_token_request_reference_id: Option<String>, pub original_payment_authorized_amount: Option<MinorUnit>, /// The currency of the original payment authorized amount #[schema(value_type = Currency)] pub original_payment_authorized_currency: Option<common_enums::Currency>, /// Metadata associated with the connector token pub metadata: Option<pii::SecretSerdeValue>, /// The value of the connector token. This token can be used to make merchant initiated payments ( MIT ), directly with the connector. pub token: masking::Secret<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema, Clone)] pub struct PaymentMethodResponse { /// The unique identifier of the Payment method #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, /// Unique identifier for a merchant #[schema(value_type = String, example = "merchant_1671528864")] pub merchant_id: id_type::MerchantId, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>, example = "credit")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = Option<PrimitiveDateTime>, example = "2023-01-18T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_used_at: Option<time::PrimitiveDateTime>, /// The payment method details related to the payment method pub payment_method_data: Option<PaymentMethodResponseData>, /// The connector token details if available pub connector_tokens: Option<Vec<ConnectorTokenDetails>>, pub network_token: Option<NetworkTokenResponse>, } #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub enum PaymentMethodsData { Card(CardDetailsPaymentMethod), BankDetails(PaymentMethodDataBankCreds), WalletDetails(PaymentMethodDataWalletInfo), } #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub struct ExternalVaultTokenData { /// Tokenized reference for Card Number pub tokenized_card_number: masking::Secret<String>, } #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub struct CardDetailsPaymentMethod { pub last4_digits: Option<String>, pub issuer_country: Option<String>, pub expiry_month: Option<masking::Secret<String>>, pub expiry_year: Option<masking::Secret<String>>, pub nick_name: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, pub co_badged_card_data: Option<CoBadgedCardDataToBeSaved>, } impl From<&CoBadgedCardData> for CoBadgedCardDataToBeSaved { fn from(co_badged_card_data: &CoBadgedCardData) -> Self { Self { co_badged_card_networks: co_badged_card_data .co_badged_card_networks_info .get_card_networks(), issuer_country_code: co_badged_card_data.issuer_country_code, is_regulated: co_badged_card_data.is_regulated, regulated_name: co_badged_card_data.regulated_name.clone(), } } } #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub struct CoBadgedCardData { pub co_badged_card_networks_info: open_router::CoBadgedCardNetworks, pub issuer_country_code: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, } #[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)] pub struct CoBadgedCardDataToBeSaved { pub co_badged_card_networks: Vec<common_enums::CardNetwork>, pub issuer_country_code: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct NetworkTokenDetailsPaymentMethod { pub last4_digits: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub issuer_country: Option<common_enums::CountryAlpha2>, #[schema(value_type = Option<String>)] pub network_token_expiry_month: Option<masking::Secret<String>>, #[schema(value_type = Option<String>)] pub network_token_expiry_year: Option<masking::Secret<String>>, #[schema(value_type = Option<String>)] pub nick_name: Option<masking::Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, pub card_isin: Option<String>, pub card_issuer: Option<String>, #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodDataBankCreds { pub mask: String, pub hash: String, pub account_type: Option<String>, pub account_name: Option<String>, pub payment_method_type: api_enums::PaymentMethodType, pub connector_details: Vec<BankAccountConnectorDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct PaymentMethodDataWalletInfo { /// Last 4 digits of the card number pub last4: String, /// The information of the payment method pub card_network: String, /// The type of payment method #[serde(rename = "type")] pub card_type: Option<String>, } impl From<payments::additional_info::WalletAdditionalDataForCard> for PaymentMethodDataWalletInfo { fn from(item: payments::additional_info::WalletAdditionalDataForCard) -> Self { Self { last4: item.last4, card_network: item.card_network, card_type: item.card_type, } } } impl From<PaymentMethodDataWalletInfo> for payments::additional_info::WalletAdditionalDataForCard { fn from(item: PaymentMethodDataWalletInfo) -> Self { Self { last4: item.last4, card_network: item.card_network, card_type: item.card_type, } } } impl From<payments::ApplepayPaymentMethod> for PaymentMethodDataWalletInfo { fn from(item: payments::ApplepayPaymentMethod) -> Self { Self { last4: item .display_name .chars() .rev() .take(4) .collect::<Vec<_>>() .into_iter() .rev() .collect(), card_network: item.network, card_type: Some(item.pm_type), } } } impl TryFrom<PaymentMethodDataWalletInfo> for payments::ApplepayPaymentMethod { type Error = error_stack::Report<errors::ValidationError>; fn try_from(item: PaymentMethodDataWalletInfo) -> Result<Self, Self::Error> { Ok(Self { display_name: item.last4, network: item.card_network, pm_type: item.card_type.get_required_value("card_type")?, }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct BankAccountTokenData { pub payment_method_type: api_enums::PaymentMethodType, pub payment_method: api_enums::PaymentMethod, pub connector_details: BankAccountConnectorDetails, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct BankAccountConnectorDetails { pub connector: String, pub account_id: masking::Secret<String>, pub mca_id: id_type::MerchantConnectorAccountId, pub access_token: BankAccountAccessCreds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub enum BankAccountAccessCreds { AccessToken(masking::Secret<String>), } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct Card { pub card_number: CardNumber, pub name_on_card: Option<masking::Secret<String>>, pub card_exp_month: masking::Secret<String>, pub card_exp_year: masking::Secret<String>, pub card_brand: Option<String>, pub card_isin: Option<String>, pub nick_name: Option<String>, } #[cfg(feature = "v1")] impl From<(Card, Option<common_enums::CardNetwork>)> for CardDetail { fn from((card, card_network): (Card, Option<common_enums::CardNetwork>)) -> Self { Self { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.name_on_card.clone(), nick_name: card.nick_name.map(masking::Secret::new), card_issuing_country: None, card_network, card_issuer: None, card_type: None, } } } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct CardDetailFromLocker { pub scheme: Option<String>, pub issuer_country: Option<String>, pub last4_digits: Option<String>, #[serde(skip)] #[schema(value_type=Option<String>)] pub card_number: Option<CardNumber>, #[schema(value_type=Option<String>)] pub expiry_month: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub expiry_year: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_token: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_fingerprint: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub nick_name: Option<masking::Secret<String>>, #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_type: Option<String>, pub saved_to_locker: bool, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct CardDetailFromLocker { #[schema(value_type = Option<CountryAlpha2>)] pub issuer_country: Option<api_enums::CountryAlpha2>, pub last4_digits: Option<String>, #[serde(skip)] #[schema(value_type=Option<String>)] pub card_number: Option<CardNumber>, #[schema(value_type=Option<String>)] pub expiry_month: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub expiry_year: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_fingerprint: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub nick_name: Option<masking::Secret<String>>, #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_type: Option<String>, pub saved_to_locker: bool, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct NetworkTokenResponse { pub payment_method_data: NetworkTokenDetailsPaymentMethod, } fn saved_in_locker_default() -> bool { true } #[cfg(feature = "v1")] impl From<CardDetailFromLocker> for payments::AdditionalCardInfo { fn from(item: CardDetailFromLocker) -> Self { Self { card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, card_issuing_country: item.issuer_country, bank_code: None, last4: item.last4_digits, card_isin: item.card_isin, card_extended_bin: item .card_number .map(|card_number| card_number.get_extended_card_bin()), card_exp_month: item.expiry_month, card_exp_year: item.expiry_year, card_holder_name: item.card_holder_name, payment_checks: None, authentication_data: None, is_regulated: None, signature_network: None, } } } #[cfg(feature = "v2")] impl From<CardDetailFromLocker> for payments::AdditionalCardInfo { fn from(item: CardDetailFromLocker) -> Self { Self { card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, card_issuing_country: item.issuer_country.map(|country| country.to_string()), bank_code: None, last4: item.last4_digits, card_isin: item.card_isin, card_extended_bin: item .card_number .map(|card_number| card_number.get_extended_card_bin()), card_exp_month: item.expiry_month, card_exp_year: item.expiry_year, card_holder_name: item.card_holder_name, payment_checks: None, authentication_data: None, is_regulated: None, signature_network: None, } } } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForSession { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypes>, /// The list of saved payment methods of the customer pub customer_payment_methods: Vec<CustomerPaymentMethodResponseItem>, } #[cfg(feature = "v1")] impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { fn from(item: CardDetailsPaymentMethod) -> Self { Self { scheme: None, issuer_country: item.issuer_country, last4_digits: item.last4_digits, card_number: None, expiry_month: item.expiry_month, expiry_year: item.expiry_year, card_token: None, card_holder_name: item.card_holder_name, card_fingerprint: None, nick_name: item.nick_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, } } } #[cfg(feature = "v2")] impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { fn from(item: CardDetailsPaymentMethod) -> Self { Self { issuer_country: item .issuer_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten(), last4_digits: item.last4_digits, card_number: None, expiry_month: item.expiry_month, expiry_year: item.expiry_year, card_holder_name: item.card_holder_name, card_fingerprint: None, nick_name: item.nick_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, } } } #[cfg(feature = "v2")] impl From<CardDetail> for CardDetailFromLocker { fn from(item: CardDetail) -> Self { Self { issuer_country: item.card_issuing_country, last4_digits: Some(item.card_number.get_last4()), card_number: Some(item.card_number), expiry_month: Some(item.card_exp_month), expiry_year: Some(item.card_exp_year), card_holder_name: item.card_holder_name, nick_name: item.nick_name, card_isin: None, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, card_fingerprint: None, } } } #[cfg(feature = "v1")] impl From<CardDetail> for CardDetailFromLocker { fn from(item: CardDetail) -> Self { // scheme should be updated in case of co-badged cards let card_scheme = item .card_network .clone() .map(|card_network| card_network.to_string()); Self { issuer_country: item.card_issuing_country, last4_digits: Some(item.card_number.get_last4()), card_number: Some(item.card_number), expiry_month: Some(item.card_exp_month), expiry_year: Some(item.card_exp_year), card_holder_name: item.card_holder_name, nick_name: item.nick_name, card_isin: None, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, card_fingerprint: None, scheme: card_scheme, card_token: None, } } } #[cfg(feature = "v2")] impl From<CardDetail> for CardDetailsPaymentMethod { fn from(item: CardDetail) -> Self { Self { issuer_country: item.card_issuing_country.map(|c| c.to_string()), last4_digits: Some(item.card_number.get_last4()), expiry_month: Some(item.card_exp_month), expiry_year: Some(item.card_exp_year), card_holder_name: item.card_holder_name, nick_name: item.nick_name, card_isin: None, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, co_badged_card_data: None, } } } #[cfg(feature = "v1")] impl From<(CardDetailFromLocker, Option<&CoBadgedCardData>)> for CardDetailsPaymentMethod { fn from( (item, co_badged_card_data): (CardDetailFromLocker, Option<&CoBadgedCardData>), ) -> Self { Self { issuer_country: item.issuer_country, last4_digits: item.last4_digits, expiry_month: item.expiry_month, expiry_year: item.expiry_year, nick_name: item.nick_name, card_holder_name: item.card_holder_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, co_badged_card_data: co_badged_card_data.map(CoBadgedCardDataToBeSaved::from), } } } #[cfg(feature = "v2")] impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { fn from(item: CardDetailFromLocker) -> Self { Self { issuer_country: item.issuer_country.map(|country| country.to_string()), last4_digits: item.last4_digits, expiry_month: item.expiry_month, expiry_year: item.expiry_year, nick_name: item.nick_name, card_holder_name: item.card_holder_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, co_badged_card_data: None, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct PaymentExperienceTypes { /// The payment experience enabled #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience_type: api_enums::PaymentExperience, /// The list of eligible connectors for a given payment experience #[schema(example = json!(["stripe", "adyen"]))] pub eligible_connectors: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct CardNetworkTypes { /// The card network enabled #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: api_enums::CardNetwork, /// surcharge details for this card network pub surcharge_details: Option<SurchargeDetailsResponse>, /// The list of eligible connectors for a given card network #[schema(example = json!(["stripe", "adyen"]))] pub eligible_connectors: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankDebitTypes { pub eligible_connectors: Vec<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypes { /// The payment method type enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The list of payment experiences enabled, if applicable for a payment method type pub payment_experience: Option<Vec<PaymentExperienceTypes>>, /// The list of card networks enabled, if applicable for a payment method type pub card_networks: Option<Vec<CardNetworkTypes>>, #[schema(deprecated)] /// The list of banks enabled, if applicable for a payment method type . To be deprecated soon. pub bank_names: Option<Vec<BankCodeResponse>>, /// The Bank debit payment method information, if applicable for a payment method type. pub bank_debits: Option<BankDebitTypes>, /// The Bank transfer payment method information, if applicable for a payment method type. pub bank_transfers: Option<BankTransferTypes>, /// Required fields for the payment_method_type. pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, /// surcharge details for this payment method type if exists pub surcharge_details: Option<SurchargeDetailsResponse>, /// auth service connector label for this payment method type, if exists pub pm_auth_connector: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] #[serde(untagged)] // Untagged used for serialization only pub enum PaymentMethodSubtypeSpecificData { #[schema(title = "card")] Card { card_networks: Vec<CardNetworkTypes>, }, #[schema(title = "bank")] Bank { #[schema(value_type = BankNames)] bank_names: Vec<common_enums::BankNames>, }, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypes { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] pub extra_information: Option<PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. pub required_fields: Vec<RequiredFieldInfo>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SurchargeDetailsResponse { /// surcharge value pub surcharge: SurchargeResponse, /// tax on surcharge value pub tax_on_surcharge: Option<SurchargePercentage>, /// surcharge amount for this payment pub display_surcharge_amount: f64, /// tax on surcharge amount for this payment pub display_tax_on_surcharge_amount: f64, /// sum of display_surcharge_amount and display_tax_on_surcharge_amount pub display_total_surcharge_amount: f64, } #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum SurchargeResponse { /// Fixed Surcharge value Fixed(MinorUnit), /// Surcharge percentage Rate(SurchargePercentage), } impl From<Surcharge> for SurchargeResponse { fn from(value: Surcharge) -> Self { match value { Surcharge::Fixed(amount) => Self::Fixed(amount), Surcharge::Rate(percentage) => Self::Rate(percentage.into()), } } } #[derive(Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct SurchargePercentage { percentage: f32, } impl From<Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>> for SurchargePercentage { fn from(value: Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>) -> Self { Self { percentage: value.get_percentage(), } } } /// Required fields info used while listing the payment_method_data #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq, ToSchema)] pub struct RequiredFieldInfo { /// Required field for a payment_method through a payment_method_type pub required_field: String, /// Display name of the required field in the front-end pub display_name: String, /// Possible field type of required field #[schema(value_type = FieldType)] pub field_type: api_enums::FieldType, #[schema(value_type = Option<String>)] pub value: Option<masking::Secret<String>>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct ResponsePaymentMethodsEnabled { /// The payment method enabled #[schema(value_type = PaymentMethod)] pub payment_method: api_enums::PaymentMethod, /// The list of payment method types enabled for a connector account pub payment_method_types: Vec<ResponsePaymentMethodTypes>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankTransferTypes { /// The list of eligible connectors for a given payment experience #[schema(example = json!(["stripe", "adyen"]))] pub eligible_connectors: Vec<String>, } #[derive(Clone, Debug)] pub struct ResponsePaymentMethodIntermediate { pub payment_method_type: api_enums::PaymentMethodType, pub payment_experience: Option<api_enums::PaymentExperience>, pub card_networks: Option<Vec<api_enums::CardNetwork>>, pub payment_method: api_enums::PaymentMethod, pub connector: String, pub merchant_connector_id: String, } impl ResponsePaymentMethodIntermediate { pub fn new( pm_type: RequestPaymentMethodTypes, connector: String, merchant_connector_id: String, pm: api_enums::PaymentMethod, ) -> Self { Self { payment_method_type: pm_type.payment_method_type, payment_experience: pm_type.payment_experience, card_networks: pm_type.card_networks, payment_method: pm, connector, merchant_connector_id, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, Hash)] pub struct RequestPaymentMethodTypes { #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, #[schema(value_type = Option<PaymentExperience>)] pub payment_experience: Option<api_enums::PaymentExperience>, #[schema(value_type = Option<Vec<CardNetwork>>)] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// List of currencies accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "specific_accepted", "list": ["USD", "INR"] } ), value_type = Option<AcceptedCurrencies>)] pub accepted_currencies: Option<admin::AcceptedCurrencies>, /// List of Countries accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "specific_accepted", "list": ["UK", "AU"] } ), value_type = Option<AcceptedCountries>)] pub accepted_countries: Option<admin::AcceptedCountries>, /// Minimum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) #[schema(example = 1)] pub minimum_amount: Option<MinorUnit>, /// Maximum amount supported by the processor. To be represented in the lowest denomination of /// the target currency (For example, for USD it should be in cents) #[schema(example = 1313)] pub maximum_amount: Option<MinorUnit>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = false)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional. #[schema(example = true)] pub installment_payment_enabled: Option<bool>, } impl RequestPaymentMethodTypes { /// Get payment_method_type #[cfg(feature = "v1")] pub fn get_payment_method_type(&self) -> Option<api_enums::PaymentMethodType> { Some(self.payment_method_type) } } #[cfg(feature = "v1")] //List Payment Method #[derive(Debug, Clone, serde::Serialize, Default, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodListRequest { /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, /// The two-letter ISO currency code #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))] pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>, /// The three-letter ISO currency code #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))] pub accepted_currencies: Option<Vec<api_enums::Currency>>, /// Filter by amount #[schema(example = 60)] pub amount: Option<MinorUnit>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional. #[schema(example = true)] pub installment_payment_enabled: Option<bool>, /// Indicates whether the payment method is eligible for card netwotks #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// Indicates the limit of last used payment methods #[schema(example = 1)] pub limit: Option<i64>, } #[cfg(feature = "v1")] impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = PaymentMethodListRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "installment_payment_enabled" => { set_or_reject_duplicate( &mut output.installment_payment_enabled, "installment_payment_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } } #[cfg(feature = "v2")] //List Payment Method #[derive(Debug, Clone, serde::Serialize, Default, ToSchema)] #[serde(deny_unknown_fields)] pub struct ListMethodsForPaymentMethodsRequest { /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, /// The two-letter ISO currency code #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))] pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>, /// Filter by amount #[schema(example = 60)] pub amount: Option<MinorUnit>, /// The three-letter ISO currency code #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))] pub accepted_currencies: Option<Vec<api_enums::Currency>>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for card netwotks #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// Indicates the limit of last used payment methods #[schema(example = 1)] pub limit: Option<i64>, } #[cfg(feature = "v2")] impl<'de> serde::Deserialize<'de> for ListMethodsForPaymentMethodsRequest { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = ListMethodsForPaymentMethodsRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = ListMethodsForPaymentMethodsRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } } // Try to set the provided value to the data otherwise throw an error fn set_or_reject_duplicate<T, E: de::Error>( data: &mut Option<T>, name: &'static str, value: T, ) -> Result<(), E> { match data { Some(_inner) => Err(de::Error::duplicate_field(name)), None => { *data = Some(value); Ok(()) } } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponse { /// Redirect URL of the merchant #[schema(example = "https://www.google.com")] pub redirect_url: Option<String>, /// currency of the Payment to be done #[schema(example = "USD", value_type = Currency)] pub currency: Option<api_enums::Currency>, /// Information about the payment method pub payment_methods: Vec<ResponsePaymentMethodsEnabled>, /// Value indicating if the current payment is a mandate payment #[schema(value_type = MandateType)] pub mandate_payment: Option<payments::MandateType>, #[schema(value_type = Option<String>)] pub merchant_name: OptionalEncryptableName, /// flag to indicate if surcharge and tax breakup screen should be shown or not #[schema(value_type = bool)] pub show_surcharge_breakup_screen: bool, #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, /// flag to indicate whether to perform external 3ds authentication #[schema(example = true)] pub request_external_three_ds_authentication: bool, /// flag that indicates whether to collect shipping details from wallets or from the customer pub collect_shipping_details_from_wallets: Option<bool>, /// flag that indicates whether to collect billing details from wallets or from the customer pub collect_billing_details_from_wallets: Option<bool>, /// flag that indicates whether to calculate tax on the order amount pub is_tax_calculation_enabled: bool, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodsListResponse { /// List of payment methods for customer pub customer_payment_methods: Vec<CustomerPaymentMethod>, /// Returns whether a customer id is not tied to a payment intent (only when the request is made against a client secret) pub is_guest_customer: Option<bool>, } // OLAP PML Response #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodsListResponse { /// List of payment methods for customer pub customer_payment_methods: Vec<PaymentMethodResponseItem>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct GetTokenDataRequest { /// Indicates the type of token to be fetched pub token_type: api_enums::TokenDataType, } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for GetTokenDataRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct TokenDataResponse { /// The unique identifier of the payment method. #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: id_type::GlobalPaymentMethodId, /// token type of the payment method #[schema(value_type = TokenDataType)] pub token_type: api_enums::TokenDataType, /// token details of the payment method pub token_details: TokenDetailsResponse, } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for TokenDataResponse {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum TokenDetailsResponse { NetworkTokenDetails(NetworkTokenDetailsResponse), } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct NetworkTokenDetailsResponse { /// Network token generated against the Card Number #[schema(value_type = String)] pub network_token: cards::NetworkToken, /// Expiry month of the network token #[schema(value_type = String)] pub network_token_exp_month: masking::Secret<String>, /// Expiry year of the network token #[schema(value_type = String)] pub network_token_exp_year: masking::Secret<String>, /// Cryptogram generated by the Network #[schema(value_type = Option<String>)] pub cryptogram: Option<masking::Secret<String>>, /// Issuer of the card pub card_issuer: Option<String>, /// Card network of the token #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<common_enums::CardNetwork>, /// Card type of the token pub card_type: Option<CardType>, /// Issuing country of the card #[schema(value_type = Option<CountryAlpha2>)] pub card_issuing_country: Option<common_enums::CountryAlpha2>, /// Bank code of the card pub bank_code: Option<String>, /// Name of the card holder #[schema(value_type = Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, /// Nick name of the card holder #[schema(value_type = Option<String>)] pub nick_name: Option<masking::Secret<String>>, /// ECI indicator of the card pub eci: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct TotalPaymentMethodCountResponse { /// total count of payment methods under the merchant pub total_count: i64, } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for TotalPaymentMethodCountResponse {} #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodDeleteResponse { /// The unique identifier of the Payment method #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] pub payment_method_id: String, /// Whether payment method was deleted or not #[schema(example = true)] pub deleted: bool, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodDeleteResponse { /// The unique identifier of the Payment method #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerDefaultPaymentMethodResponse { /// The unique identifier of the Payment method #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] pub default_payment_method_id: Option<String>, /// The unique identifier of the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>,example = "credit")] pub payment_method_type: Option<api_enums::PaymentMethodType>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentMethodResponseItem { /// The unique identifier of the payment method. #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "credit")] pub payment_method_subtype: api_enums::PaymentMethodType, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// PaymentMethod Data from locker pub payment_method_data: Option<PaymentMethodListData>, /// Masked bank details from PM auth services #[schema(example = json!({"mask": "0000"}))] pub bank: Option<MaskedBankDetails>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: time::PrimitiveDateTime, /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601")] pub last_used_at: time::PrimitiveDateTime, /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub is_default: bool, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, ///The network token details for the payment method pub network_tokenization: Option<NetworkTokenResponse>, /// Whether psp_tokenization is enabled for the payment_method, this will be true when at least /// one multi-use token with status `Active` is available for the payment method pub psp_tokenization_enabled: bool, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodResponseItem { /// The unique identifier of the payment method. #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, /// Temporary Token for payment method in vault which gets refreshed for every payment #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")] pub payment_token: String, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "credit")] pub payment_method_subtype: api_enums::PaymentMethodType, /// Indicates whether the payment method is eligible for recurring payments #[schema(example = true)] pub recurring_enabled: bool, /// PaymentMethod Data from locker pub payment_method_data: Option<PaymentMethodListData>, /// Masked bank details from PM auth services #[schema(example = json!({"mask": "0000"}))] pub bank: Option<MaskedBankDetails>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: time::PrimitiveDateTime, /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub last_used_at: time::PrimitiveDateTime, /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub is_default: bool, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodListData { Card(CardDetailFromLocker), #[cfg(feature = "payouts")] #[schema(value_type = Bank)] Bank(payouts::Bank), } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethod { /// Token for payment method in temporary card locker which gets refreshed often #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")] pub payment_token: String, /// The unique identifier of the customer. #[schema(example = "pm_iouuy468iyuowqs")] pub payment_method_id: String, /// The unique identifier of the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>,example = "credit_card")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user #[schema(example = "Citibank")] pub payment_method_issuer: Option<String>, /// A standard code representing the issuer of payment method #[schema(value_type = Option<PaymentMethodIssuerCode>,example = "jp_applepay")] pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional. #[schema(example = true)] pub installment_payment_enabled: Option<bool>, /// Type of payment experience enabled with the connector #[schema(value_type = Option<Vec<PaymentExperience>>,example = json!(["redirect_to_url"]))] pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, /// Card details from card locker #[schema(example = json!({"last4": "1142","exp_month": "03","exp_year": "2030"}))] pub card: Option<CardDetailFromLocker>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = Option<PrimitiveDateTime>,example = "2023-01-18T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] #[serde(skip_serializing_if = "Option::is_none")] pub bank_transfer: Option<payouts::Bank>, /// Masked bank details from PM auth services #[schema(example = json!({"mask": "0000"}))] pub bank: Option<MaskedBankDetails>, /// Surcharge details for this saved card pub surcharge_details: Option<SurchargeDetailsResponse>, /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = Option<PrimitiveDateTime>,example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_used_at: Option<time::PrimitiveDateTime>, /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub default_payment_method_set: bool, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkRequest { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: Option<String>, /// The unique identifier of the customer. #[schema(value_type = String, example = "cus_92dnwed8s32bV9D8Snbiasd8v")] pub customer_id: id_type::CustomerId, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Redirect to this URL post completion #[schema(value_type = Option<String>, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1/status")] pub return_url: Option<String>, /// List of payment methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkResponse { /// The unique identifier for the collect link. #[schema(value_type = String, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: String, /// The unique identifier of the customer. #[schema(value_type = String, example = "cus_92dnwed8s32bV9D8Snbiasd8v")] pub customer_id: id_type::CustomerId, /// Time when this link will be expired in ISO8601 format #[schema(value_type = PrimitiveDateTime, example = "2025-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: time::PrimitiveDateTime, /// URL to the form's link generated for collecting payment method details. #[schema(value_type = String, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1")] pub link: masking::Secret<url::Url>, /// Redirect to this URL post completion #[schema(value_type = Option<String>, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1/status")] pub return_url: Option<String>, /// Collect link config used #[serde(flatten)] #[schema(value_type = GenericLinkUiConfig)] pub ui_config: link_utils::GenericLinkUiConfig, /// List of payment methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkRenderRequest { /// Unique identifier for a merchant. #[schema(example = "merchant_1671528864", value_type = String)] pub merchant_id: id_type::MerchantId, /// The unique identifier for the collect link. #[schema(value_type = String, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: String, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodCollectLinkDetails { pub publishable_key: masking::Secret<String>, pub client_secret: masking::Secret<String>, pub pm_collect_link_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: time::PrimitiveDateTime, pub return_url: Option<String>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodCollectLinkStatusDetails { pub pm_collect_link_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: time::PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: link_utils::PaymentMethodCollectStatus, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MaskedBankDetails { pub mask: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodId { pub payment_method_id: String, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DefaultPaymentMethod { #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, pub payment_method_id: String, } //------------------------------------------------TokenizeService------------------------------------------------ #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizePayloadEncrypted { pub payload: String, pub key_id: String, pub version: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizePayloadRequest { pub value1: String, pub value2: String, pub lookup_key: String, pub service_name: String, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct GetTokenizePayloadRequest { pub lookup_key: String, pub service_name: String, pub get_value2: bool, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct DeleteTokenizeByTokenRequest { pub lookup_key: String, pub service_name: String, } #[derive(Debug, serde::Serialize)] // Blocked: Yet to be implemented by `basilisk` pub struct DeleteTokenizeByDateRequest { pub buffer_minutes: i32, pub service_name: String, pub max_rows: i32, } #[derive(Debug, serde::Deserialize)] pub struct GetTokenizePayloadResponse { pub lookup_key: String, pub get_value2: Option<bool>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCardValue1 { pub card_number: String, pub exp_year: String, pub exp_month: String, pub name_on_card: Option<String>, pub nickname: Option<String>, pub card_last_four: Option<String>, pub card_token: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ListCountriesCurrenciesRequest { pub connector: api_enums::Connector, pub payment_method_type: api_enums::PaymentMethodType, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ListCountriesCurrenciesResponse { pub currencies: HashSet<api_enums::Currency>, pub countries: HashSet<CountryCodeWithName>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq)] pub struct CountryCodeWithName { pub code: api_enums::CountryAlpha2, pub name: api_enums::Country, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCardValue2 { pub card_security_code: Option<String>, pub card_fingerprint: Option<String>, pub external_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub payment_method_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletValue1 { pub data: payments::WalletData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankTransferValue1 { pub data: payments::BankTransferData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankTransferValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectValue1 { pub data: payments::BankRedirectData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PaymentMethodRecord { pub customer_id: id_type::CustomerId, pub name: Option<masking::Secret<String>>, pub email: Option<pii::Email>, pub phone: Option<masking::Secret<String>>, pub phone_country_code: Option<String>, pub merchant_id: Option<id_type::MerchantId>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_type: Option<api_enums::PaymentMethodType>, pub nick_name: Option<masking::Secret<String>>, pub payment_instrument_id: Option<masking::Secret<String>>, pub connector_customer_id: Option<String>, pub card_number_masked: masking::Secret<String>, pub card_expiry_month: masking::Secret<String>, pub card_expiry_year: masking::Secret<String>, pub card_scheme: Option<String>, pub original_transaction_id: Option<String>, pub billing_address_zip: Option<masking::Secret<String>>, pub billing_address_state: Option<masking::Secret<String>>, pub billing_address_first_name: Option<masking::Secret<String>>, pub billing_address_last_name: Option<masking::Secret<String>>, pub billing_address_city: Option<String>, pub billing_address_country: Option<api_enums::CountryAlpha2>, pub billing_address_line1: Option<masking::Secret<String>>, pub billing_address_line2: Option<masking::Secret<String>>, pub billing_address_line3: Option<masking::Secret<String>>, pub raw_card_number: Option<masking::Secret<String>>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub merchant_connector_ids: Option<String>, pub original_transaction_amount: Option<i64>, pub original_transaction_currency: Option<common_enums::Currency>, pub line_number: Option<i64>, pub network_token_number: Option<CardNumber>, pub network_token_expiry_month: Option<masking::Secret<String>>, pub network_token_expiry_year: Option<masking::Secret<String>>, pub network_token_requestor_ref_id: Option<String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct UpdatePaymentMethodRecord { pub payment_method_id: String, pub status: Option<common_enums::PaymentMethodStatus>, pub network_transaction_id: Option<String>, pub line_number: Option<i64>, pub payment_instrument_id: Option<masking::Secret<String>>, pub connector_customer_id: Option<String>, pub merchant_connector_ids: Option<String>, pub card_expiry_month: Option<masking::Secret<String>>, pub card_expiry_year: Option<masking::Secret<String>>, } #[derive(Debug, serde::Serialize)] pub struct PaymentMethodUpdateResponse { pub payment_method_id: String, pub status: Option<common_enums::PaymentMethodStatus>, pub network_transaction_id: Option<String>, pub connector_mandate_details: Option<pii::SecretSerdeValue>, pub update_status: UpdateStatus, #[serde(skip_serializing_if = "Option::is_none")] pub update_error: Option<String>, pub updated_payment_method_data: Option<bool>, pub connector_customer: Option<pii::SecretSerdeValue>, pub line_number: Option<i64>, } #[derive(Debug, Default, serde::Serialize)] pub struct PaymentMethodMigrationResponse { pub line_number: Option<i64>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method: Option<api_enums::PaymentMethod>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method_type: Option<api_enums::PaymentMethodType>, pub customer_id: Option<id_type::CustomerId>, pub migration_status: MigrationStatus, #[serde(skip_serializing_if = "Option::is_none")] pub migration_error: Option<String>, pub card_number_masked: Option<masking::Secret<String>>, pub card_migrated: Option<bool>, pub network_token_migrated: Option<bool>, pub connector_mandate_details_migrated: Option<bool>, pub network_transaction_id_migrated: Option<bool>, } #[derive(Debug, Default, serde::Serialize)] pub enum MigrationStatus { Success, #[default] Failed, } #[derive(Debug, Default, serde::Serialize)] pub enum UpdateStatus { Success, #[default] Failed, } impl PaymentMethodRecord { fn create_address(&self) -> Option<payments::AddressDetails> { if self.billing_address_first_name.is_some() && self.billing_address_line1.is_some() && self.billing_address_zip.is_some() && self.billing_address_city.is_some() && self.billing_address_country.is_some() { Some(payments::AddressDetails { city: self.billing_address_city.clone(), country: self.billing_address_country, line1: self.billing_address_line1.clone(), line2: self.billing_address_line2.clone(), state: self.billing_address_state.clone(), line3: self.billing_address_line3.clone(), zip: self.billing_address_zip.clone(), first_name: self.billing_address_first_name.clone(), last_name: self.billing_address_last_name.clone(), origin_zip: None, }) } else { None } } fn create_phone(&self) -> Option<payments::PhoneDetails> { if self.phone.is_some() || self.phone_country_code.is_some() { Some(payments::PhoneDetails { number: self.phone.clone(), country_code: self.phone_country_code.clone(), }) } else { None } } fn create_billing(&self) -> Option<payments::Address> { let address = self.create_address(); let phone = self.create_phone(); if address.is_some() || phone.is_some() || self.email.is_some() { Some(payments::Address { address, phone, email: self.email.clone(), }) } else { None } } } #[cfg(feature = "v1")] type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, ); #[cfg(feature = "v1")] type PaymentMethodUpdateResponseType = ( Result<PaymentMethodRecordUpdateResponse, String>, UpdatePaymentMethodRecord, ); #[cfg(feature = "v1")] impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponse { fn from((response, record): PaymentMethodMigrationResponseType) -> Self { match response { Ok(res) => Self { payment_method_id: Some(res.payment_method_response.payment_method_id), payment_method: res.payment_method_response.payment_method, payment_method_type: res.payment_method_response.payment_method_type, customer_id: res.payment_method_response.customer_id, migration_status: MigrationStatus::Success, migration_error: None, card_number_masked: Some(record.card_number_masked), line_number: record.line_number, card_migrated: res.card_migrated, network_token_migrated: res.network_token_migrated, connector_mandate_details_migrated: res.connector_mandate_details_migrated, network_transaction_id_migrated: res.network_transaction_id_migrated, }, Err(e) => Self { customer_id: Some(record.customer_id), migration_status: MigrationStatus::Failed, migration_error: Some(e), card_number_masked: Some(record.card_number_masked), line_number: record.line_number, ..Self::default() }, } } } #[cfg(feature = "v1")] impl From<PaymentMethodUpdateResponseType> for PaymentMethodUpdateResponse { fn from((response, record): PaymentMethodUpdateResponseType) -> Self { match response { Ok(res) => Self { payment_method_id: res.payment_method_id, status: Some(res.status), network_transaction_id: res.network_transaction_id, connector_mandate_details: res.connector_mandate_details, updated_payment_method_data: res.updated_payment_method_data, connector_customer: res.connector_customer, update_status: UpdateStatus::Success, update_error: None, line_number: record.line_number, }, Err(e) => Self { payment_method_id: record.payment_method_id, status: record.status, network_transaction_id: record.network_transaction_id, connector_mandate_details: None, updated_payment_method_data: None, connector_customer: None, update_status: UpdateStatus::Failed, update_error: Some(e), line_number: record.line_number, }, } } } impl TryFrom<( &PaymentMethodRecord, id_type::MerchantId, Option<&Vec<id_type::MerchantConnectorAccountId>>, )> for PaymentMethodMigrate { type Error = error_stack::Report<errors::ValidationError>; fn try_from( item: ( &PaymentMethodRecord, id_type::MerchantId, Option<&Vec<id_type::MerchantConnectorAccountId>>, ), ) -> Result<Self, Self::Error> { let (record, merchant_id, mca_ids) = item; let billing = record.create_billing(); let connector_mandate_details = if let Some(payment_instrument_id) = &record.payment_instrument_id { let ids = mca_ids.get_required_value("mca_ids")?; let mandate_map: HashMap<_, _> = ids .iter() .map(|mca_id| { ( mca_id.clone(), PaymentsMandateReferenceRecord { connector_mandate_id: payment_instrument_id.peek().to_string(), payment_method_type: record.payment_method_type, original_payment_authorized_amount: record.original_transaction_amount, original_payment_authorized_currency: record .original_transaction_currency, }, ) }) .collect(); Some(PaymentsMandateReference(mandate_map)) } else { None }; Ok(Self { merchant_id, customer_id: Some(record.customer_id.clone()), card: Some(MigrateCardDetail { card_number: record .raw_card_number .clone() .unwrap_or_else(|| record.card_number_masked.clone()), card_exp_month: record.card_expiry_month.clone(), card_exp_year: record.card_expiry_year.clone(), card_holder_name: record.name.clone(), card_network: None, card_type: None, card_issuer: None, card_issuing_country: None, nick_name: record.nick_name.clone(), }), network_token: Some(MigrateNetworkTokenDetail { network_token_data: MigrateNetworkTokenData { network_token_number: record.network_token_number.clone().unwrap_or_default(), network_token_exp_month: record .network_token_expiry_month .clone() .unwrap_or_default(), network_token_exp_year: record .network_token_expiry_year .clone() .unwrap_or_default(), card_holder_name: record.name.clone(), nick_name: record.nick_name.clone(), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, }, network_token_requestor_ref_id: record .network_token_requestor_ref_id .clone() .unwrap_or_default(), }), payment_method: record.payment_method, payment_method_type: record.payment_method_type, payment_method_issuer: None, billing, connector_mandate_details: connector_mandate_details.map( |payments_mandate_reference| { CommonMandateReference::from(payments_mandate_reference) }, ), metadata: None, payment_method_issuer_code: None, card_network: None, #[cfg(feature = "payouts")] bank_transfer: None, #[cfg(feature = "payouts")] wallet: None, payment_method_data: None, network_transaction_id: record.original_transaction_id.clone(), }) } } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardNetworkTokenizeRequest { /// Merchant ID associated with the tokenization request #[schema(example = "merchant_1671528864", value_type = String)] pub merchant_id: id_type::MerchantId, /// Details of the card or payment method to be tokenized #[serde(flatten)] pub data: TokenizeDataRequest, /// Customer details #[schema(value_type = CustomerDetails)] pub customer: payments::CustomerDetails, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The name of the bank/ provider issuing the payment method to the end user pub payment_method_issuer: Option<String>, } impl common_utils::events::ApiEventMetric for CardNetworkTokenizeRequest {} #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum TokenizeDataRequest { Card(TokenizeCardRequest), ExistingPaymentMethod(TokenizePaymentMethodRequest), } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct TokenizeCardRequest { /// Card Number #[schema(value_type = String, example = "4111111145551142")] pub raw_card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String, example = "10")] pub card_expiry_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String, example = "25")] pub card_expiry_year: masking::Secret<String>, /// The CVC number for the card #[schema(value_type = Option<String>, example = "242")] pub card_cvc: Option<masking::Secret<String>>, /// Card Holder Name #[schema(value_type = Option<String>, example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>, example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<CardType>, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TokenizePaymentMethodRequest { /// Payment method's ID #[serde(skip_deserializing)] pub payment_method_id: String, /// The CVC number for the card #[schema(value_type = Option<String>, example = "242")] pub card_cvc: Option<masking::Secret<String>>, } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardNetworkTokenizeResponse { /// Response for payment method entry in DB pub payment_method_response: Option<PaymentMethodResponse>, /// Customer details #[schema(value_type = CustomerDetails)] pub customer: Option<payments::CustomerDetails>, /// Card network tokenization status pub card_tokenized: bool, /// Error code #[serde(skip_serializing_if = "Option::is_none")] pub error_code: Option<String>, /// Error message #[serde(skip_serializing_if = "Option::is_none")] pub error_message: Option<String>, /// Details that were sent for tokenization #[serde(skip_serializing_if = "Option::is_none")] pub tokenization_data: Option<TokenizeDataRequest>, } impl common_utils::events::ApiEventMetric for CardNetworkTokenizeResponse {} impl From<&Card> for MigrateCardDetail { fn from(card: &Card) -> Self { Self { card_number: masking::Secret::new(card.card_number.get_card_no()), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.name_on_card.clone(), nick_name: card .nick_name .as_ref() .map(|name| masking::Secret::new(name.clone())), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionRequest { /// The customer id for which the payment methods session is to be created #[schema(value_type = String, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::GlobalCustomerId, /// The billing address details of the customer. This will also be used for any new payment methods added during the session #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The return url to which the customer should be redirected to after adding the payment method #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, /// The time (seconds ) when the session will expire /// If not provided, the session will expire in 15 minutes #[schema(example = 900, default = 900)] pub expires_in: Option<u32>, /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data #[schema(value_type = Option<serde_json::Value>)] pub tokenization_data: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodsSessionUpdateRequest { /// The billing address details of the customer. This will also be used for any new payment methods added during the session #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data #[schema(value_type = Option<serde_json::Value>)] pub tokenization_data: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionUpdateSavedPaymentMethod { /// The payment method id of the payment method to be updated #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: id_type::GlobalPaymentMethodId, /// The update request for the payment method update #[serde(flatten)] pub payment_method_update_request: PaymentMethodUpdate, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionDeleteSavedPaymentMethod { /// The payment method id of the payment method to be updated #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: id_type::GlobalPaymentMethodId, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionConfirmRequest { /// The payment method type #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype #[schema(value_type = PaymentMethodType, example = "google_pay")] pub payment_method_subtype: common_enums::PaymentMethodType, /// The payment instrument data to be used for the payment #[schema(value_type = PaymentMethodDataRequest)] pub payment_method_data: payments::PaymentMethodDataRequest, /// The return url to which the customer should be redirected to after adding the payment method #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionResponse { #[schema(value_type = String, example = "12345_pms_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodSessionId, /// The customer id for which the payment methods session is to be created #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] pub customer_id: id_type::GlobalCustomerId, /// The billing address details of the customer. This will also be used for any new payment methods added during the session #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data #[schema(value_type = Option<serde_json::Value>)] pub tokenization_data: Option<pii::SecretSerdeValue>, /// The iso timestamp when the session will expire /// Trying to retrieve the session or any operations on the session after this time will result in an error #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_at: time::PrimitiveDateTime, /// Client Secret #[schema(value_type = String)] pub client_secret: masking::Secret<String>, /// The return url to which the user should be redirected to #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The next action details for the payment method session #[schema(value_type = Option<NextActionData>)] pub next_action: Option<payments::NextActionData>, /// The customer authentication details for the payment method /// This refers to either the payment / external authentication details pub authentication_details: Option<AuthenticationDetails>, /// The payment method that was created using this payment method session #[schema(value_type = Option<Vec<String>>)] pub associated_payment_methods: Option<Vec<String>>, /// The token-id created if there is tokenization_data present #[schema(value_type = Option<String>, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] pub associated_token_id: Option<id_type::GlobalTokenId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema, Clone)] pub struct AuthenticationDetails { /// The status of authentication for the payment method #[schema(value_type = IntentStatus)] pub status: common_enums::IntentStatus, /// Error details of the authentication #[schema(value_type = Option<ErrorDetails>)] pub error: Option<payments::ErrorDetails>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct NetworkTokenStatusCheckSuccessResponse { /// The status of the network token #[schema(value_type = TokenStatus)] pub status: api_enums::TokenStatus, /// The expiry month of the network token if active #[schema(value_type = String)] pub token_expiry_month: masking::Secret<String>, /// The expiry year of the network token if active #[schema(value_type = String)] pub token_expiry_year: masking::Secret<String>, /// The last four digits of the card pub card_last_four: String, /// The last four digits of the network token pub token_last_four: String, /// The expiry date of the card in MM/YY format pub card_expiry: String, /// The payment method ID that was checked #[schema(value_type = String, example = "12345_pm_019959146f92737389eb6927ce1eb7dc")] pub payment_method_id: id_type::GlobalPaymentMethodId, /// The customer ID associated with the payment method #[schema(value_type = String, example = "12345_cus_0195dc62bb8e7312a44484536da76aef")] pub customer_id: id_type::GlobalCustomerId, } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for NetworkTokenStatusCheckResponse {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct NetworkTokenStatusCheckFailureResponse { /// Error message describing what went wrong pub error_message: String, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NetworkTokenStatusCheckResponse { /// Successful network token status check response SuccessResponse(NetworkTokenStatusCheckSuccessResponse), /// Error response for network token status check FailureResponse(NetworkTokenStatusCheckFailureResponse), }
crates/api_models/src/payment_methods.rs
api_models::src::payment_methods
29,259
true
// File: crates/api_models/src/verifications.rs // Module: api_models::src::verifications use common_utils::id_type; /// The request body for verification of merchant (everything except domain_names are prefilled) #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayMerchantVerificationConfigs { pub domain_names: Vec<String>, pub encrypt_to: String, pub partner_internal_merchant_identifier: String, pub partner_merchant_name: String, } /// The derivation point for domain names from request body #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayMerchantVerificationRequest { pub domain_names: Vec<String>, pub merchant_connector_account_id: id_type::MerchantConnectorAccountId, } /// Response to be sent for the verify/applepay api #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayMerchantResponse { pub status_message: String, } /// QueryParams to be send by the merchant for fetching the verified domains #[derive(Debug, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayGetVerifiedDomainsParam { pub merchant_id: id_type::MerchantId, pub merchant_connector_account_id: id_type::MerchantConnectorAccountId, } /// Response to be sent for derivation of the already verified domains #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayVerifiedDomainsResponse { pub verified_domains: Vec<String>, }
crates/api_models/src/verifications.rs
api_models::src::verifications
348
true
// File: crates/api_models/src/connector_enums.rs // Module: api_models::src::connector_enums pub use common_enums::connector_enums::Connector;
crates/api_models/src/connector_enums.rs
api_models::src::connector_enums
37
true
// File: crates/api_models/src/proxy.rs // Module: api_models::src::proxy use std::collections::HashMap; use common_utils::request::Method; use reqwest::header::HeaderMap; use serde::{Deserialize, Serialize}; use serde_json::Value; use utoipa::ToSchema; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Headers(pub HashMap<String, String>); impl Headers { pub fn as_map(&self) -> &HashMap<String, String> { &self.0 } pub fn from_header_map(headers: Option<&HeaderMap>) -> Self { headers .map(|h| { let map = h .iter() .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())) .collect(); Self(map) }) .unwrap_or_else(|| Self(HashMap::new())) } } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct ProxyRequest { /// The request body that needs to be forwarded pub request_body: Value, /// The destination URL where the request needs to be forwarded #[schema(value_type = String, example = "https://api.example.com/endpoint")] pub destination_url: url::Url, /// The headers that need to be forwarded #[schema(value_type = Object, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub headers: Headers, /// The method that needs to be used for the request #[schema(value_type = Method, example = "Post")] pub method: Method, /// The vault token that is used to fetch sensitive data from the vault pub token: String, /// The type of token that is used to fetch sensitive data from the vault #[schema(value_type = TokenType, example = "payment_method_id")] pub token_type: TokenType, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum TokenType { TokenizationId, PaymentMethodId, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct ProxyResponse { /// The response received from the destination pub response: Value, /// The status code of the response pub status_code: u16, /// The headers of the response #[schema(value_type = Object, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub response_headers: Headers, } impl common_utils::events::ApiEventMetric for ProxyRequest {} impl common_utils::events::ApiEventMetric for ProxyResponse {}
crates/api_models/src/proxy.rs
api_models::src::proxy
583
true
// File: crates/api_models/src/events.rs // Module: api_models::src::events pub mod apple_pay_certificates_migration; pub mod chat; pub mod connector_onboarding; pub mod customer; pub mod dispute; pub mod external_service_auth; pub mod gsm; mod locker_migration; pub mod payment; #[cfg(feature = "payouts")] pub mod payouts; #[cfg(feature = "recon")] pub mod recon; pub mod refund; #[cfg(feature = "v2")] pub mod revenue_recovery; pub mod routing; pub mod user; pub mod user_role; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, impl_api_event_type, }; use crate::customers::CustomerListRequest; #[cfg(feature = "tokenization_v2")] use crate::tokenization; #[allow(unused_imports)] use crate::{ admin::*, analytics::{ api_event::*, auth_events::*, connector_events::ConnectorEventsRequest, outgoing_webhook_event::OutgoingWebhookLogsRequest, routing_events::RoutingEventsRequest, sdk_events::*, search::*, *, }, api_keys::*, cards_info::*, disputes::*, files::*, mandates::*, organization::{ OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest, }, payment_methods::*, payments::*, user::{UserKeyTransferRequest, UserTransferKeyResponse}, verifications::*, }; impl ApiEventMetric for GetPaymentIntentFiltersRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Analytics) } } impl ApiEventMetric for GetPaymentIntentMetricRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Analytics) } } impl ApiEventMetric for PaymentIntentFiltersResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Analytics) } } impl_api_event_type!( Miscellaneous, ( PaymentMethodId, PaymentMethodCreate, PaymentLinkInitiateRequest, RetrievePaymentLinkResponse, MandateListConstraints, CreateFileResponse, MerchantConnectorResponse, MerchantConnectorId, MandateResponse, MandateRevokedResponse, RetrievePaymentLinkRequest, PaymentLinkListConstraints, MandateId, DisputeListGetConstraints, RetrieveApiKeyResponse, ProfileResponse, ProfileUpdate, ProfileCreate, RevokeApiKeyResponse, ToggleKVResponse, ToggleKVRequest, ToggleAllKVRequest, ToggleAllKVResponse, MerchantAccountDeleteResponse, MerchantAccountUpdate, CardInfoResponse, CreateApiKeyResponse, CreateApiKeyRequest, ListApiKeyConstraints, MerchantConnectorDeleteResponse, MerchantConnectorUpdate, MerchantConnectorCreate, MerchantId, CardsInfoRequest, MerchantAccountResponse, MerchantAccountListRequest, MerchantAccountCreate, PaymentsSessionRequest, ApplepayMerchantVerificationRequest, ApplepayMerchantResponse, ApplepayVerifiedDomainsResponse, UpdateApiKeyRequest, GetApiEventFiltersRequest, ApiEventFiltersResponse, GetInfoResponse, GetPaymentMetricRequest, GetRefundMetricRequest, GetActivePaymentsMetricRequest, GetSdkEventMetricRequest, GetAuthEventMetricRequest, GetAuthEventFilterRequest, GetPaymentFiltersRequest, PaymentFiltersResponse, GetRefundFilterRequest, RefundFiltersResponse, AuthEventFiltersResponse, GetSdkEventFiltersRequest, SdkEventFiltersResponse, ApiLogsRequest, GetApiEventMetricRequest, SdkEventsRequest, ReportRequest, ConnectorEventsRequest, OutgoingWebhookLogsRequest, GetGlobalSearchRequest, GetSearchRequest, GetSearchResponse, GetSearchRequestWithIndex, GetDisputeFilterRequest, DisputeFiltersResponse, GetDisputeMetricRequest, SankeyResponse, OrganizationResponse, OrganizationCreateRequest, OrganizationUpdateRequest, OrganizationId, CustomerListRequest, RoutingEventsRequest ) ); impl_api_event_type!( Keymanager, ( TransferKeyResponse, MerchantKeyTransferRequest, UserKeyTransferRequest, UserTransferKeyResponse ) ); impl<T> ApiEventMetric for MetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } impl<T> ApiEventMetric for PaymentsMetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } impl<T> ApiEventMetric for PaymentIntentsMetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } impl<T> ApiEventMetric for RefundsMetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } impl<T> ApiEventMetric for DisputesMetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } impl<T> ApiEventMetric for AuthEventMetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentMethodIntentConfirmInternal { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), payment_method_type: Some(self.request.payment_method_type), payment_method_subtype: Some(self.request.payment_method_subtype), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentMethodIntentCreate { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodCreate) } } impl ApiEventMetric for DisputeListFilters { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentMethodSessionRequest {} #[cfg(feature = "v2")] impl ApiEventMetric for PaymentMethodsSessionUpdateRequest {} #[cfg(feature = "v2")] impl ApiEventMetric for PaymentMethodSessionResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodSession { payment_method_session_id: self.id.clone(), }) } } #[cfg(feature = "tokenization_v2")] impl ApiEventMetric for tokenization::GenericTokenizationRequest {} #[cfg(feature = "tokenization_v2")] impl ApiEventMetric for tokenization::GenericTokenizationResponse {} #[cfg(feature = "tokenization_v2")] impl ApiEventMetric for tokenization::DeleteTokenDataResponse {} #[cfg(feature = "tokenization_v2")] impl ApiEventMetric for tokenization::DeleteTokenDataRequest {}
crates/api_models/src/events.rs
api_models::src::events
1,525
true
// File: crates/api_models/src/open_router.rs // Module: api_models::src::open_router use std::{collections::HashMap, fmt::Debug}; use common_utils::{errors, id_type, types::MinorUnit}; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, }, }; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::{ enums::{Currency, PaymentMethod}, payment_methods, }; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct OpenRouterDecideGatewayRequest { pub payment_info: PaymentInfo, #[schema(value_type = String)] pub merchant_id: id_type::ProfileId, pub eligible_gateway_list: Option<Vec<String>>, pub ranking_algorithm: Option<RankingAlgorithm>, pub elimination_enabled: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct DecideGatewayResponse { pub decided_gateway: Option<String>, pub gateway_priority_map: Option<serde_json::Value>, pub filter_wise_gateways: Option<serde_json::Value>, pub priority_logic_tag: Option<String>, pub routing_approach: Option<String>, pub gateway_before_evaluation: Option<String>, pub priority_logic_output: Option<PriorityLogicOutput>, pub reset_approach: Option<String>, pub routing_dimension: Option<String>, pub routing_dimension_level: Option<String>, pub is_scheduled_outage: Option<bool>, pub is_dynamic_mga_enabled: Option<bool>, pub gateway_mga_id_map: Option<serde_json::Value>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct PriorityLogicOutput { pub is_enforcement: Option<bool>, pub gws: Option<Vec<String>>, pub priority_logic_tag: Option<String>, pub gateway_reference_ids: Option<HashMap<String, String>>, pub primary_logic: Option<PriorityLogicData>, pub fallback_logic: Option<PriorityLogicData>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PriorityLogicData { pub name: Option<String>, pub status: Option<String>, pub failure_reason: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RankingAlgorithm { SrBasedRouting, PlBasedRouting, NtwBasedRouting, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct PaymentInfo { #[schema(value_type = String)] pub payment_id: id_type::PaymentId, pub amount: MinorUnit, pub currency: Currency, // customerId: Option<ETCu::CustomerId>, // preferredGateway: Option<ETG::Gateway>, pub payment_type: String, pub metadata: Option<String>, // internalMetadata: Option<String>, // isEmi: Option<bool>, // emiBank: Option<String>, // emiTenure: Option<i32>, pub payment_method_type: String, pub payment_method: PaymentMethod, // paymentSource: Option<String>, // authType: Option<ETCa::txn_card_info::AuthType>, // cardIssuerBankName: Option<String>, pub card_isin: Option<String>, // cardType: Option<ETCa::card_type::CardType>, // cardSwitchProvider: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct DecidedGateway { pub gateway_priority_map: Option<HashMap<String, f64>>, pub debit_routing_output: Option<DebitRoutingOutput>, pub routing_approach: String, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct DebitRoutingOutput { pub co_badged_card_networks_info: CoBadgedCardNetworks, pub issuer_country: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, pub card_type: common_enums::CardType, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct CoBadgedCardNetworksInfo { pub network: common_enums::CardNetwork, pub saving_percentage: f64, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct CoBadgedCardNetworks(pub Vec<CoBadgedCardNetworksInfo>); impl CoBadgedCardNetworks { pub fn get_card_networks(&self) -> Vec<common_enums::CardNetwork> { self.0.iter().map(|info| info.network.clone()).collect() } pub fn get_signature_network(&self) -> Option<common_enums::CardNetwork> { self.0 .iter() .find(|info| info.network.is_signature_network()) .map(|info| info.network.clone()) } } impl From<&DebitRoutingOutput> for payment_methods::CoBadgedCardData { fn from(output: &DebitRoutingOutput) -> Self { Self { co_badged_card_networks_info: output.co_badged_card_networks_info.clone(), issuer_country_code: output.issuer_country, is_regulated: output.is_regulated, regulated_name: output.regulated_name.clone(), } } } impl TryFrom<(payment_methods::CoBadgedCardData, String)> for DebitRoutingRequestData { type Error = error_stack::Report<errors::ParsingError>; fn try_from( (output, card_type): (payment_methods::CoBadgedCardData, String), ) -> Result<Self, Self::Error> { let parsed_card_type = card_type.parse::<common_enums::CardType>().map_err(|_| { error_stack::Report::new(errors::ParsingError::EnumParseFailure("CardType")) })?; Ok(Self { co_badged_card_networks_info: output.co_badged_card_networks_info.get_card_networks(), issuer_country: output.issuer_country_code, is_regulated: output.is_regulated, regulated_name: output.regulated_name, card_type: parsed_card_type, }) } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CoBadgedCardRequest { pub merchant_category_code: common_enums::DecisionEngineMerchantCategoryCode, pub acquirer_country: common_enums::CountryAlpha2, pub co_badged_card_data: Option<DebitRoutingRequestData>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DebitRoutingRequestData { pub co_badged_card_networks_info: Vec<common_enums::CardNetwork>, pub issuer_country: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, pub card_type: common_enums::CardType, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ErrorResponse { pub status: String, pub error_code: String, pub error_message: String, pub priority_logic_tag: Option<String>, pub filter_wise_gateways: Option<serde_json::Value>, pub error_info: UnifiedError, pub is_dynamic_mga_enabled: bool, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct UnifiedError { pub code: String, pub user_message: String, pub developer_message: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)] #[serde(rename_all = "camelCase")] pub struct UpdateScorePayload { #[schema(value_type = String)] pub merchant_id: id_type::ProfileId, pub gateway: String, pub status: TxnStatus, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] pub struct UpdateScoreResponse { pub message: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TxnStatus { Started, AuthenticationFailed, JuspayDeclined, PendingVbv, VBVSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CODInitiated, Voided, VoidedPostCharge, VoidInitiated, Nop, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, ToBeCharged, Pending, Failure, Declined, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct DecisionEngineConfigSetupRequest { pub merchant_id: String, pub config: DecisionEngineConfigVariant, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GetDecisionEngineConfigRequest { pub merchant_id: String, pub algorithm: DecisionEngineDynamicAlgorithmType, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub enum DecisionEngineDynamicAlgorithmType { SuccessRate, Elimination, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(tag = "type", content = "data")] #[serde(rename_all = "camelCase")] pub enum DecisionEngineConfigVariant { SuccessRate(DecisionEngineSuccessRateData), Elimination(DecisionEngineEliminationData), } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineSuccessRateData { pub default_latency_threshold: Option<f64>, pub default_bucket_size: Option<i32>, pub default_hedging_percent: Option<f64>, pub default_lower_reset_factor: Option<f64>, pub default_upper_reset_factor: Option<f64>, pub default_gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>, pub sub_level_input_config: Option<Vec<DecisionEngineSRSubLevelInputConfig>>, } impl DecisionEngineSuccessRateData { pub fn update(&mut self, new_config: Self) { if let Some(threshold) = new_config.default_latency_threshold { self.default_latency_threshold = Some(threshold); } if let Some(bucket_size) = new_config.default_bucket_size { self.default_bucket_size = Some(bucket_size); } if let Some(hedging_percent) = new_config.default_hedging_percent { self.default_hedging_percent = Some(hedging_percent); } if let Some(lower_reset_factor) = new_config.default_lower_reset_factor { self.default_lower_reset_factor = Some(lower_reset_factor); } if let Some(upper_reset_factor) = new_config.default_upper_reset_factor { self.default_upper_reset_factor = Some(upper_reset_factor); } if let Some(gateway_extra_score) = new_config.default_gateway_extra_score { self.default_gateway_extra_score .as_mut() .map(|score| score.extend(gateway_extra_score)); } if let Some(sub_level_input_config) = new_config.sub_level_input_config { self.sub_level_input_config.as_mut().map(|config| { config.extend(sub_level_input_config); }); } } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineSRSubLevelInputConfig { pub payment_method_type: Option<String>, pub payment_method: Option<String>, pub latency_threshold: Option<f64>, pub bucket_size: Option<i32>, pub hedging_percent: Option<f64>, pub lower_reset_factor: Option<f64>, pub upper_reset_factor: Option<f64>, pub gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>, } impl DecisionEngineSRSubLevelInputConfig { pub fn update(&mut self, new_config: Self) { if let Some(payment_method_type) = new_config.payment_method_type { self.payment_method_type = Some(payment_method_type); } if let Some(payment_method) = new_config.payment_method { self.payment_method = Some(payment_method); } if let Some(latency_threshold) = new_config.latency_threshold { self.latency_threshold = Some(latency_threshold); } if let Some(bucket_size) = new_config.bucket_size { self.bucket_size = Some(bucket_size); } if let Some(hedging_percent) = new_config.hedging_percent { self.hedging_percent = Some(hedging_percent); } if let Some(lower_reset_factor) = new_config.lower_reset_factor { self.lower_reset_factor = Some(lower_reset_factor); } if let Some(upper_reset_factor) = new_config.upper_reset_factor { self.upper_reset_factor = Some(upper_reset_factor); } if let Some(gateway_extra_score) = new_config.gateway_extra_score { self.gateway_extra_score .as_mut() .map(|score| score.extend(gateway_extra_score)); } } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineGatewayWiseExtraScore { pub gateway_name: String, pub gateway_sigma_factor: f64, } impl DecisionEngineGatewayWiseExtraScore { pub fn update(&mut self, new_config: Self) { self.gateway_name = new_config.gateway_name; self.gateway_sigma_factor = new_config.gateway_sigma_factor; } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineEliminationData { pub threshold: f64, } impl DecisionEngineEliminationData { pub fn update(&mut self, new_config: Self) { self.threshold = new_config.threshold; } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct MerchantAccount { pub merchant_id: String, pub gateway_success_rate_based_decider_input: Option<String>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct FetchRoutingConfig { pub merchant_id: String, pub algorithm: AlgorithmType, } #[derive(Debug, Serialize, Deserialize, Clone, Copy)] #[serde(rename_all = "camelCase")] pub enum AlgorithmType { SuccessRate, Elimination, DebitRouting, }
crates/api_models/src/open_router.rs
api_models::src::open_router
3,078
true
// File: crates/api_models/src/refunds.rs // Module: api_models::src::refunds use std::collections::HashMap; pub use common_utils::types::MinorUnit; use common_utils::{pii, types::TimeRange}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use super::payments::AmountFilter; #[cfg(feature = "v1")] use crate::admin; use crate::{admin::MerchantConnectorInfo, enums}; #[cfg(feature = "v1")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundRequest { /// The payment id against which refund is to be initiated #[schema( max_length = 30, min_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: common_utils::id_type::PaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. If this is not passed by the merchant, this field shall be auto generated and provided in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: Option<String>, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the full payment amount #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] pub amount: Option<MinorUnit>, /// Reason for the refund. Often useful for displaying to users and your customer support executive. In case the payment went through Stripe, this field needs to be passed with one of these enums: `duplicate`, `fraudulent`, or `requested_by_customer` #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// To indicate whether to refund needs to be instant or scheduled. Default value is instant #[schema(default = "Instant", example = "Instant")] pub refund_type: Option<RefundType>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>)] pub split_refunds: Option<common_types::refunds::SplitRefund>, } #[cfg(feature = "v2")] #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundsCreateRequest { /// The payment id against which refund is initiated #[schema( max_length = 30, min_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: common_utils::id_type::GlobalPaymentId, /// Unique Identifier for the Refund given by the Merchant. #[schema( max_length = 64, min_length = 1, example = "ref_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub merchant_reference_id: common_utils::id_type::RefundReferenceId, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the amount_captured of the payment #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] pub amount: Option<MinorUnit>, /// Reason for the refund. Often useful for displaying to users and your customer support executive. #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// To indicate whether to refund needs to be instant or scheduled. Default value is instant #[schema(default = "Instant", example = "Instant")] pub refund_type: Option<RefundType>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v1")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrieveBody { pub force_sync: Option<bool>, } #[cfg(feature = "v2")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrieveBody { pub force_sync: Option<bool>, } #[cfg(feature = "v2")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrievePayload { /// `force_sync` with the connector to get refund details pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v1")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RefundsRetrieveRequest { /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: String, /// `force_sync` with the connector to get refund details /// (defaults to false) pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RefundsRetrieveRequest { /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: common_utils::id_type::GlobalRefundId, /// `force_sync` with the connector to get refund details /// (defaults to false) pub force_sync: Option<bool>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundUpdateRequest { #[serde(skip)] pub refund_id: String, /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundMetadataUpdateRequest { /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundManualUpdateRequest { #[serde(skip)] pub refund_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The status for refund pub status: Option<RefundStatus>, /// The code for the error pub error_code: Option<String>, /// The error message pub error_message: Option<String>, } #[cfg(feature = "v1")] /// To indicate whether to refund needs to be instant or scheduled #[derive( Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, )] #[serde(rename_all = "snake_case")] pub enum RefundType { Scheduled, #[default] Instant, } #[cfg(feature = "v2")] /// To indicate whether the refund needs to be instant or scheduled #[derive( Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, )] #[serde(rename_all = "snake_case")] pub enum RefundType { Scheduled, #[default] Instant, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { /// Unique Identifier for the refund pub refund_id: String, /// The payment id against which refund is initiated #[schema(value_type = String)] pub payment_id: common_utils::id_type::PaymentId, /// The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc #[schema(value_type = i64 , minimum = 100, example = 6540)] pub amount: MinorUnit, /// The three-letter ISO currency code pub currency: String, /// The status for refund pub status: RefundStatus, /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive pub reason: Option<String>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, /// The error message pub error_message: Option<String>, /// The code for the error pub error_code: Option<String>, /// Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// The timestamp at which refund is created #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, /// The timestamp at which refund is updated #[serde(with = "common_utils::custom_serde::iso8601::option")] pub updated_at: Option<PrimitiveDateTime>, /// The connector used for the refund and the corresponding payment #[schema(example = "stripe")] pub connector: String, /// The id of business profile for this refund #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The merchant_connector_id of the processor through which this payment went through #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>,)] pub split_refunds: Option<common_types::refunds::SplitRefund>, /// Error code received from the issuer in case of failed refunds pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed refunds pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] impl RefundResponse { pub fn get_refund_id_as_string(&self) -> String { self.refund_id.clone() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { /// Global Refund Id for the refund #[schema(value_type = String)] pub id: common_utils::id_type::GlobalRefundId, /// The payment id against which refund is initiated #[schema(value_type = String)] pub payment_id: common_utils::id_type::GlobalPaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4", value_type = Option<String>, )] pub merchant_reference_id: Option<common_utils::id_type::RefundReferenceId>, /// The refund amount #[schema(value_type = i64 , minimum = 100, example = 6540)] pub amount: MinorUnit, /// The three-letter ISO currency code #[schema(value_type = Currency)] pub currency: common_enums::Currency, /// The status for refund pub status: RefundStatus, /// An arbitrary string attached to the object pub reason: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, /// The error details for the refund pub error_details: Option<RefundErrorDetails>, /// The timestamp at which refund is created #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The timestamp at which refund is updated #[serde(with = "common_utils::custom_serde::iso8601")] pub updated_at: PrimitiveDateTime, /// The connector used for the refund and the corresponding payment #[schema(example = "stripe", value_type = Connector)] pub connector: enums::Connector, /// The id of business profile for this refund #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, /// The merchant_connector_id of the processor through which this payment went through #[schema(value_type = String)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// The reference id of the connector for the refund pub connector_refund_reference_id: Option<String>, } #[cfg(feature = "v2")] impl RefundResponse { pub fn get_refund_id_as_string(&self) -> String { self.id.get_string_repr().to_owned() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundErrorDetails { pub code: String, pub message: String, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundListRequest { /// The identifier for the payment #[schema(value_type = Option<String>)] pub payment_id: Option<common_utils::id_type::PaymentId>, /// The identifier for the refund pub refund_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// Limit on the number of objects to return pub limit: Option<i64>, /// The starting point within a list of objects pub offset: Option<i64>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc) #[serde(flatten)] pub time_range: Option<TimeRange>, /// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range) pub amount_filter: Option<AmountFilter>, /// The list of connectors to filter refunds list pub connector: Option<Vec<String>>, /// The list of merchant connector ids to filter the refunds list for selected label #[schema(value_type = Option<Vec<String>>)] pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, /// The list of currencies to filter refunds list #[schema(value_type = Option<Vec<Currency>>)] pub currency: Option<Vec<enums::Currency>>, /// The list of refund statuses to filter refunds list #[schema(value_type = Option<Vec<RefundStatus>>)] pub refund_status: Option<Vec<enums::RefundStatus>>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundListRequest { /// The identifier for the payment #[schema(value_type = Option<String>)] pub payment_id: Option<common_utils::id_type::GlobalPaymentId>, /// The identifier for the refund #[schema(value_type = String)] pub refund_id: Option<common_utils::id_type::GlobalRefundId>, /// Limit on the number of objects to return pub limit: Option<i64>, /// The starting point within a list of objects pub offset: Option<i64>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc) #[serde(flatten)] pub time_range: Option<TimeRange>, /// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range) pub amount_filter: Option<AmountFilter>, /// The list of connectors to filter refunds list pub connector: Option<Vec<String>>, /// The list of merchant connector ids to filter the refunds list for selected label #[schema(value_type = Option<Vec<String>>)] pub connector_id_list: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, /// The list of currencies to filter refunds list #[schema(value_type = Option<Vec<Currency>>)] pub currency: Option<Vec<enums::Currency>>, /// The list of refund statuses to filter refunds list #[schema(value_type = Option<Vec<RefundStatus>>)] pub refund_status: Option<Vec<enums::RefundStatus>>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)] pub struct RefundListResponse { /// The number of refunds included in the list pub count: usize, /// The total number of refunds in the list pub total_count: i64, /// The List of refund response object pub data: Vec<RefundResponse>, } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, ToSchema)] pub struct RefundListMetaData { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<enums::Currency>, /// The list of available refund status filters #[schema(value_type = Vec<RefundStatus>)] pub refund_status: Vec<enums::RefundStatus>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RefundListFilters { /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<enums::Currency>, /// The list of available refund status filters #[schema(value_type = Vec<RefundStatus>)] pub refund_status: Vec<enums::RefundStatus>, } #[derive(Clone, Debug, serde::Serialize)] pub struct RefundAggregateResponse { /// The list of refund status with their count pub status_with_count: HashMap<enums::RefundStatus, i64>, } /// The status for refunds #[derive( Debug, Eq, Clone, Copy, PartialEq, Default, Deserialize, Serialize, ToSchema, strum::Display, strum::EnumIter, )] #[serde(rename_all = "snake_case")] pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, } impl From<enums::RefundStatus> for RefundStatus { fn from(status: enums::RefundStatus) -> Self { match status { enums::RefundStatus::Failure | enums::RefundStatus::TransactionFailure => Self::Failed, enums::RefundStatus::ManualReview => Self::Review, enums::RefundStatus::Pending => Self::Pending, enums::RefundStatus::Success => Self::Succeeded, } } } impl From<RefundStatus> for enums::RefundStatus { fn from(status: RefundStatus) -> Self { match status { RefundStatus::Failed => Self::Failure, RefundStatus::Review => Self::ManualReview, RefundStatus::Pending => Self::Pending, RefundStatus::Succeeded => Self::Success, } } }
crates/api_models/src/refunds.rs
api_models::src::refunds
5,319
true
// File: crates/api_models/src/organization.rs // Module: api_models::src::organization use common_enums::OrganizationType; use common_utils::{id_type, pii}; use utoipa::ToSchema; pub struct OrganizationNew { pub org_id: id_type::OrganizationId, pub org_type: OrganizationType, pub org_name: Option<String>, } impl OrganizationNew { pub fn new(org_type: OrganizationType, org_name: Option<String>) -> Self { Self { org_id: id_type::OrganizationId::default(), org_type, org_name, } } } #[derive(Clone, Debug, serde::Serialize)] pub struct OrganizationId { pub organization_id: id_type::OrganizationId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OrganizationCreateRequest { /// Name of the organization pub organization_name: String, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OrganizationUpdateRequest { /// Name of the organization pub organization_name: Option<String>, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, /// Platform merchant id is unique distiguisher for special merchant in the platform org #[schema(value_type = String)] pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct OrganizationResponse { /// The unique identifier for the Organization #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: id_type::OrganizationId, /// Name of the Organization pub organization_name: Option<String>, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: time::PrimitiveDateTime, pub created_at: time::PrimitiveDateTime, /// Organization Type of the organization #[schema(value_type = Option<OrganizationType>, example = "standard")] pub organization_type: Option<OrganizationType>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct OrganizationResponse { /// The unique identifier for the Organization #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub id: id_type::OrganizationId, /// Name of the Organization pub organization_name: Option<String>, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: time::PrimitiveDateTime, pub created_at: time::PrimitiveDateTime, /// Organization Type of the organization #[schema(value_type = Option<OrganizationType>, example = "standard")] pub organization_type: Option<OrganizationType>, }
crates/api_models/src/organization.rs
api_models::src::organization
890
true
// File: crates/api_models/src/payouts.rs // Module: api_models::src::payouts use std::collections::HashMap; use cards::CardNumber; #[cfg(feature = "v2")] use common_utils::types::BrowserInformation; use common_utils::{ consts::default_payouts_list_limit, crypto, id_type, link_utils, payout_method_utils, pii::{self, Email}, transformers::ForeignFrom, types::{UnifiedCode, UnifiedMessage}, }; use masking::Secret; #[cfg(feature = "v1")] use payments::BrowserInformation; use router_derive::FlatStruct; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{enums as api_enums, payment_methods::RequiredFieldInfo, payments}; #[derive(Debug, Serialize, Clone, ToSchema)] pub enum PayoutRequest { PayoutActionRequest(PayoutActionRequest), PayoutCreateRequest(Box<PayoutCreateRequest>), PayoutRetrieveRequest(PayoutRetrieveRequest), } #[derive( Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PayoutCreateRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts that have been done by a single merchant. This field is auto generated and is returned in the API response, **not required to be included in the Payout Create/Update Request.** #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub payout_id: Option<id_type::PayoutId>, /// This is an identifier for the merchant account. This is inferred from the API key provided during the request, **not required to be included in the Payout Create/Update Request.** #[schema(max_length = 255, value_type = Option<String>, example = "merchant_1668273825")] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported. #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = Option<u64>, example = 1000)] #[mandatory_in(PayoutsCreateRequest = u64)] #[remove_in(PayoutsConfirmRequest)] #[serde(default, deserialize_with = "payments::amount::deserialize_option")] pub amount: Option<payments::Amount>, /// The currency of the payout request can be specified here #[schema(value_type = Option<Currency>, example = "USD")] #[mandatory_in(PayoutsCreateRequest = Currency)] #[remove_in(PayoutsConfirmRequest)] pub currency: Option<api_enums::Currency>, /// Specifies routing algorithm for selecting a connector #[schema(value_type = Option<StaticRoutingAlgorithm>, example = json!({ "type": "single", "data": "adyen" }))] pub routing: Option<serde_json::Value>, /// This field allows the merchant to manually select a connector with which the payout can go through. #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// This field is used when merchant wants to confirm the payout, thus useful for the payout _Confirm_ request. Ideally merchants should _Create_ a payout, _Update_ it (if required), then _Confirm_ it. #[schema(value_type = Option<bool>, example = true, default = false)] #[remove_in(PayoutConfirmRequest)] pub confirm: Option<bool>, /// The payout_type of the payout request can be specified here, this is a mandatory field to _Confirm_ the payout, i.e., should be passed in _Create_ request, if not then should be updated in the payout _Update_ request, then only it can be confirmed. #[schema(value_type = Option<PayoutType>, example = "card")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method information required for carrying out a payout #[schema(value_type = Option<PayoutMethodData>)] pub payout_method_data: Option<PayoutMethodData>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = Option<bool>, example = true, default = false)] pub auto_fulfill: Option<bool>, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. _Deprecated: Use customer_id instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetails>)] pub customer: Option<payments::CustomerDetails>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PayoutsCreateRequest)] #[mandatory_in(PayoutConfirmRequest = String)] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "US", value_type = Option<CountryAlpha2>)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to, select from the given list of options #[schema(value_type = Option<PayoutEntityType>, example = "Individual")] pub entity_type: Option<api_enums::PayoutEntityType>, /// Specifies whether or not the payout request is recurring #[schema(value_type = Option<bool>, default = false)] pub recurring: Option<bool>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Provide a reference to a stored payout method, used to process the payout. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432", value_type = Option<String>)] pub payout_token: Option<String>, /// The business profile to use for this payout, especially if there are multiple business profiles associated with the account, otherwise default business profile associated with the merchant account will be used. #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The send method which will be required for processing payouts, check options for better understanding. #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// Whether to get the payout link (if applicable). Merchant need to specify this during the Payout _Create_, this field can not be updated during Payout _Update_. #[schema(default = false, example = true, value_type = Option<bool>)] pub payout_link: Option<bool>, /// Custom payout link config for the particular payout, if payout link is to be generated. #[schema(value_type = Option<PayoutCreatePayoutLinkConfig>)] pub payout_link_config: Option<PayoutCreatePayoutLinkConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: Option<Secret<String>>, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// Identifier for payout method pub payout_method_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<BrowserInformation>, } impl PayoutCreateRequest { pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } } /// Custom payout link config for the particular payout, if payout link is to be generated. #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] pub struct PayoutCreatePayoutLinkConfig { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub payout_link_id: Option<String>, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// List of payout methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, /// Form layout of the payout link #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] pub form_layout: Option<api_enums::UIWidgetFormLayout>, /// `test_mode` allows for opening payout links without any restrictions. This removes /// - domain name validations /// - check for making sure link is accessed within an iframe #[schema(value_type = Option<bool>, example = false)] pub test_mode: Option<bool>, } /// The payout method information required for carrying out a payout #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodData { Card(CardPayout), Bank(Bank), Wallet(Wallet), BankRedirect(BankRedirect), } impl Default for PayoutMethodData { fn default() -> Self { Self::Card(CardPayout::default()) } } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct CardPayout { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String)] pub expiry_month: Secret<String>, /// The card's expiry year #[schema(value_type = String)] pub expiry_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(untagged)] pub enum Bank { Ach(AchBankTransfer), Bacs(BacsBankTransfer), Sepa(SepaBankTransfer), Pix(PixBankTransfer), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct AchBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [9 digits] Routing number - used in USA for identifying a specific bank. #[schema(value_type = String, example = "110000000")] pub bank_routing_number: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct BacsBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [6 digits] Sort Code - used in UK and Ireland for identifying a bank and it's branches. #[schema(value_type = String, example = "98-76-54")] pub bank_sort_code: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] // The SEPA (Single Euro Payments Area) is a pan-European network that allows you to send and receive payments in euros between two cross-border bank accounts in the eurozone. pub struct SepaBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// International Bank Account Number (iban) - used in many countries for identifying a bank along with it's customer. #[schema(value_type = String, example = "DE89370400440532013000")] pub iban: Secret<String>, /// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches #[schema(value_type = String, example = "HSBCGB2LXXX")] pub bic: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct PixBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank branch #[schema(value_type = Option<String>, example = "3707")] pub bank_branch: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// Unique key for pix customer #[schema(value_type = String, example = "000123456")] pub pix_key: Secret<String>, /// Individual taxpayer identification number #[schema(value_type = Option<String>, example = "000123456")] pub tax_id: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum Wallet { ApplePayDecrypt(ApplePayDecrypt), Paypal(Paypal), Venmo(Venmo), } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirect { Interac(Interac), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Interac { /// Customer email linked with interac account #[schema(value_type = String, example = "john.doe@example.com")] pub email: Email, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Paypal { /// Email linked with paypal account #[schema(value_type = String, example = "john.doe@example.com")] pub email: Option<Email>, /// mobile number linked to paypal account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, /// id of the paypal account #[schema(value_type = String, example = "G83KXTJ5EHCQ2")] pub paypal_id: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Venmo { /// mobile number linked to venmo account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct ApplePayDecrypt { /// The dpan number associated with card number #[schema(value_type = String, example = "4242424242424242")] pub dpan: CardNumber, /// The card's expiry month #[schema(value_type = String)] pub expiry_month: Secret<String>, /// The card's expiry year #[schema(value_type = String)] pub expiry_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } #[derive(Debug, ToSchema, Clone, Serialize, router_derive::PolymorphicSchema)] #[serde(deny_unknown_fields)] pub struct PayoutCreateResponse { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, value_type = String, example = "merchant_1668273825")] pub merchant_id: id_type::MerchantId, /// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported. #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 1000)] pub amount: common_utils::types::MinorUnit, /// Recipient's currency for the payout request #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// The connector used for the payout #[schema(example = "wise")] pub connector: Option<String>, /// The payout method that is to be used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method details for the payout #[schema(value_type = Option<PayoutMethodDataResponse>, example = json!(r#"{ "card": { "last4": "2503", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": null, "payment_checks": null, "authentication_data": null } }"#))] pub payout_method_data: Option<PayoutMethodDataResponse>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = bool, example = true, default = false)] pub auto_fulfill: bool, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetailsResponse>)] pub customer: Option<payments::CustomerDetailsResponse>, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout #[schema(example = "US", value_type = CountryAlpha2)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout #[schema(example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: api_enums::PayoutEntityType, /// Specifies whether or not the payout request is recurring #[schema(value_type = bool, default = false)] pub recurring: bool, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Unique identifier of the merchant connector account #[schema(value_type = Option<String>, example = "mca_sAD3OZLATetvjLOYhUSy")] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Current status of the Payout #[schema(value_type = PayoutStatus, example = RequiresConfirmation)] pub status: api_enums::PayoutStatus, /// If there was an error while calling the connector the error message is received here #[schema(value_type = Option<String>, example = "Failed while verifying the card")] pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(value_type = Option<String>, example = "E0001")] pub error_code: Option<String>, /// The business profile that is associated with this payout #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Time when the payout was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Underlying processor's payout resource ID #[schema(value_type = Option<String>, example = "S3FC9G9M2MVFDXT5")] pub connector_transaction_id: Option<String>, /// Payout's send priority (if applicable) #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// List of attempts #[schema(value_type = Option<Vec<PayoutAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PayoutAttemptResponse>>, /// If payout link was requested, this contains the link's ID and the URL to render the payout widget #[schema(value_type = Option<PayoutLinkResponse>)] pub payout_link: Option<PayoutLinkResponse>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: crypto::OptionalEncryptableName, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, /// Identifier for payout method pub payout_method_id: Option<String>, } /// The payout method information for response #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodDataResponse { #[schema(value_type = CardAdditionalData)] Card(Box<payout_method_utils::CardAdditionalData>), #[schema(value_type = BankAdditionalData)] Bank(Box<payout_method_utils::BankAdditionalData>), #[schema(value_type = WalletAdditionalData)] Wallet(Box<payout_method_utils::WalletAdditionalData>), #[schema(value_type = BankRedirectAdditionalData)] BankRedirect(Box<payout_method_utils::BankRedirectAdditionalData>), } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct PayoutAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = PayoutStatus, example = "failed")] pub status: api_enums::PayoutStatus, /// The payout attempt amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6583)] pub amount: common_utils::types::MinorUnit, /// The currency of the amount of the payout attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<api_enums::Currency>, /// The connector used for the payout pub connector: Option<String>, /// Connector's error code in case of failures pub error_code: Option<String>, /// Connector's error message in case of failures pub error_message: Option<String>, /// The payout method that was used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payment_method: Option<api_enums::PayoutType>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "bacs")] pub payout_method_type: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payout provided by the connector pub connector_transaction_id: Option<String>, /// If the payout was cancelled the reason provided here pub cancellation_reason: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, } #[derive(Default, Debug, Clone, Deserialize, ToSchema)] pub struct PayoutRetrieveBody { pub force_sync: Option<bool>, #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive(Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutRetrieveRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, /// `force_sync` with the connector to get payout details /// (defaults to false) #[schema(value_type = Option<bool>, default = false, example = true)] pub force_sync: Option<bool>, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive(Debug, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PayoutCancelRequest, PayoutFulfillRequest)] pub struct PayoutActionRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, } #[derive(Default, Debug, ToSchema, Clone, Deserialize)] pub struct PayoutVendorAccountDetails { pub vendor_details: PayoutVendorDetails, pub individual_details: PayoutIndividualDetails, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutVendorDetails { pub account_type: String, pub business_type: String, pub business_profile_mcc: Option<i32>, pub business_profile_url: Option<String>, pub business_profile_name: Option<Secret<String>>, pub company_address_line1: Option<Secret<String>>, pub company_address_line2: Option<Secret<String>>, pub company_address_postal_code: Option<Secret<String>>, pub company_address_city: Option<Secret<String>>, pub company_address_state: Option<Secret<String>>, pub company_phone: Option<Secret<String>>, pub company_tax_id: Option<Secret<String>>, pub company_owners_provided: Option<bool>, pub capabilities_card_payments: Option<bool>, pub capabilities_transfers: Option<bool>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutIndividualDetails { pub tos_acceptance_date: Option<i64>, pub tos_acceptance_ip: Option<Secret<String>>, pub individual_dob_day: Option<Secret<String>>, pub individual_dob_month: Option<Secret<String>>, pub individual_dob_year: Option<Secret<String>>, pub individual_id_number: Option<Secret<String>>, pub individual_ssn_last_4: Option<Secret<String>>, pub external_account_account_holder_type: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListConstraints { /// The identifier for customer #[schema(value_type = Option<String>, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "payout_fafa124123", value_type = Option<String>,)] pub starting_after: Option<id_type::PayoutId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "payout_fafa124123", value_type = Option<String>,)] pub ending_before: Option<id_type::PayoutId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The time at which payout is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListFilterConstraints { /// The identifier for payout #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: Option<id_type::PayoutId>, /// The merchant order reference ID for payout #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[schema(value_type = Option<String>,example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payouts list #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// The list of currencies to filter payouts list #[schema(value_type = Currency, example = "USD")] pub currency: Option<Vec<api_enums::Currency>>, /// The list of payout status to filter payouts list #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["pending", "failed"]))] pub status: Option<Vec<api_enums::PayoutStatus>>, /// The list of payout methods to filter payouts list #[schema(value_type = Option<Vec<PayoutType>>, example = json!(["bank", "card"]))] pub payout_method: Option<Vec<common_enums::PayoutType>>, /// Type of recipient #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: Option<common_enums::PayoutEntityType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListResponse { /// The number of payouts included in the list pub size: usize, /// The list of payouts response objects pub data: Vec<PayoutCreateResponse>, /// The total number of available payouts for given constraints #[serde(skip_serializing_if = "Option::is_none")] pub total_count: Option<i64>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListFilters { /// The list of available connector filters #[schema(value_type = Vec<PayoutConnectors>)] pub connector: Vec<api_enums::PayoutConnectors>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<common_enums::Currency>, /// The list of available payout status filters #[schema(value_type = Vec<PayoutStatus>)] pub status: Vec<common_enums::PayoutStatus>, /// The list of available payout method filters #[schema(value_type = Vec<PayoutType>)] pub payout_method: Vec<common_enums::PayoutType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutLinkResponse { pub payout_link_id: String, #[schema(value_type = String)] pub link: Secret<url::Url>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PayoutLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payout_id: id_type::PayoutId, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkDetails { pub publishable_key: Secret<String>, pub client_secret: Secret<String>, pub payout_link_id: String, pub payout_id: id_type::PayoutId, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>, pub enabled_payment_methods_with_required_fields: Vec<PayoutEnabledPaymentMethodsInfo>, pub amount: common_utils::types::StringMajorUnit, pub currency: common_enums::Currency, pub locale: String, pub form_layout: Option<common_enums::UIWidgetFormLayout>, pub test_mode: bool, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutEnabledPaymentMethodsInfo { pub payment_method: common_enums::PaymentMethod, pub payment_method_types_info: Vec<PaymentMethodTypeInfo>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodTypeInfo { pub payment_method_type: common_enums::PaymentMethodType, pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, } #[derive(Clone, Debug, serde::Serialize, FlatStruct)] pub struct RequiredFieldsOverrideRequest { pub billing: Option<payments::Address>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkStatusDetails { pub payout_link_id: String, pub payout_id: id_type::PayoutId, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: api_enums::PayoutStatus, pub error_code: Option<UnifiedCode>, pub error_message: Option<UnifiedMessage>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub test_mode: bool, } impl From<Bank> for payout_method_utils::BankAdditionalData { fn from(bank_data: Bank) -> Self { match bank_data { Bank::Ach(AchBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_routing_number, }) => Self::Ach(Box::new( payout_method_utils::AchBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_routing_number: bank_routing_number.into(), }, )), Bank::Bacs(BacsBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_sort_code, }) => Self::Bacs(Box::new( payout_method_utils::BacsBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_sort_code: bank_sort_code.into(), }, )), Bank::Sepa(SepaBankTransfer { bank_name, bank_country_code, bank_city, iban, bic, }) => Self::Sepa(Box::new( payout_method_utils::SepaBankTransferAdditionalData { bank_name, bank_country_code, bank_city, iban: iban.into(), bic: bic.map(From::from), }, )), Bank::Pix(PixBankTransfer { bank_name, bank_branch, bank_account_number, pix_key, tax_id, }) => Self::Pix(Box::new( payout_method_utils::PixBankTransferAdditionalData { bank_name, bank_branch, bank_account_number: bank_account_number.into(), pix_key: pix_key.into(), tax_id: tax_id.map(From::from), }, )), } } } impl From<Wallet> for payout_method_utils::WalletAdditionalData { fn from(wallet_data: Wallet) -> Self { match wallet_data { Wallet::Paypal(Paypal { email, telephone_number, paypal_id, }) => Self::Paypal(Box::new(payout_method_utils::PaypalAdditionalData { email: email.map(ForeignFrom::foreign_from), telephone_number: telephone_number.map(From::from), paypal_id: paypal_id.map(From::from), })), Wallet::Venmo(Venmo { telephone_number }) => { Self::Venmo(Box::new(payout_method_utils::VenmoAdditionalData { telephone_number: telephone_number.map(From::from), })) } Wallet::ApplePayDecrypt(ApplePayDecrypt { expiry_month, expiry_year, card_holder_name, .. }) => Self::ApplePayDecrypt(Box::new( payout_method_utils::ApplePayDecryptAdditionalData { card_exp_month: expiry_month, card_exp_year: expiry_year, card_holder_name, }, )), } } } impl From<BankRedirect> for payout_method_utils::BankRedirectAdditionalData { fn from(bank_redirect: BankRedirect) -> Self { match bank_redirect { BankRedirect::Interac(Interac { email }) => { Self::Interac(Box::new(payout_method_utils::InteracAdditionalData { email: Some(ForeignFrom::foreign_from(email)), })) } } } } impl From<payout_method_utils::AdditionalPayoutMethodData> for PayoutMethodDataResponse { fn from(additional_data: payout_method_utils::AdditionalPayoutMethodData) -> Self { match additional_data { payout_method_utils::AdditionalPayoutMethodData::Card(card_data) => { Self::Card(card_data) } payout_method_utils::AdditionalPayoutMethodData::Bank(bank_data) => { Self::Bank(bank_data) } payout_method_utils::AdditionalPayoutMethodData::Wallet(wallet_data) => { Self::Wallet(wallet_data) } payout_method_utils::AdditionalPayoutMethodData::BankRedirect(bank_redirect) => { Self::BankRedirect(bank_redirect) } } } }
crates/api_models/src/payouts.rs
api_models::src::payouts
11,001
true
// File: crates/api_models/src/cards_info.rs // Module: api_models::src::cards_info use std::fmt::Debug; use common_utils::events::ApiEventMetric; use utoipa::ToSchema; use crate::enums; #[derive(serde::Deserialize, ToSchema)] pub struct CardsInfoRequestParams { #[schema(example = "pay_OSERgeV9qAy7tlK7aKpc_secret_TuDUoh11Msxh12sXn3Yp")] pub client_secret: Option<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CardsInfoRequest { pub client_secret: Option<String>, pub card_iin: String, } #[derive(serde::Serialize, Debug, ToSchema)] pub struct CardInfoResponse { #[schema(example = "374431")] pub card_iin: String, #[schema(example = "AMEX")] pub card_issuer: Option<String>, #[schema(example = "AMEX")] pub card_network: Option<String>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "CLASSIC")] pub card_sub_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, } #[derive(serde::Serialize, Debug, ToSchema)] pub struct CardInfoMigrateResponseRecord { pub card_iin: Option<String>, pub card_issuer: Option<String>, pub card_network: Option<String>, pub card_type: Option<String>, pub card_sub_type: Option<String>, pub card_issuing_country: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardInfoCreateRequest { pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub last_updated_provider: Option<String>, } impl ApiEventMetric for CardInfoCreateRequest {} #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardInfoUpdateRequest { pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub last_updated_provider: Option<String>, pub line_number: Option<i64>, } impl ApiEventMetric for CardInfoUpdateRequest {} #[derive(Debug, Default, serde::Serialize)] pub enum CardInfoMigrationStatus { Success, #[default] Failed, } #[derive(Debug, Default, serde::Serialize)] pub struct CardInfoMigrationResponse { pub line_number: Option<i64>, pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<String>, pub card_type: Option<String>, pub card_sub_type: Option<String>, pub card_issuing_country: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub migration_error: Option<String>, pub migration_status: CardInfoMigrationStatus, } impl ApiEventMetric for CardInfoMigrationResponse {} type CardInfoMigrationResponseType = ( Result<CardInfoMigrateResponseRecord, String>, CardInfoUpdateRequest, ); impl From<CardInfoMigrationResponseType> for CardInfoMigrationResponse { fn from((response, record): CardInfoMigrationResponseType) -> Self { match response { Ok(res) => Self { card_iin: record.card_iin, line_number: record.line_number, card_issuer: res.card_issuer, card_network: res.card_network, card_type: res.card_type, card_sub_type: res.card_sub_type, card_issuing_country: res.card_issuing_country, migration_status: CardInfoMigrationStatus::Success, migration_error: None, }, Err(e) => Self { card_iin: record.card_iin, migration_status: CardInfoMigrationStatus::Failed, migration_error: Some(e), line_number: record.line_number, ..Self::default() }, } } }
crates/api_models/src/cards_info.rs
api_models::src::cards_info
977
true
// File: crates/api_models/src/revenue_recovery_data_backfill.rs // Module: api_models::src::revenue_recovery_data_backfill use std::{collections::HashMap, fs::File, io::BufReader}; use actix_multipart::form::{tempfile::TempFile, MultipartForm}; use actix_web::{HttpResponse, ResponseError}; use common_enums::{CardNetwork, PaymentMethodType}; use common_utils::{events::ApiEventMetric, pii::PhoneNumberStrategy}; use csv::Reader; use masking::Secret; use serde::{Deserialize, Serialize}; use time::{Date, PrimitiveDateTime}; #[derive(Debug, Deserialize, Serialize)] pub struct RevenueRecoveryBackfillRequest { pub bin_number: Option<Secret<String>>, pub customer_id_resp: String, pub connector_payment_id: Option<String>, pub token: Option<Secret<String>>, pub exp_date: Option<Secret<String>>, pub card_network: Option<CardNetwork>, pub payment_method_sub_type: Option<PaymentMethodType>, pub clean_bank_name: Option<String>, pub country_name: Option<String>, pub daily_retry_history: Option<String>, } #[derive(Debug, Serialize)] pub struct UnlockStatusResponse { pub unlocked: bool, } #[derive(Debug, Serialize)] pub struct RevenueRecoveryDataBackfillResponse { pub processed_records: usize, pub failed_records: usize, } #[derive(Debug, Serialize)] pub struct CsvParsingResult { pub records: Vec<RevenueRecoveryBackfillRequest>, pub failed_records: Vec<CsvParsingError>, } #[derive(Debug, Serialize)] pub struct CsvParsingError { pub row_number: usize, pub error: String, } /// Comprehensive card #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ComprehensiveCardData { pub card_type: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_network: Option<CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub daily_retry_history: Option<HashMap<Date, i32>>, } impl ApiEventMetric for RevenueRecoveryDataBackfillResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for UnlockStatusResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for CsvParsingResult { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for CsvParsingError { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for RedisDataResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for UpdateTokenStatusRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } impl ApiEventMetric for UpdateTokenStatusResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[derive(Debug, Clone, Serialize)] pub enum BackfillError { InvalidCardType(String), DatabaseError(String), RedisError(String), CsvParsingError(String), FileProcessingError(String), } #[derive(serde::Deserialize)] pub struct BackfillQuery { pub cutoff_time: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub enum RedisKeyType { Status, // for customer:{id}:status Tokens, // for customer:{id}:tokens } #[derive(Debug, Deserialize)] pub struct GetRedisDataQuery { pub key_type: RedisKeyType, } #[derive(Debug, Serialize)] pub struct RedisDataResponse { pub exists: bool, pub ttl_seconds: i64, pub data: Option<serde_json::Value>, } #[derive(Debug, Serialize)] pub enum ScheduledAtUpdate { SetToNull, SetToDateTime(PrimitiveDateTime), } impl<'de> Deserialize<'de> for ScheduledAtUpdate { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let value = serde_json::Value::deserialize(deserializer)?; match value { serde_json::Value::String(s) => { if s.to_lowercase() == "null" { Ok(Self::SetToNull) } else { // Parse as datetime using iso8601 deserializer common_utils::custom_serde::iso8601::deserialize( &mut serde_json::Deserializer::from_str(&format!("\"{}\"", s)), ) .map(Self::SetToDateTime) .map_err(serde::de::Error::custom) } } _ => Err(serde::de::Error::custom( "Expected null variable or datetime iso8601 ", )), } } } #[derive(Debug, Deserialize, Serialize)] pub struct UpdateTokenStatusRequest { pub connector_customer_id: String, pub payment_processor_token: Secret<String, PhoneNumberStrategy>, pub scheduled_at: Option<ScheduledAtUpdate>, pub is_hard_decline: Option<bool>, pub error_code: Option<String>, } #[derive(Debug, Serialize)] pub struct UpdateTokenStatusResponse { pub updated: bool, pub message: String, } impl std::fmt::Display for BackfillError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::InvalidCardType(msg) => write!(f, "Invalid card type: {}", msg), Self::DatabaseError(msg) => write!(f, "Database error: {}", msg), Self::RedisError(msg) => write!(f, "Redis error: {}", msg), Self::CsvParsingError(msg) => write!(f, "CSV parsing error: {}", msg), Self::FileProcessingError(msg) => write!(f, "File processing error: {}", msg), } } } impl std::error::Error for BackfillError {} impl ResponseError for BackfillError { fn error_response(&self) -> HttpResponse { HttpResponse::BadRequest().json(serde_json::json!({ "error": self.to_string() })) } } #[derive(Debug, MultipartForm)] pub struct RevenueRecoveryDataBackfillForm { #[multipart(rename = "file")] pub file: TempFile, } impl RevenueRecoveryDataBackfillForm { pub fn validate_and_get_records_with_errors(&self) -> Result<CsvParsingResult, BackfillError> { // Step 1: Open the file let file = File::open(self.file.file.path()) .map_err(|error| BackfillError::FileProcessingError(error.to_string()))?; let mut csv_reader = Reader::from_reader(BufReader::new(file)); // Step 2: Parse CSV into typed records let mut records = Vec::new(); let mut failed_records = Vec::new(); for (row_index, record_result) in csv_reader .deserialize::<RevenueRecoveryBackfillRequest>() .enumerate() { match record_result { Ok(record) => { records.push(record); } Err(err) => { failed_records.push(CsvParsingError { row_number: row_index + 2, // +2 because enumerate starts at 0 and CSV has header row error: err.to_string(), }); } } } Ok(CsvParsingResult { records, failed_records, }) } }
crates/api_models/src/revenue_recovery_data_backfill.rs
api_models::src::revenue_recovery_data_backfill
1,750
true
// File: crates/api_models/src/surcharge_decision_configs.rs // Module: api_models::src::surcharge_decision_configs use common_utils::{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH, events, types::{MinorUnit, Percentage}, }; use euclid::frontend::{ ast::Program, dir::{DirKeyKind, EuclidDirFilter}, }; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct SurchargeDetailsOutput { pub surcharge: SurchargeOutput, pub tax_on_surcharge: Option<Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum SurchargeOutput { Fixed { amount: MinorUnit }, Rate(Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>), } #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct SurchargeDecisionConfigs { pub surcharge_details: Option<SurchargeDetailsOutput>, } impl EuclidDirFilter for SurchargeDecisionConfigs { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::PaymentMethod, DirKeyKind::MetaData, DirKeyKind::PaymentAmount, DirKeyKind::PaymentCurrency, DirKeyKind::BillingCountry, DirKeyKind::CardNetwork, DirKeyKind::PayLaterType, DirKeyKind::WalletType, DirKeyKind::BankTransferType, DirKeyKind::BankRedirectType, DirKeyKind::BankDebitType, DirKeyKind::CryptoType, DirKeyKind::RealTimePaymentType, ]; } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SurchargeDecisionManagerRecord { pub name: String, pub merchant_surcharge_configs: MerchantSurchargeConfigs, pub algorithm: Program<SurchargeDecisionConfigs>, pub created_at: i64, pub modified_at: i64, } impl events::ApiEventMetric for SurchargeDecisionManagerRecord { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct SurchargeDecisionConfigReq { pub name: Option<String>, pub merchant_surcharge_configs: MerchantSurchargeConfigs, pub algorithm: Option<Program<SurchargeDecisionConfigs>>, } impl events::ApiEventMetric for SurchargeDecisionConfigReq { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct MerchantSurchargeConfigs { pub show_surcharge_breakup_screen: Option<bool>, } pub type SurchargeDecisionManagerResponse = SurchargeDecisionManagerRecord;
crates/api_models/src/surcharge_decision_configs.rs
api_models::src::surcharge_decision_configs
649
true
// File: crates/api_models/src/payments.rs // Module: api_models::src::payments #[cfg(feature = "v1")] use std::fmt; use std::{ collections::{HashMap, HashSet}, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::{GooglePayCardFundingSource, ProductType}; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_types::{payments as common_payments_types, primitive_wrappers}; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, new_type::MaskedBankAccount, pii::{self, Email}, types::{AmountConvertor, MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; #[cfg(feature = "v2")] fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error> where D: serde::Deserializer<'de>, T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error, { let opt_str: Option<String> = Option::deserialize(v)?; match opt_str { Some(s) if s.is_empty() => Ok(None), Some(s) => { // Estimate capacity based on comma count let capacity = s.matches(',').count() + 1; let mut result = Vec::with_capacity(capacity); for item in s.split(',') { let trimmed_item = item.trim(); if !trimmed_item.is_empty() { let parsed_item = trimmed_item.parse::<T>().map_err(|e| { <D::Error as serde::de::Error>::custom(format!( "Invalid value '{trimmed_item}': {e}" )) })?; result.push(parsed_item); } } Ok(Some(result)) } None => Ok(None), } } use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; #[cfg(feature = "v1")] use serde::{de, Deserializer}; use serde::{ser::Serializer, Deserialize, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v2")] use crate::mandates; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, enums as api_enums, mandates::RecurringDetails, }; #[cfg(feature = "v1")] use crate::{disputes, ephemeral_key::EphemeralKeyCreateResponse, refunds, ValidateFieldAndGet}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, /// The tax registration identifier of the customer. #[schema(value_type=Option<String>,max_length = 255)] pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentAttemptListRequest { #[schema(value_type = String)] pub payment_intent_id: id_type::GlobalPaymentId, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentAttemptListResponse { pub payment_attempt_list: Vec<PaymentAttemptResponse>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, enable_partial_authorization: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "cs_0195b34da95d75239c6a4bf514458896")] pub client_secret: Option<Secret<String>>, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, /// Enable split payments, i.e., split the amount between multiple payment methods #[schema(value_type = SplitTxnsEnabled, default = "skip")] pub split_txns_enabled: common_enums::SplitTxnsEnabled, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = PaymentType)] pub payment_type: api_enums::PaymentType, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardBalanceCheckResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The balance of the gift card pub balance: MinorUnit, /// The currency of the Gift Card #[schema(value_type = Currency)] pub currency: common_enums::Currency, /// Whether the gift card balance is enough for the transaction (Used for split payments case) pub needs_additional_pm_data: bool, /// Transaction amount left after subtracting gift card balance (Used for split payments) pub remaining_amount: MinorUnit, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, router_derive::ValidateSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The primary amount for the payment, provided in the lowest denomination of the specified currency (e.g., 6540 for $65.40 USD). This field is mandatory for creating a payment. #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order, in the lowest denomination of the currency. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three-letter ISO 4217 currency code (e.g., "USD", "EUR") for the payment amount. This field is mandatory for creating a payment. #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The amount to be captured from the user's payment method, in the lowest denomination. If not provided, and `capture_method` is `automatic`, the full payment `amount` will be captured. If `capture_method` is `manual`, this can be specified in the `/capture` call. Must be less than or equal to the authorized amount. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Optional. A merchant-provided unique identifier for the payment, contains 30 characters long (e.g., "pay_mbabizu24mvu3mela5njyhpit4"). If provided, it ensures idempotency for the payment creation request. If omitted, Hyperswitch generates a unique ID for the payment. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// If set to `true`, Hyperswitch attempts to confirm and authorize the payment immediately after creation, provided sufficient payment method details are included. If `false` or omitted (default is `false`), the payment is created with a status such as `requires_payment_method` or `requires_confirmation`, and a separate `POST /payments/{payment_id}/confirm` call is necessary to proceed with authorization. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// An arbitrary string attached to the payment. Often useful for displaying to users or for your own internal record-keeping. #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to redirect the customer to after they complete the payment process or authentication. This is crucial for flows that involve off-site redirection (e.g., 3DS, some bank redirects, wallet payments). #[schema(value_type = Option<String>, example = "https://hyperswitch.io", max_length = 2048)] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 64, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Your unique identifier for this payment or order. This ID helps you reconcile payments on your system. If provided, it is passed to the connector if supported. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, /// If enabled, provides whole connector response pub all_keys_required: Option<bool>, /// Indicates whether the `payment_id` was provided by the merchant /// This value is inferred internally based on the request #[serde(skip_deserializing)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub is_payment_id_from_merchant: bool, /// Indicates how the payment was initiated (e.g., ecommerce, mail, or telephone). #[schema(value_type = Option<PaymentChannel>)] pub payment_channel: Option<common_enums::PaymentChannel>, /// Your tax status for this order or transaction. #[schema(value_type = Option<TaxStatus>)] pub tax_status: Option<api_enums::TaxStatus>, /// Total amount of the discount you have applied to the order or transaction. #[schema(value_type = Option<i64>, example = 6540)] pub discount_amount: Option<MinorUnit>, /// Tax amount applied to shipping charges. pub shipping_amount_tax: Option<MinorUnit>, /// Duty or customs fee amount for international transactions. pub duty_amount: Option<MinorUnit>, /// Date the payer placed the order. #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub order_date: Option<PrimitiveDateTime>, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, /// Boolean indicating whether to enable overcapture for this payment #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<bool>, example = true)] pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>, /// Boolean flag indicating whether this payment method is stored and has been previously used for payments #[schema(value_type = Option<bool>, example = true)] pub is_stored_credential: Option<bool>, /// The category of the MIT transaction #[schema(value_type = Option<MitCategory>, example = "recurring")] pub mit_category: Option<api_enums::MitCategory>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encrypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, .. }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } pub fn validate_stored_credential( &self, ) -> common_utils::errors::CustomResult<(), ValidationError> { if self.is_stored_credential == Some(false) && (self.recurring_details.is_some() || self.payment_token.is_some() || self.mandate_id.is_some()) { Err(ValidationError::InvalidValue { message: "is_stored_credential should be true when reusing stored payment method data" .to_string(), } .into()) } else { Ok(()) } } pub fn validate_mit_request(&self) -> common_utils::errors::CustomResult<(), ValidationError> { if self.mit_category.is_some() && (!matches!(self.off_session, Some(true)) || self.recurring_details.is_none()) { return Err(ValidationError::InvalidValue { message: "`mit_category` requires both: (1) `off_session = true`, and (2) `recurring_details`.".to_string(), } .into()); } Ok(()) } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, tax_registration_id: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, tax_registration_id: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, /// Accept-language of the browser pub accept_language: Option<String>, /// Identifier of the source that initiated the request. pub referer: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// A unique identifier for this specific payment attempt. pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The name of the payment connector (e.g., 'stripe', 'adyen') used for this attempt. pub connector: Option<String>, /// A human-readable message from the connector explaining the error, if one occurred during this payment attempt. pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If this payment attempt is associated with a mandate (e.g., for a recurring or subsequent payment), this field will contain the ID of that mandate. pub mandate_id: Option<String>, /// The error code returned by the connector if this payment attempt failed. This code is specific to the connector. pub error_code: Option<String>, /// If a tokenized (saved) payment method was used for this attempt, this field contains the payment token representing that payment method. pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// The connector's own reference or transaction ID for this specific payment attempt. Useful for reconciliation with the connector. #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The payment method information for the payment attempt pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentAttemptRecordResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The amount of the payment attempt #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Error details for the payment attempt, if any. /// This includes fields like error code, network advice code, and network decline code. pub error_details: Option<RecordAttemptErrorDetails>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub payment_intent_feature_metadata: Option<FeatureMetadata>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub payment_attempt_feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// attempt created at timestamp pub created_at: PrimitiveDateTime, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct RecoveryPaymentsResponse { /// Unique identifier for the payment. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub intent_status: api_enums::IntentStatus, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, // stripe specific field used to identify duplicate attempts. #[schema(value_type = Option<String>, example = "ch_123abc456def789ghi012klmn")] pub charge_id: Option<String>, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// A unique identifier for this specific capture operation. pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The name of the payment connector that processed this capture. pub connector: String, /// The ID of the payment attempt that was successfully authorized and subsequently captured by this operation. pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// A human-readable message from the connector explaining why this capture operation failed, if applicable. pub error_message: Option<String>, /// The error code returned by the connector if this capture operation failed. This code is connector-specific. pub error_code: Option<String>, /// A more detailed reason from the connector explaining the capture failure, if available. pub error_reason: Option<String>, /// The connector's own reference or transaction ID for this specific capture operation. Useful for reconciliation. pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq, ToSchema)] pub struct NetworkDetails { pub network_advice_code: Option<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For Flexiti Redirect as PayLater long term finance Option FlexitiRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, BreadpayRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::FlexitiRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} | Self::BreadpayRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, SepaGuarenteedBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaGuarenteedBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SplitPaymentMethodDataRequest { pub payment_method_data: PaymentMethodData, #[schema(value_type = PaymentMethod)] pub payment_method_type: api_enums::PaymentMethod, #[schema(value_type = PaymentMethodType)] pub payment_method_subtype: api_enums::PaymentMethodType, } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct RecordAttemptPaymentMethodDataRequest { /// Additional details for the payment method (e.g., card expiry date, card network). #[serde(flatten)] pub payment_method_data: AdditionalPaymentData, /// billing details for the payment method. pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct ProxyPaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<ProxyPaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum ProxyPaymentMethodData { #[schema(title = "ProxyCardData")] VaultDataCard(Box<ProxyCardData>), VaultToken(VaultToken), } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ProxyCardData { /// The token which refers to the card number #[schema(value_type = String, example = "token_card_number")] pub card_number: Secret<String>, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, /// The first six digit of the card number #[schema(value_type = String, example = "424242")] pub bin_number: Option<String>, /// The last four digit of the card number #[schema(value_type = String, example = "4242")] pub last_four: Option<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct VaultToken { /// The tokenized CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BluecodeRedirect {} => api_enums::PaymentMethodType::Bluecode, Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPay(_) | Self::AmazonPayRedirect(_) => { api_enums::PaymentMethodType::AmazonPay } Self::Skrill(_) => api_enums::PaymentMethodType::Skrill, Self::Paysera(_) => api_enums::PaymentMethodType::Paysera, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, Self::RevolutPay(_) => api_enums::PaymentMethodType::RevolutPay, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::FlexitiRedirect {} => api_enums::PaymentMethodType::Flexiti, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, Self::BreadpayRedirect {} => api_enums::PaymentMethodType::Breadpay, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, Self::SepaGuarenteedBankDebit { .. } => { api_enums::PaymentMethodType::SepaGuarenteedDebit } } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, Self::InstantBankTransferFinland {} => { api_enums::PaymentMethodType::InstantBankTransferFinland } Self::InstantBankTransferPoland {} => { api_enums::PaymentMethodType::InstantBankTransferPoland } Self::IndonesianBankTransfer { .. } => { api_enums::PaymentMethodType::IndonesianBankTransfer } } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, Self::UpiQr(_) => api_enums::PaymentMethodType::UpiQr, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, Self::BhnCardNetwork(_) => api_enums::PaymentMethodType::BhnCardNetwork, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, BhnCardNetwork(BHNGiftCardDetails), } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct BHNGiftCardDetails { /// The gift card or account number #[schema(value_type = String)] pub account_number: Secret<String>, /// The security PIN for gift cards requiring it #[schema(value_type = String)] pub pin: Option<Secret<String>>, /// The CVV2 code for Open Loop/VPLN products #[schema(value_type = String)] pub cvv2: Option<Secret<String>>, /// The expiration date in MMYYYY format for Open Loop/VPLN products #[schema(value_type = String)] pub expiration_date: Option<String>, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, /// Indicates if the card issuer is regulated under government-imposed interchange fee caps. /// In the United States, this includes debit cards that fall under the Durbin Amendment, /// which imposes capped interchange fees. pub is_regulated: Option<bool>, /// The global signature network under which the card is issued. /// This represents the primary global card brand, even if the transaction uses a local network pub signature_network: Option<api_enums::CardNetwork>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } impl AdditionalPaymentData { pub fn get_additional_card_info(&self) -> Option<AdditionalCardInfo> { match self { Self::Card(additional_card_info) => Some(*additional_card_info.clone()), _ => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), UpiQr(UpiQrData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiQrData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, /// Source bank account number #[schema(value_type = Option<String>, example = "8b******-****-****-****-*******08bc5")] source_bank_account_id: Option<MaskedBankAccount>, /// Partially masked destination bank account number _Deprecated: Will be removed in next stable release._ #[schema(value_type = Option<String>, example = "********-****-460b-****-f23b4e71c97b", deprecated)] destination_bank_account_id: Option<MaskedBankAccount>, /// The expiration date and time for the Pix QR code in ISO 8601 format #[schema(value_type = Option<String>, example = "2025-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] expiry_date: Option<PrimitiveDateTime>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, InstantBankTransferFinland {}, InstantBankTransferPoland {}, IndonesianBankTransfer { #[schema(value_type = Option<BankNames>, example = "bri")] bank_name: Option<common_enums::BankNames>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} | Self::InstantBankTransferFinland {} | Self::IndonesianBankTransfer { .. } | Self::InstantBankTransferPoland {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay HK redirect #[schema(title = "AliPayHkRedirect")] AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Ali Pay QrCode #[schema(title = "AliPayQr")] AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect #[schema(title = "AliPayRedirect")] AliPayRedirect(AliPayRedirection), /// The wallet data for Amazon Pay #[schema(title = "AmazonPay")] AmazonPay(AmazonPayWalletData), /// The wallet data for Amazon Pay redirect #[schema(title = "AmazonPayRedirect")] AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Apple pay #[schema(title = "ApplePay")] ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow #[schema(title = "ApplePayRedirect")] ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow #[schema(title = "ApplePayThirdPartySdk")] ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// The wallet data for Bluecode QR Code Redirect #[schema(title = "BluecodeRedirect")] BluecodeRedirect {}, /// The wallet data for Cashapp Qr #[schema(title = "CashappQr")] CashappQr(Box<CashappQr>), /// Wallet data for DANA redirect flow #[schema(title = "DanaRedirect")] DanaRedirect {}, /// The wallet data for Gcash redirect #[schema(title = "GcashRedirect")] GcashRedirect(GcashRedirection), /// The wallet data for GoPay redirect #[schema(title = "GoPayRedirect")] GoPayRedirect(GoPayRedirection), /// The wallet data for Google pay #[schema(title = "GooglePay")] GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow #[schema(title = "GooglePayRedirect")] GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow #[schema(title = "GooglePayThirdPartySdk")] GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), /// The wallet data for KakaoPay redirect #[schema(title = "KakaoPayRedirect")] KakaoPayRedirect(KakaoPayRedirection), /// Wallet data for MbWay redirect flow #[schema(title = "MbWayRedirect")] MbWayRedirect(Box<MbWayRedirection>), // The wallet data for Mifinity Ewallet #[schema(title = "Mifinity")] Mifinity(MifinityData), /// The wallet data for MobilePay redirect #[schema(title = "MobilePayRedirect")] MobilePayRedirect(Box<MobilePayRedirection>), /// The wallet data for Momo redirect #[schema(title = "MomoRedirect")] MomoRedirect(MomoRedirection), /// This is for paypal redirection #[schema(title = "PaypalRedirect")] PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal #[schema(title = "PaypalSdk")] PaypalSdk(PayPalWalletData), /// The wallet data for Paysera #[schema(title = "Paysera")] Paysera(PayseraData), /// The wallet data for Paze #[schema(title = "Paze")] Paze(PazeWalletData), // The wallet data for RevolutPay #[schema(title = "RevolutPay")] RevolutPay(RevolutPayData), /// The wallet data for Samsung Pay #[schema(title = "SamsungPay")] SamsungPay(Box<SamsungPayWalletData>), /// The wallet data for Skrill #[schema(title = "Skrill")] Skrill(SkrillData), // The wallet data for Swish #[schema(title = "SwishQr")] SwishQr(SwishQrData), /// The wallet data for Touch n Go Redirection #[schema(title = "TouchNGoRedirect")] TouchNGoRedirect(Box<TouchNGoRedirection>), /// Wallet data for Twint Redirection #[schema(title = "TwintRedirect")] TwintRedirect {}, /// Wallet data for Vipps Redirection #[schema(title = "VippsRedirect")] VippsRedirect {}, /// The wallet data for WeChat Pay Display QrCode #[schema(title = "WeChatPayQr")] WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for WeChat Pay Redirection #[schema(title = "WeChatPayRedirect")] WeChatPayRedirect(Box<WeChatPayRedirection>), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPay(_) | Self::AmazonPayRedirect(_) | Self::Skrill(_) | Self::Paysera(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) | Self::RevolutPay(_) | Self::BluecodeRedirect {} => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay #[schema(value_type = GpayTokenizationData)] pub tokenization_data: common_types::payments::GpayTokenizationData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPaySessionTokenData { #[serde(rename = "amazon_pay")] pub data: AmazonPayMerchantCredentials, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPayMerchantCredentials { /// Amazon Pay merchant account identifier pub merchant_id: String, /// Amazon Pay store ID pub store_id: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SkrillData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayseraData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData { #[schema(value_type = Option<String>)] pub token: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData { #[schema(value_type = Option<String>)] pub token: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BluecodeQrRedirect {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, /// Card funding source for the selected payment method pub card_funding_source: Option<GooglePayCardFundingSource>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct RevolutPayData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayWalletData { /// Checkout Session identifier pub checkout_session_id: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay #[schema(value_type = ApplePayPaymentData)] pub payment_data: common_types::payments::ApplePayPaymentData, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number (CPF or CNPJ) #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, /// The shopper's bank account number associated with the boleto #[schema(value_type = Option<String>)] pub bank_number: Option<Secret<String>>, /// The type of identification document used (e.g., CPF or CNPJ) #[schema(value_type = Option<DocumentKind>, example = "Cpf", default = "Cnpj")] pub document_type: Option<common_enums::DocumentKind>, /// The fine percentage charged if payment is overdue #[schema(value_type = Option<String>)] pub fine_percentage: Option<String>, /// The number of days after the due date when the fine is applied #[schema(value_type = Option<String>)] pub fine_quantity_days: Option<String>, /// The interest percentage charged on late payments #[schema(value_type = Option<String>)] pub interest_percentage: Option<String>, /// The number of days after which the boleto is written off (canceled) #[schema(value_type = Option<String>)] pub write_off_quantity_days: Option<String>, /// Custom messages or instructions to display on the boleto #[schema(value_type = Option<Vec<String>>)] pub messages: Option<Vec<String>>, // #[serde(with = "common_utils::custom_serde::date_yyyy_mm_dd::option")] #[schema(value_type = Option<String>, format = "date", example = "2025-08-22")] // The date upon which the boleto is due and is of format: "YYYY-MM-DD" pub due_date: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct CustomRecoveryPaymentMethodData { /// Primary payment method token at payment processor end. #[schema(value_type = String, example = "token_1234")] pub primary_processor_payment_method_token: Secret<String>, /// AdditionalCardInfo for the primary token. pub additional_payment_method_info: AdditionalCardInfo, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] // #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] // #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The city, district, suburb, town, or village of the address. #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO 3166-1 alpha-2 country code (e.g., US, GB). #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the street address or P.O. Box. #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the street address or P.O. Box (e.g., apartment, suite, unit, or building). #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the street address, if applicable. #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, /// The zip/postal code of the origin #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub origin_zip: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), origin_zip: self.origin_zip.or(other.origin_zip.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment being captured. This is taken from the path parameter. #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant. This is usually inferred from the API key. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The amount to capture, in the lowest denomination of the currency. If omitted, the entire `amount_capturable` of the payment will be captured. Must be less than or equal to the current `amount_capturable`. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount. (Currently not fully supported or behavior may vary by connector). pub refund_uncaptured_amount: Option<bool>, /// A dynamic suffix that appears on your customer's credit card statement. This is concatenated with the (shortened) descriptor prefix set on your account to form the complete statement descriptor. The combined length should not exceed connector-specific limits (typically 22 characters). pub statement_descriptor_suffix: Option<String>, /// An optional prefix for the statement descriptor that appears on your customer's credit card statement. This can override the default prefix set on your merchant account. The combined length of prefix and suffix should not exceed connector-specific limits (typically 22 characters). pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. (Deprecated) #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[cfg(feature = "v2")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The reason for the payment cancel pub cancellation_reason: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCancelResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "cancelled")] pub status: common_enums::IntentStatus, /// Cancellation reason for the payment cancellation #[schema(example = "Requested by merchant")] pub cancellation_reason: Option<String>, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, /// The unique identifier for the customer associated with the payment pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<api_enums::Connector>, #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// Error details for the payment pub error: Option<ErrorDetails>, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, RedirectInsidePopup, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, #[cfg(feature = "v1")] RedirectInsidePopup { popup_url: String, redirect_response_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the SDK UPI intent URI for payment processing SdkUpiIntentInformation { #[schema(value_type = String)] sdk_uri: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, poll_config: Option<PollConfig>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum ThreeDsMethodData { AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, /// Three DS Method Key three_ds_method_key: Option<ThreeDsMethodKey>, /// Indicates whethere to wait for Post message after 3DS method data submission consume_post_message_for_three_ds_method_completion: bool, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum ThreeDsMethodKey { #[serde(rename = "threeDSMethodData")] ThreeDsMethodData, #[serde(rename = "JWT")] JWT, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SdkUpiIntentInformation { pub sdk_uri: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher entry date pub entry_date: Option<String>, /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, /// Human-readable numeric version of the barcode. pub digitable_line: Option<Secret<String>>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, pub poll_config: Option<PollConfig>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PollConfig { /// Interval of the poll pub delay_in_secs: u16, /// Frequency of the poll pub frequency: u16, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The amount (in minor units) that can still be captured for this payment. This is relevant when `capture_method` is `manual`. Once fully captured, or if `capture_method` is `automatic` and payment succeeded, this will be 0. #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The total amount (in minor units) that has been captured for this payment. For `fauxpay` sandbox connector, this might reflect the authorized amount if `status` is `succeeded` even if `capture_method` was `manual`. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The name of the payment connector (e.g., 'stripe', 'adyen') that processed or is processing this payment. #[schema(example = "stripe")] pub connector: Option<String>, /// A secret token unique to this payment intent. It is primarily used by client-side applications (e.g., Hyperswitch SDKs) to authenticate actions like confirming the payment or handling next actions. This secret should be handled carefully and not exposed publicly beyond its intended client-side use. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Timestamp indicating when this payment intent was created, in ISO 8601 format. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Three-letter ISO currency code (e.g., USD, EUR) for the payment amount. #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// An arbitrary string providing a description for the payment, often useful for display or internal record-keeping. #[schema(example = "It's my first payment request")] pub description: Option<String>, /// An array of refund objects associated with this payment. Empty or null if no refunds have been processed. #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// If the payment requires further action from the customer (e.g., 3DS authentication, redirect to a bank page), this object will contain the necessary information for the client to proceed. Null if no further action is needed from the customer at this stage. pub next_action: Option<NextActionData>, /// If the payment intent was cancelled, this field provides a textual reason for the cancellation (e.g., "requested_by_customer", "abandoned"). pub cancellation_reason: Option<String>, /// The connector-specific error code from the last failed payment attempt associated with this payment intent. #[schema(example = "E0001")] pub error_code: Option<String>, /// A human-readable error message from the last failed payment attempt associated with this payment intent. #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Describes the type of payment flow experienced by the customer (e.g., 'redirect_to_url', 'invoke_sdk', 'display_qr_code'). #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// The specific payment method subtype used for this payment (e.g., 'credit_card', 'klarna', 'gpay'). This provides more granularity than the 'payment_method' field. #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// A label identifying the specific merchant connector account (MCA) used for this payment. This often combines the connector name, business country, and a custom label (e.g., "stripe_US_primary"). #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The two-letter ISO country code (e.g., US, GB) of the business unit or profile under which this payment was processed. #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The label identifying the specific business unit or profile under which this payment was processed by the merchant. pub business_label: Option<String>, /// An optional sub-label for further categorization of the business unit or profile used for this payment. pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Indicates how the payment was initiated (e.g., ecommerce, mail, or telephone). #[schema(value_type = Option<PaymentChannel>)] pub payment_channel: Option<common_enums::PaymentChannel>, /// A unique identifier for the payment method used in this payment. If the payment method was saved or tokenized, this ID can be used to reference it for future transactions or recurring payments. pub payment_method_id: Option<String>, /// The network transaction ID is a unique identifier for the transaction as recognized by the payment network (e.g., Visa, Mastercard), this ID can be used to reference it for future transactions or recurring payments. pub network_transaction_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, /// Contains whole connector response #[schema(value_type = Option<String>)] pub whole_connector_response: Option<Secret<String>>, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, /// Bool indicating if overcapture must be requested for this payment #[schema(value_type = Option<bool>)] pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>, /// Boolean indicating whether overcapture is effectively enabled for this payment #[schema(value_type = Option<bool>)] pub is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>, /// Contains card network response details (e.g., Visa/Mastercard advice codes). #[schema(value_type = Option<NetworkDetails>)] pub network_details: Option<NetworkDetails>, /// Boolean flag indicating whether this payment method is stored and has been previously used for payments #[schema(value_type = Option<bool>, example = true)] pub is_stored_credential: Option<bool>, /// The category of the MIT transaction #[schema(value_type = Option<MitCategory>, example = "recurring")] pub mit_category: Option<api_enums::MitCategory>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment instrument data to be used for the payment in case of split payments pub split_payment_method_data: Option<Vec<SplitPaymentMethodDataRequest>>, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, /// If true, returns stringified connector raw response body pub return_raw_connector_response: Option<bool>, /// The webhook endpoint URL to receive payment status notifications #[schema(value_type = Option<String>, example = "https://merchant.example.com/webhooks/payment")] pub webhook_url: Option<common_utils::types::Url>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Gift Card balance check #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsGiftCardBalanceCheckRequest { pub gift_card_data: GiftCardData, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: mandates::ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct ExternalVaultProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: ProxyPaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, /// If true, returns stringified connector raw response body pub return_raw_connector_response: Option<bool>, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, /// Stringified connector raw response body. Only returned if `return_raw_connector_response` is true pub return_raw_connector_response: Option<bool>, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, /// The webhook endpoint URL to receive payment status notifications #[schema(value_type = Option<String>, example = "https://merchant.example.com/webhooks/payment")] pub webhook_url: Option<common_utils::types::Url>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present, description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption, statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled, payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication, force_3ds_challenge: request.force_3ds_challenge, merchant_connector_details: request.merchant_connector_details.clone(), enable_partial_authorization: request.enable_partial_authorization, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), payment_token: None, merchant_connector_details: request.merchant_connector_details.clone(), return_raw_connector_response: request.return_raw_connector_response, split_payment_method_data: None, webhook_url: request.webhook_url.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request body for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, /// If true, returns stringified connector raw response body pub return_raw_connector_response: Option<bool>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] /// Request for Payment Status pub struct PaymentsStatusRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, /// If true, returns stringified connector raw response body pub return_raw_connector_response: Option<bool>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The detailed error reason that was returned by the connector. pub reason: Option<String>, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// Time when the payment was last modified #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// Stringified connector raw response body. Only returned if `return_raw_connector_response` is true #[schema(value_type = Option<String>)] pub raw_connector_response: Option<Secret<String>>, /// Additional data that might be required by hyperswitch based on the additional features. pub feature_metadata: Option<FeatureMetadata>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] impl PaymentAttemptListResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( &self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.payment_attempt_list.iter().find_map(|attempt| { attempt .connector_payment_id .as_ref() .filter(|txn_id| *txn_id == connector_transaction_id) .map(|_| attempt.clone()) }) } pub fn find_attempt_in_attempts_list_using_charge_id( &self, charge_id: String, ) -> Option<PaymentAttemptResponse> { self.payment_attempt_list.iter().find_map(|attempt| { attempt.feature_metadata.as_ref().and_then(|metadata| { metadata.revenue_recovery.as_ref().and_then(|recovery| { recovery .charge_id .as_ref() .filter(|id| **id == charge_id) .map(|_| attempt.clone()) }) }) }) } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Vec<Connector>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub connector: Option<Vec<api_enums::Connector>>, /// The currency to filter payments list #[param(value_type = Option<Vec<Currency>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub currency: Option<Vec<enums::Currency>>, /// The payment status to filter payments list #[param(value_type = Option<Vec<IntentStatus>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub status: Option<Vec<enums::IntentStatus>>, /// The payment method type to filter payments list #[param(value_type = Option<Vec<PaymentMethod>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub payment_method_type: Option<Vec<enums::PaymentMethod>>, /// The payment method subtype to filter payments list #[param(value_type = Option<Vec<PaymentMethodType>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub payment_method_subtype: Option<Vec<enums::PaymentMethodType>>, /// The authentication type to filter payments list #[param(value_type = Option<Vec<AuthenticationType>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The merchant connector id to filter payments list #[param(value_type = Option<Vec<String>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<Vec<CardNetwork>>)] #[serde(deserialize_with = "parse_comma_separated", default)] pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// Optional query parameters that might be specific to a connector or flow, passed through during the retrieve operation. Use with caution and refer to specific connector documentation if applicable. pub param: Option<String>, /// Optionally specifies the connector to be used for a 'force_sync' retrieve operation. If provided, Hyperswitch will attempt to sync the payment status from this specific connector. pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, /// If enabled, provides whole connector response pub all_keys_required: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, /// Description for the item pub description: Option<String>, /// Stock Keeping Unit (SKU) or the item identifier for this item. pub sku: Option<String>, /// Universal Product Code for the item. pub upc: Option<String>, /// Code describing a commodity or a group of commodities pertaining to goods classification. pub commodity_code: Option<String>, /// Unit of measure used for the item quantity. pub unit_of_measure: Option<String>, /// Total amount for the item. #[schema(value_type = Option<i64>)] pub total_amount: Option<MinorUnit>, // total_amount, /// Discount amount applied to this item. #[schema(value_type = Option<i64>)] pub unit_discount_amount: Option<MinorUnit>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsUpdateMetadataRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Object, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: pii::SecretSerdeValue, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsUpdateMetadataResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, pub adyen: Option<AdyenConnectorMetadata>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AdyenConnectorMetadata { pub testing: AdyenTestingData, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AdyenTestingData { /// Holder name to be sent to Adyen for a card payment(CIT) or a generic payment(MIT). This value overrides the values for card.card_holder_name and applies during both CIT and MIT payment transactions. #[schema(value_type = String)] pub holder_name: Option<Secret<String>>, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// The session response structure for Amazon Pay AmazonPay(Box<AmazonPaySessionTokenResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VaultSessionDetails { Vgs(VgsSessionDetails), HyperswitchVault(HyperswitchVaultSessionDetails), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct VgsSessionDetails { /// The identifier of the external vault #[schema(value_type = String)] pub external_vault_id: Secret<String>, /// The environment for the external vault initiation pub sdk_env: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct HyperswitchVaultSessionDetails { /// Session ID for Hyperswitch Vault #[schema(value_type = String)] pub payment_method_session_id: Secret<String>, /// Client secret for Hyperswitch Vault #[schema(value_type = String)] pub client_secret: Secret<String>, /// Publishable key for Hyperswitch Vault #[schema(value_type = String)] pub publishable_key: Secret<String>, /// Profile ID for Hyperswitch Vault #[schema(value_type = String)] pub profile_id: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaypalFlow { Checkout, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaypalTransactionInfo { /// Paypal flow type #[schema(value_type = PaypalFlow, example = "checkout")] pub flow: PaypalFlow, /// Currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Authorization token used by client to initiate sdk pub client_token: Option<String>, /// The transaction info Paypal requires pub transaction_info: Option<PaypalTransactionInfo>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, /// The next action is to await for a merchant callback AwaitMerchantCallback, /// The next action is to deny the payment with an error message Deny { message: String }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse(NullObject), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPaySessionTokenResponse { /// Amazon Pay merchant account identifier pub merchant_id: String, /// Ledger currency provided during registration for the given merchant identifier #[schema(example = "USD", value_type = Currency)] pub ledger_currency: common_enums::Currency, /// Amazon Pay store ID pub store_id: String, /// Payment flow for charging the buyer pub payment_intent: AmazonPayPaymentIntent, /// The total shipping costs #[schema(value_type = String)] pub total_shipping_amount: StringMajorUnit, /// The total tax amount for the order #[schema(value_type = String)] pub total_tax_amount: StringMajorUnit, /// The total amount for items in the cart #[schema(value_type = String)] pub total_base_amount: StringMajorUnit, /// The delivery options available for the provided address pub delivery_options: Vec<AmazonPayDeliveryOptions>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum AmazonPayPaymentIntent { /// Create a Charge Permission to authorize and capture funds at a later time Confirm, /// Authorize funds immediately and capture at a later time Authorize, /// Authorize and capture funds immediately AuthorizeWithCapture, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPayDeliveryOptions { /// Delivery Option identifier pub id: String, /// Total delivery cost pub price: AmazonPayDeliveryPrice, /// Shipping method details pub shipping_method: AmazonPayShippingMethod, /// Specifies if this delivery option is the default pub is_default: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPayDeliveryPrice { /// Transaction amount in MinorUnit pub amount: MinorUnit, #[serde(skip_deserializing)] /// Transaction amount in StringMajorUnit #[schema(value_type = String)] pub display_amount: StringMajorUnit, /// Transaction currency code in ISO 4217 format #[schema(example = "USD", value_type = Currency)] pub currency_code: common_enums::Currency, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmazonPayShippingMethod { /// Name of the shipping method pub shipping_method_name: String, /// Code of the shipping method pub shipping_method_code: String, } impl AmazonPayDeliveryOptions { pub fn parse_delivery_options_request( delivery_options_request: &[serde_json::Value], ) -> Result<Vec<Self>, common_utils::errors::ParsingError> { delivery_options_request .iter() .map(|option| { serde_json::from_value(option.clone()).map_err(|_| { common_utils::errors::ParsingError::StructParseFailure( "AmazonPayDeliveryOptions", ) }) }) .collect() } pub fn get_default_delivery_amount( delivery_options: Vec<Self>, ) -> Result<MinorUnit, error_stack::Report<ValidationError>> { let mut default_options = delivery_options .into_iter() .filter(|delivery_option| delivery_option.is_default); match (default_options.next(), default_options.next()) { (Some(default_option), None) => Ok(default_option.price.amount), _ => Err(ValidationError::InvalidValue { message: "Amazon Pay Delivery Option".to_string(), }) .attach_printable("Expected exactly one default Amazon Pay Delivery Option"), } } pub fn validate_currency( currency_code: common_enums::Currency, amazonpay_supported_currencies: HashSet<common_enums::Currency>, ) -> Result<(), ValidationError> { if !amazonpay_supported_currencies.contains(&currency_code) { return Err(ValidationError::InvalidValue { message: format!("{currency_code:?} is not a supported currency."), }); } Ok(()) } pub fn insert_display_amount( delivery_options: &mut Vec<Self>, currency_code: common_enums::Currency, ) -> Result<(), error_stack::Report<common_utils::errors::ParsingError>> { let required_amount_type = common_utils::types::StringMajorUnitForCore; for option in delivery_options { let display_amount = required_amount_type .convert(option.price.amount, currency_code) .change_context(common_utils::errors::ParsingError::I64ToStringConversionFailure)?; option.price.display_amount = display_amount; } Ok(()) } } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, /// External vault session details pub vault_details: Option<VaultSessionDetails>, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, /// If enabled, provides whole connector response pub all_keys_required: Option<bool>, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } /// Request to cancel a payment when the payment is already captured #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelPostCaptureRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] /// Request constructed internally for extending authorization pub struct PaymentsExtendAuthorizationRequest { /// The identifier for the payment pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] /// Indicates if 3DS method data was successfully completed or not pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct ListMethodsForPaymentsRequest { /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, /// The two-letter ISO currency code #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))] pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>, /// Filter by amount #[schema(example = 60)] pub amount: Option<MinorUnit>, /// The three-letter ISO currency code #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))] pub accepted_currencies: Option<Vec<api_enums::Currency>>, /// Indicates whether the payment method supports recurring payments. Optional. #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for card networks #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// Indicates the limit of last used payment methods #[schema(example = 1)] pub limit: Option<i64>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethodResponseItem>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethodResponseItem>>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The payment experience for the payment method #[schema(value_type = Option<Vec<PaymentExperience>>)] pub payment_experience: Option<Vec<common_enums::PaymentExperience>>, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = RequiredFieldInfo)] pub required_fields: Vec<payment_methods::RequiredFieldInfo>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Challenge request key which should be set as form field name for creq pub challenge_request_key: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub revenue_recovery: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.revenue_recovery .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, revenue_recovery: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } #[allow(dead_code)] pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, pub payment_form_header_text: Option<String>, pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, pub is_setup_mandate_flow: Option<bool>, pub capture_method: Option<common_enums::CaptureMethod>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, pub color_icon_card_cvc_error: Option<String>, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, pub payment_form_header_text: Option<String>, pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, pub color_icon_card_cvc_error: Option<String>, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub capture_method: Option<common_enums::CaptureMethod>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, #[schema(value_type = Vec<CardNetwork>, example = "[Visa, Mastercard]")] pub card_brands: HashSet<api_enums::CardNetwork>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsEligibilityRequest { /// The identifier for the payment /// Added in the payload for ApiEventMetrics, populated from the path param #[serde(skip)] pub payment_id: id_type::PaymentId, /// Token used for client side verification #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// The payment method to be used for the payment #[schema(value_type = PaymentMethod, example = "wallet")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method type to be used for the payment #[schema(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The browser information for the payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<BrowserInformation>, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsEligibilityResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Next action to be performed by the SDK pub sdk_next_action: SdkNextAction, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: Option<PaymentConnectorTransmission>, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, #[schema(value_type = BillingConnectorPaymentMethodDetails)] /// Extra Payment Method Details that are needed to be stored pub billing_connector_payment_method_details: Option<BillingConnectorPaymentMethodDetails>, /// Invoice Next billing time #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub invoice_next_billing_time: Option<PrimitiveDateTime>, /// Invoice Next billing time #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub invoice_billing_started_at_time: Option<PrimitiveDateTime>, /// First Payment Attempt Payment Gateway Error Code #[schema(value_type = Option<String>, example = "card_declined")] pub first_payment_attempt_pg_error_code: Option<String>, /// First Payment Attempt Network Error Code #[schema(value_type = Option<String>, example = "05")] pub first_payment_attempt_network_decline_code: Option<String>, /// First Payment Attempt Network Advice Code #[schema(value_type = Option<String>, example = "02")] pub first_payment_attempt_network_advice_code: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum BillingConnectorPaymentMethodDetails { Card(BillingConnectorAdditionalCardInfo), } #[cfg(feature = "v2")] #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)] pub struct BillingConnectorAdditionalCardInfo { #[schema(value_type = CardNetwork, example = "Visa")] /// Card Network pub card_network: Option<common_enums::enums::CardNetwork>, #[schema(value_type = Option<String>, example = "JP MORGAN CHASE")] /// Card Issuer pub card_issuer: Option<String>, } #[cfg(feature = "v2")] impl BillingConnectorPaymentMethodDetails { pub fn get_billing_connector_card_info(&self) -> Option<&BillingConnectorAdditionalCardInfo> { match self { Self::Card(card_details) => Some(card_details), } } } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = Some(payment_connector_transmission); } pub fn get_payment_token_for_api_request(&self) -> mandates::ProcessorPaymentToken { mandates::ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } pub fn get_connector_customer_id(&self) -> String { self.billing_connector_payment_details .connector_customer_id .to_owned() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The additional payment data to be used for the payment attempt. pub payment_method_data: Option<RecordAttemptPaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, /// Number of attempts made for invoice #[schema(value_type = Option<u16>, example = 1)] pub retry_count: Option<u16>, /// Next Billing time of the Invoice #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub invoice_next_billing_time: Option<PrimitiveDateTime>, /// Next Billing time of the Invoice #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub invoice_billing_started_at_time: Option<PrimitiveDateTime>, /// source where the payment was triggered by #[schema(value_type = TriggeredBy, example = "internal" )] pub triggered_by: common_enums::TriggeredBy, #[schema(value_type = CardNetwork, example = "Visa" )] /// card_network pub card_network: Option<common_enums::CardNetwork>, #[schema(example = "Chase")] /// Card Issuer pub card_issuer: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct RecoveryPaymentsCreate { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: id_type::PaymentReferenceId, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_merchant_connector_id: id_type::MerchantConnectorAccountId, /// Payments connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: id_type::MerchantConnectorAccountId, #[schema(value_type = AttemptStatus, example = "charged")] pub attempt_status: enums::AttemptStatus, /// The billing details of the payment attempt. pub billing: Option<Address>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_sub_type: api_enums::PaymentMethodType, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: Secret<String>, /// Invoice billing started at billing connector end. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub billing_started_at: Option<PrimitiveDateTime>, /// A unique identifier for a payment provided by the payment connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<Secret<String>>, /// payment method token units at payment processor end. pub payment_method_data: CustomRecoveryPaymentMethodData, /// Type of action that needs to be taken after consuming the recovery payload. For example: scheduling a failed payment or stopping the invoice. pub action: common_payments_types::RecoveryAction, /// Allow partial authorization for this payment #[schema(value_type = Option<bool>, default = false)] pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema)] pub struct NullObject; impl Serialize for NullObject { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_none() } } #[cfg(test)] mod null_object_test { use serde_json; use super::*; #[allow(clippy::unwrap_used)] #[test] fn test_null_object_serialization() { let null_object = NullObject; let serialized = serde_json::to_string(&null_object).unwrap(); assert_eq!(serialized, "null"); } }
crates/api_models/src/payments.rs
api_models::src::payments
93,853
true
// File: crates/api_models/src/lib.rs // Module: api_models::src::lib pub mod admin; pub mod analytics; pub mod api_keys; pub mod apple_pay_certificates_migration; pub mod authentication; pub mod blocklist; pub mod cards_info; pub mod chat; pub mod conditional_configs; pub mod connector_enums; pub mod connector_onboarding; pub mod consts; pub mod currency; pub mod customers; pub mod disputes; pub mod enums; pub mod ephemeral_key; #[cfg(feature = "errors")] pub mod errors; pub mod events; pub mod external_service_auth; pub mod feature_matrix; pub mod files; pub mod gsm; pub mod health_check; pub mod locker_migration; pub mod mandates; pub mod open_router; pub mod organization; pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod pm_auth; pub mod poll; pub mod process_tracker; pub mod profile_acquirer; #[cfg(feature = "v2")] pub mod proxy; #[cfg(feature = "recon")] pub mod recon; pub mod refunds; pub mod relay; #[cfg(feature = "v2")] pub mod revenue_recovery_data_backfill; pub mod routing; pub mod subscription; pub mod surcharge_decision_configs; pub mod three_ds_decision_rule; #[cfg(feature = "tokenization_v2")] pub mod tokenization; pub mod user; pub mod user_role; pub mod verifications; pub mod verify_connector; pub mod webhook_events; pub mod webhooks; pub trait ValidateFieldAndGet<Request> { fn validate_field_and_get( &self, request: &Request, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ValidationError> where Self: Sized; }
crates/api_models/src/lib.rs
api_models::src::lib
370
true
// File: crates/api_models/src/conditional_configs.rs // Module: api_models::src::conditional_configs use common_utils::events; use euclid::frontend::ast::Program; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DecisionManagerRecord { pub name: String, pub program: Program<common_types::payments::ConditionalConfigs>, pub created_at: i64, pub modified_at: i64, } impl events::ApiEventMetric for DecisionManagerRecord { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct ConditionalConfigReq { pub name: Option<String>, pub algorithm: Option<Program<common_types::payments::ConditionalConfigs>>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DecisionManagerRequest { pub name: Option<String>, pub program: Option<Program<common_types::payments::ConditionalConfigs>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum DecisionManager { DecisionManagerv0(ConditionalConfigReq), DecisionManagerv1(DecisionManagerRequest), } impl events::ApiEventMetric for DecisionManager { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } pub type DecisionManagerResponse = DecisionManagerRecord; #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DecisionManagerRequest { pub name: String, pub program: Program<common_types::payments::ConditionalConfigs>, } #[cfg(feature = "v2")] impl events::ApiEventMetric for DecisionManagerRequest { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } }
crates/api_models/src/conditional_configs.rs
api_models::src::conditional_configs
444
true
// File: crates/api_models/src/disputes.rs // Module: api_models::src::disputes use std::collections::HashMap; use common_utils::types::{StringMinorUnit, TimeRange}; use masking::{Deserialize, Serialize}; use serde::de::Error; use time::PrimitiveDateTime; use utoipa::ToSchema; use super::enums::{Currency, DisputeStage, DisputeStatus}; use crate::{admin::MerchantConnectorInfo, files}; #[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq)] pub struct DisputeResponse { /// The identifier for dispute pub dispute_id: String, /// The identifier for payment_intent #[schema(value_type = String)] pub payment_id: common_utils::id_type::PaymentId, /// The identifier for payment_attempt pub attempt_id: String, /// The dispute amount pub amount: StringMinorUnit, /// The three-letter ISO currency code #[schema(value_type = Currency)] pub currency: Currency, /// Stage of the dispute pub dispute_stage: DisputeStage, /// Status of the dispute pub dispute_status: DisputeStatus, /// connector to which dispute is associated with pub connector: String, /// Status of the dispute sent by connector pub connector_status: String, /// Dispute id sent by connector pub connector_dispute_id: String, /// Reason of dispute sent by connector pub connector_reason: Option<String>, /// Reason code of dispute sent by connector pub connector_reason_code: Option<String>, /// Evidence deadline of dispute sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub challenge_required_by: Option<PrimitiveDateTime>, /// Dispute created time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_created_at: Option<PrimitiveDateTime>, /// Dispute updated time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_updated_at: Option<PrimitiveDateTime>, /// Time at which dispute is received #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The `profile_id` associated with the dispute #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The `merchant_connector_id` of the connector / processor through which the dispute was processed #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq)] pub struct DisputeResponsePaymentsRetrieve { /// The identifier for dispute pub dispute_id: String, /// Stage of the dispute pub dispute_stage: DisputeStage, /// Status of the dispute pub dispute_status: DisputeStatus, /// Status of the dispute sent by connector pub connector_status: String, /// Dispute id sent by connector pub connector_dispute_id: String, /// Reason of dispute sent by connector pub connector_reason: Option<String>, /// Reason code of dispute sent by connector pub connector_reason_code: Option<String>, /// Evidence deadline of dispute sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub challenge_required_by: Option<PrimitiveDateTime>, /// Dispute created time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_created_at: Option<PrimitiveDateTime>, /// Dispute updated time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_updated_at: Option<PrimitiveDateTime>, /// Time at which dispute is received #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, } #[derive(Debug, Serialize, Deserialize, strum::Display, Clone)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EvidenceType { CancellationPolicy, CustomerCommunication, CustomerSignature, Receipt, RefundPolicy, ServiceDocumentation, ShippingDocumentation, InvoiceShowingDistinctTransactions, RecurringTransactionAgreement, UncategorizedFile, } #[derive(Clone, Debug, Serialize, ToSchema)] pub struct DisputeEvidenceBlock { /// Evidence type pub evidence_type: EvidenceType, /// File metadata pub file_metadata_response: files::FileMetadataResponse, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct DisputeListGetConstraints { /// The identifier for dispute pub dispute_id: Option<String>, /// The payment_id against which dispute is raised pub payment_id: Option<common_utils::id_type::PaymentId>, /// Limit on the number of objects to return pub limit: Option<u32>, /// The starting point within a list of object pub offset: Option<u32>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The comma separated list of status of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub dispute_status: Option<Vec<DisputeStatus>>, /// The comma separated list of stages of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub dispute_stage: Option<Vec<DisputeStage>>, /// Reason for the dispute pub reason: Option<String>, /// The comma separated list of connectors linked to disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub connector: Option<Vec<String>>, /// The comma separated list of currencies of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub currency: Option<Vec<Currency>>, /// The merchant connector id to filter the disputes list pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<TimeRange>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct DisputeListFilters { /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<Currency>, /// The list of available dispute status filters pub dispute_status: Vec<DisputeStatus>, /// The list of available dispute stage filters pub dispute_stage: Vec<DisputeStage>, } #[derive(Default, Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct SubmitEvidenceRequest { ///Dispute Id pub dispute_id: String, /// Logs showing the usage of service by customer pub access_activity_log: Option<String>, /// Billing address of the customer pub billing_address: Option<String>, /// File Id of cancellation policy pub cancellation_policy: Option<String>, /// Details of showing cancellation policy to customer before purchase pub cancellation_policy_disclosure: Option<String>, /// Details telling why customer's subscription was not cancelled pub cancellation_rebuttal: Option<String>, /// File Id of customer communication pub customer_communication: Option<String>, /// Customer email address pub customer_email_address: Option<String>, /// Customer name pub customer_name: Option<String>, /// IP address of the customer pub customer_purchase_ip: Option<String>, /// Fild Id of customer signature pub customer_signature: Option<String>, /// Product Description pub product_description: Option<String>, /// File Id of receipt pub receipt: Option<String>, /// File Id of refund policy pub refund_policy: Option<String>, /// Details of showing refund policy to customer before purchase pub refund_policy_disclosure: Option<String>, /// Details why customer is not entitled to refund pub refund_refusal_explanation: Option<String>, /// Customer service date pub service_date: Option<String>, /// File Id service documentation pub service_documentation: Option<String>, /// Shipping address of the customer pub shipping_address: Option<String>, /// Delivery service that shipped the product pub shipping_carrier: Option<String>, /// Shipping date pub shipping_date: Option<String>, /// File Id shipping documentation pub shipping_documentation: Option<String>, /// Tracking number of shipped product pub shipping_tracking_number: Option<String>, /// File Id showing two distinct transactions when customer claims a payment was charged twice pub invoice_showing_distinct_transactions: Option<String>, /// File Id of recurring transaction agreement pub recurring_transaction_agreement: Option<String>, /// Any additional supporting file pub uncategorized_file: Option<String>, /// Any additional evidence statements pub uncategorized_text: Option<String>, } #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct DeleteEvidenceRequest { /// Id of the dispute pub dispute_id: String, /// Evidence Type to be deleted pub evidence_type: EvidenceType, } #[derive(Debug, Deserialize, Serialize)] pub struct DisputeRetrieveRequest { /// The identifier for dispute pub dispute_id: String, /// Decider to enable or disable the connector call for dispute retrieve request pub force_sync: Option<bool>, } #[derive(Clone, Debug, serde::Serialize)] pub struct DisputesAggregateResponse { /// Different status of disputes with their count pub status_with_count: HashMap<DisputeStatus, i64>, } #[derive(Debug, Deserialize, Serialize)] pub struct DisputeRetrieveBody { /// Decider to enable or disable the connector call for dispute retrieve request pub force_sync: Option<bool>, } fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error> where D: serde::Deserializer<'de>, T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error, { let output = Option::<&str>::deserialize(v)?; output .map(|s| { s.split(",") .map(|x| x.parse::<T>().map_err(D::Error::custom)) .collect::<Result<_, _>>() }) .transpose() }
crates/api_models/src/disputes.rs
api_models::src::disputes
2,358
true
// File: crates/api_models/src/subscription.rs // Module: api_models::src::subscription use common_enums::connector_enums::InvoiceStatus; use common_types::payments::CustomerAcceptance; use common_utils::{ events::ApiEventMetric, id_type::{ CustomerId, InvoiceId, MerchantConnectorAccountId, MerchantId, PaymentId, ProfileId, SubscriptionId, }, types::{MinorUnit, Url}, }; use masking::Secret; use utoipa::ToSchema; use crate::{ enums::{ AuthenticationType, CaptureMethod, Currency, FutureUsage, IntentStatus, PaymentExperience, PaymentMethod, PaymentMethodType, PaymentType, }, mandates::RecurringDetails, payments::{Address, NextActionData, PaymentMethodDataRequest}, }; /// Request payload for creating a subscription. /// /// This struct captures details required to create a subscription, /// including plan, profile, merchant connector, and optional customer info. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateSubscriptionRequest { /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, /// Identifier for the subscription plan. pub plan_id: Option<String>, /// Optional coupon code applied to the subscription. pub coupon_code: Option<String>, /// customer ID associated with this subscription. pub customer_id: CustomerId, /// payment details for the subscription. pub payment_details: CreateSubscriptionPaymentDetails, /// billing address for the subscription. pub billing: Option<Address>, /// shipping address for the subscription. pub shipping: Option<Address>, } /// Response payload returned after successfully creating a subscription. /// /// Includes details such as subscription ID, status, plan, merchant, and customer info. #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct SubscriptionResponse { /// Unique identifier for the subscription. pub id: SubscriptionId, /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, /// Current status of the subscription. pub status: SubscriptionStatus, /// Identifier for the associated subscription plan. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: Option<String>, /// Associated profile ID. pub profile_id: ProfileId, #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<Secret<String>>, /// Merchant identifier owning this subscription. pub merchant_id: MerchantId, /// Optional coupon code applied to this subscription. pub coupon_code: Option<String>, /// Optional customer ID associated with this subscription. pub customer_id: CustomerId, /// Payment details for the invoice. pub payment: Option<PaymentResponseData>, /// Invoice Details for the subscription. pub invoice: Option<Invoice>, } /// Possible states of a subscription lifecycle. /// /// - `Created`: Subscription was created but not yet activated. /// - `Active`: Subscription is currently active. /// - `InActive`: Subscription is inactive. /// - `Pending`: Subscription is pending activation. /// - `Trial`: Subscription is in a trial period. /// - `Paused`: Subscription is paused. /// - `Unpaid`: Subscription is unpaid. /// - `Onetime`: Subscription is a one-time payment. /// - `Cancelled`: Subscription has been cancelled. /// - `Failed`: Subscription has failed. #[derive(Debug, Clone, serde::Serialize, strum::EnumString, strum::Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SubscriptionStatus { /// Subscription is active. Active, /// Subscription is created but not yet active. Created, /// Subscription is inactive. InActive, /// Subscription is in pending state. Pending, /// Subscription is in trial state. Trial, /// Subscription is paused. Paused, /// Subscription is unpaid. Unpaid, /// Subscription is a one-time payment. Onetime, /// Subscription is cancelled. Cancelled, /// Subscription has failed. Failed, } impl SubscriptionResponse { /// Creates a new [`CreateSubscriptionResponse`] with the given identifiers. /// /// By default, `client_secret`, `coupon_code`, and `customer` fields are `None`. #[allow(clippy::too_many_arguments)] pub fn new( id: SubscriptionId, merchant_reference_id: Option<String>, status: SubscriptionStatus, plan_id: Option<String>, item_price_id: Option<String>, profile_id: ProfileId, merchant_id: MerchantId, client_secret: Option<Secret<String>>, customer_id: CustomerId, payment: Option<PaymentResponseData>, invoice: Option<Invoice>, ) -> Self { Self { id, merchant_reference_id, status, plan_id, item_price_id, profile_id, client_secret, merchant_id, coupon_code: None, customer_id, payment, invoice, } } } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct GetPlansResponse { pub plan_id: String, pub name: String, pub description: Option<String>, pub price_id: Vec<SubscriptionPlanPrices>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct SubscriptionPlanPrices { pub price_id: String, pub plan_id: Option<String>, pub amount: MinorUnit, pub currency: Currency, pub interval: PeriodUnit, pub interval_count: i64, pub trial_period: Option<i64>, pub trial_period_unit: Option<PeriodUnit>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub enum PeriodUnit { Day, Week, Month, Year, } /// For Client based calls, SDK will use the client_secret\nin order to call /payment_methods\nClient secret will be generated whenever a new\npayment method is created #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ClientSecret(String); impl ClientSecret { pub fn new(secret: String) -> Self { Self(secret) } pub fn as_str(&self) -> &str { &self.0 } pub fn as_string(&self) -> &String { &self.0 } } #[derive(serde::Deserialize, serde::Serialize, Debug, ToSchema)] pub struct GetPlansQuery { #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<ClientSecret>, pub limit: Option<u32>, pub offset: Option<u32>, } impl ApiEventMetric for SubscriptionResponse {} impl ApiEventMetric for CreateSubscriptionRequest {} impl ApiEventMetric for GetPlansQuery {} impl ApiEventMetric for GetPlansResponse {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionPaymentDetails { pub shipping: Option<Address>, pub billing: Option<Address>, pub payment_method: PaymentMethod, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: PaymentMethodDataRequest, pub customer_acceptance: Option<CustomerAcceptance>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateSubscriptionPaymentDetails { /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = String)] pub return_url: Url, pub setup_future_usage: Option<FutureUsage>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentDetails { pub payment_method: Option<PaymentMethod>, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: Option<PaymentMethodDataRequest>, pub setup_future_usage: Option<FutureUsage>, pub customer_acceptance: Option<CustomerAcceptance>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, pub payment_type: Option<PaymentType>, } // Creating new type for PaymentRequest API call as usage of api_models::PaymentsRequest will result in invalid payment request during serialization // Eg: Amount will be serialized as { amount: {Value: 100 }} #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CreatePaymentsRequestData { pub amount: MinorUnit, pub currency: Currency, pub customer_id: Option<CustomerId>, pub billing: Option<Address>, pub shipping: Option<Address>, pub profile_id: Option<ProfileId>, pub setup_future_usage: Option<FutureUsage>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct ConfirmPaymentsRequestData { pub billing: Option<Address>, pub shipping: Option<Address>, pub profile_id: Option<ProfileId>, pub payment_method: PaymentMethod, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: PaymentMethodDataRequest, pub customer_acceptance: Option<CustomerAcceptance>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CreateAndConfirmPaymentsRequestData { pub amount: MinorUnit, pub currency: Currency, pub customer_id: Option<CustomerId>, pub confirm: bool, pub billing: Option<Address>, pub shipping: Option<Address>, pub profile_id: Option<ProfileId>, pub setup_future_usage: Option<FutureUsage>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, pub payment_method: Option<PaymentMethod>, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: Option<PaymentMethodDataRequest>, pub customer_acceptance: Option<CustomerAcceptance>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentResponseData { pub payment_id: PaymentId, pub status: IntentStatus, pub amount: MinorUnit, pub currency: Currency, pub profile_id: Option<ProfileId>, pub connector: Option<String>, /// Identifier for Payment Method #[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<Secret<String>>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub next_action: Option<NextActionData>, pub payment_experience: Option<PaymentExperience>, pub error_code: Option<String>, pub error_message: Option<String>, pub payment_method_type: Option<PaymentMethodType>, #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<Secret<String>>, pub billing: Option<Address>, pub shipping: Option<Address>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateMitPaymentRequestData { pub amount: MinorUnit, pub currency: Currency, pub confirm: bool, pub customer_id: Option<CustomerId>, pub recurring_details: Option<RecurringDetails>, pub off_session: Option<bool>, pub profile_id: Option<ProfileId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionRequest { #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<ClientSecret>, /// Payment details for the invoice. pub payment_details: ConfirmSubscriptionPaymentDetails, } impl ConfirmSubscriptionRequest { pub fn get_billing_address(&self) -> Option<Address> { self.payment_details .payment_method_data .billing .as_ref() .or(self.payment_details.billing.as_ref()) .cloned() } } impl ApiEventMetric for ConfirmSubscriptionRequest {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateAndConfirmSubscriptionRequest { /// Identifier for the associated plan_id. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, /// Identifier for the coupon code for the subscription. pub coupon_code: Option<String>, /// Identifier for customer. pub customer_id: CustomerId, /// Billing address for the subscription. pub billing: Option<Address>, /// Shipping address for the subscription. pub shipping: Option<Address>, /// Payment details for the invoice. pub payment_details: PaymentDetails, /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, } impl CreateAndConfirmSubscriptionRequest { pub fn get_billing_address(&self) -> Option<Address> { self.payment_details .payment_method_data .as_ref() .and_then(|data| data.billing.clone()) .or(self.billing.clone()) } } impl ApiEventMetric for CreateAndConfirmSubscriptionRequest {} #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct ConfirmSubscriptionResponse { /// Unique identifier for the subscription. pub id: SubscriptionId, /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, /// Current status of the subscription. pub status: SubscriptionStatus, /// Identifier for the associated subscription plan. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: Option<String>, /// Optional coupon code applied to this subscription. pub coupon: Option<String>, /// Associated profile ID. pub profile_id: ProfileId, /// Payment details for the invoice. pub payment: Option<PaymentResponseData>, /// Customer ID associated with this subscription. pub customer_id: Option<CustomerId>, /// Invoice Details for the subscription. pub invoice: Option<Invoice>, /// Billing Processor subscription ID. pub billing_processor_subscription_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct Invoice { /// Unique identifier for the invoice. pub id: InvoiceId, /// Unique identifier for the subscription. pub subscription_id: SubscriptionId, /// Identifier for the merchant. pub merchant_id: MerchantId, /// Identifier for the profile. pub profile_id: ProfileId, /// Identifier for the merchant connector account. pub merchant_connector_id: MerchantConnectorAccountId, /// Identifier for the Payment. pub payment_intent_id: Option<PaymentId>, /// Identifier for Payment Method #[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<String>, /// Identifier for the Customer. pub customer_id: CustomerId, /// Invoice amount. pub amount: MinorUnit, /// Currency for the invoice payment. pub currency: Currency, /// Status of the invoice. pub status: InvoiceStatus, } impl ApiEventMetric for ConfirmSubscriptionResponse {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpdateSubscriptionRequest { /// Identifier for the associated plan_id. pub plan_id: String, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, } impl ApiEventMetric for UpdateSubscriptionRequest {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct EstimateSubscriptionQuery { /// Identifier for the associated subscription plan. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, /// Identifier for the coupon code for the subscription. pub coupon_code: Option<String>, } impl ApiEventMetric for EstimateSubscriptionQuery {} #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct EstimateSubscriptionResponse { /// Estimated amount to be charged for the invoice. pub amount: MinorUnit, /// Currency for the amount. pub currency: Currency, /// Identifier for the associated plan_id. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: Option<String>, /// Identifier for the coupon code for the subscription. pub coupon_code: Option<String>, /// Identifier for customer. pub customer_id: Option<CustomerId>, pub line_items: Vec<SubscriptionLineItem>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct SubscriptionLineItem { /// Unique identifier for the line item. pub item_id: String, /// Type of the line item. pub item_type: String, /// Description of the line item. pub description: String, /// Amount for the line item. pub amount: MinorUnit, /// Currency for the line item pub currency: Currency, /// Quantity of the line item. pub quantity: i64, } impl ApiEventMetric for EstimateSubscriptionResponse {}
crates/api_models/src/subscription.rs
api_models::src::subscription
3,958
true
// File: crates/api_models/src/enums.rs // Module: api_models::src::enums use std::str::FromStr; pub use common_enums::*; use utoipa::ToSchema; pub use super::connector_enums::Connector; #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithm { RoundRobin, MaxConversion, MinCost, Custom, } #[cfg(feature = "payouts")] #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutConnectors { Adyen, Adyenplatform, Cybersource, Ebanx, Gigadat, Loonio, Nomupay, Nuvei, Payone, Paypal, Stripe, Wise, Worldpay, } #[cfg(feature = "v2")] /// Whether active attempt is to be set/unset #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum UpdateActiveAttempt { /// Request to set the active attempt id #[schema(value_type = Option<String>)] Set(common_utils::id_type::GlobalAttemptId), /// To unset the active attempt id Unset, } #[cfg(feature = "payouts")] impl From<PayoutConnectors> for RoutableConnectors { fn from(value: PayoutConnectors) -> Self { match value { PayoutConnectors::Adyen => Self::Adyen, PayoutConnectors::Adyenplatform => Self::Adyenplatform, PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Gigadat => Self::Gigadat, PayoutConnectors::Loonio => Self::Loonio, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Stripe => Self::Stripe, PayoutConnectors::Wise => Self::Wise, PayoutConnectors::Worldpay => Self::Worldpay, } } } #[cfg(feature = "payouts")] impl From<PayoutConnectors> for Connector { fn from(value: PayoutConnectors) -> Self { match value { PayoutConnectors::Adyen => Self::Adyen, PayoutConnectors::Adyenplatform => Self::Adyenplatform, PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Gigadat => Self::Gigadat, PayoutConnectors::Loonio => Self::Loonio, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Stripe => Self::Stripe, PayoutConnectors::Wise => Self::Wise, PayoutConnectors::Worldpay => Self::Worldpay, } } } #[cfg(feature = "payouts")] impl TryFrom<Connector> for PayoutConnectors { type Error = String; fn try_from(value: Connector) -> Result<Self, Self::Error> { match value { Connector::Adyen => Ok(Self::Adyen), Connector::Adyenplatform => Ok(Self::Adyenplatform), Connector::Cybersource => Ok(Self::Cybersource), Connector::Ebanx => Ok(Self::Ebanx), Connector::Gigadat => Ok(Self::Gigadat), Connector::Loonio => Ok(Self::Loonio), Connector::Nuvei => Ok(Self::Nuvei), Connector::Nomupay => Ok(Self::Nomupay), Connector::Payone => Ok(Self::Payone), Connector::Paypal => Ok(Self::Paypal), Connector::Stripe => Ok(Self::Stripe), Connector::Wise => Ok(Self::Wise), Connector::Worldpay => Ok(Self::Worldpay), _ => Err(format!("Invalid payout connector {value}")), } } } #[cfg(feature = "frm")] #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmConnectors { /// Signifyd Risk Manager. Official docs: https://docs.signifyd.com/ Signifyd, Riskified, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum TaxConnectors { Taxjar, } #[derive(Clone, Debug, serde::Serialize, strum::EnumString, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BillingConnectors { Chargebee, Recurly, Stripebilling, Custombilling, #[cfg(feature = "dummy_connector")] DummyBillingConnector, } #[derive(Clone, Copy, Debug, serde::Serialize, strum::EnumString, Eq, PartialEq)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum VaultConnectors { Vgs, HyperswitchVault, Tokenex, } impl From<VaultConnectors> for Connector { fn from(value: VaultConnectors) -> Self { match value { VaultConnectors::Vgs => Self::Vgs, VaultConnectors::HyperswitchVault => Self::HyperswitchVault, VaultConnectors::Tokenex => Self::Tokenex, } } } #[derive( Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FrmAction { CancelTxn, AutoRefund, ManualReview, } #[derive( Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FrmPreferredFlowTypes { Pre, Post, } #[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] pub struct UnresolvedResponseReason { pub code: String, /// A message to merchant to give hint on next action he/she should do to resolve pub message: String, } /// Possible field type of required fields in payment_method_data #[derive( Clone, Debug, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FieldType { UserCardNumber, UserCardExpiryMonth, UserCardExpiryYear, UserCardCvc, UserCardNetwork, UserFullName, UserEmailAddress, UserPhoneNumber, UserPhoneNumberCountryCode, //phone number's country code UserCountry { options: Vec<String> }, //for country inside payment method data ex- bank redirect UserCurrency { options: Vec<String> }, UserCryptoCurrencyNetwork, //for crypto network associated with the cryptopcurrency UserBillingName, UserAddressLine1, UserAddressLine2, UserAddressCity, UserAddressPincode, UserAddressState, UserAddressCountry { options: Vec<String> }, UserShippingName, UserShippingAddressLine1, UserShippingAddressLine2, UserShippingAddressCity, UserShippingAddressPincode, UserShippingAddressState, UserShippingAddressCountry { options: Vec<String> }, UserSocialSecurityNumber, UserBlikCode, UserBank, UserBankOptions { options: Vec<String> }, UserBankAccountNumber, UserSourceBankAccountId, UserDestinationBankAccountId, Text, DropDown { options: Vec<String> }, UserDateOfBirth, UserVpaId, LanguagePreference { options: Vec<String> }, UserPixKey, UserCpf, UserCnpj, UserIban, UserBsbNumber, UserBankSortCode, UserBankRoutingNumber, UserBankType { options: Vec<String> }, UserBankAccountHolderName, UserMsisdn, UserClientIdentifier, OrderDetailsProductName, } impl FieldType { pub fn get_billing_variants() -> Vec<Self> { vec![ Self::UserBillingName, Self::UserAddressLine1, Self::UserAddressLine2, Self::UserAddressCity, Self::UserAddressPincode, Self::UserAddressState, Self::UserAddressCountry { options: vec![] }, ] } pub fn get_shipping_variants() -> Vec<Self> { vec![ Self::UserShippingName, Self::UserShippingAddressLine1, Self::UserShippingAddressLine2, Self::UserShippingAddressCity, Self::UserShippingAddressPincode, Self::UserShippingAddressState, Self::UserShippingAddressCountry { options: vec![] }, ] } } /// This implementatiobn is to ignore the inner value of UserAddressCountry enum while comparing impl PartialEq for FieldType { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::UserCardNumber, Self::UserCardNumber) => true, (Self::UserCardExpiryMonth, Self::UserCardExpiryMonth) => true, (Self::UserCardExpiryYear, Self::UserCardExpiryYear) => true, (Self::UserCardCvc, Self::UserCardCvc) => true, (Self::UserFullName, Self::UserFullName) => true, (Self::UserEmailAddress, Self::UserEmailAddress) => true, (Self::UserPhoneNumber, Self::UserPhoneNumber) => true, (Self::UserPhoneNumberCountryCode, Self::UserPhoneNumberCountryCode) => true, ( Self::UserCountry { options: options_self, }, Self::UserCountry { options: options_other, }, ) => options_self.eq(options_other), ( Self::UserCurrency { options: options_self, }, Self::UserCurrency { options: options_other, }, ) => options_self.eq(options_other), (Self::UserCryptoCurrencyNetwork, Self::UserCryptoCurrencyNetwork) => true, (Self::UserBillingName, Self::UserBillingName) => true, (Self::UserAddressLine1, Self::UserAddressLine1) => true, (Self::UserAddressLine2, Self::UserAddressLine2) => true, (Self::UserAddressCity, Self::UserAddressCity) => true, (Self::UserAddressPincode, Self::UserAddressPincode) => true, (Self::UserAddressState, Self::UserAddressState) => true, (Self::UserAddressCountry { .. }, Self::UserAddressCountry { .. }) => true, (Self::UserShippingName, Self::UserShippingName) => true, (Self::UserShippingAddressLine1, Self::UserShippingAddressLine1) => true, (Self::UserShippingAddressLine2, Self::UserShippingAddressLine2) => true, (Self::UserShippingAddressCity, Self::UserShippingAddressCity) => true, (Self::UserShippingAddressPincode, Self::UserShippingAddressPincode) => true, (Self::UserShippingAddressState, Self::UserShippingAddressState) => true, (Self::UserShippingAddressCountry { .. }, Self::UserShippingAddressCountry { .. }) => { true } (Self::UserBlikCode, Self::UserBlikCode) => true, (Self::UserBank, Self::UserBank) => true, (Self::Text, Self::Text) => true, ( Self::DropDown { options: options_self, }, Self::DropDown { options: options_other, }, ) => options_self.eq(options_other), (Self::UserDateOfBirth, Self::UserDateOfBirth) => true, (Self::UserVpaId, Self::UserVpaId) => true, (Self::UserPixKey, Self::UserPixKey) => true, (Self::UserCpf, Self::UserCpf) => true, (Self::UserCnpj, Self::UserCnpj) => true, (Self::LanguagePreference { .. }, Self::LanguagePreference { .. }) => true, (Self::UserMsisdn, Self::UserMsisdn) => true, (Self::UserClientIdentifier, Self::UserClientIdentifier) => true, (Self::OrderDetailsProductName, Self::OrderDetailsProductName) => true, _unused => false, } } } #[cfg(test)] mod test { use super::*; #[test] fn test_partialeq_for_field_type() { let user_address_country_is_us = FieldType::UserAddressCountry { options: vec!["US".to_string()], }; let user_address_country_is_all = FieldType::UserAddressCountry { options: vec!["ALL".to_string()], }; assert!(user_address_country_is_us.eq(&user_address_country_is_all)) } } /// Denotes the retry action #[derive( Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, Clone, PartialEq, Eq, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RetryAction { /// Manual retry through request is being deprecated, now it is available through profile ManualRetry, /// Denotes that the payment is requeued Requeue, } #[derive(Clone, Copy)] pub enum LockerChoice { HyperswitchCardVault, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PmAuthConnectors { Plaid, } pub fn convert_pm_auth_connector(connector_name: &str) -> Option<PmAuthConnectors> { PmAuthConnectors::from_str(connector_name).ok() } pub fn convert_authentication_connector(connector_name: &str) -> Option<AuthenticationConnectors> { AuthenticationConnectors::from_str(connector_name).ok() } pub fn convert_tax_connector(connector_name: &str) -> Option<TaxConnectors> { TaxConnectors::from_str(connector_name).ok() } pub fn convert_billing_connector(connector_name: &str) -> Option<BillingConnectors> { BillingConnectors::from_str(connector_name).ok() } #[cfg(feature = "frm")] pub fn convert_frm_connector(connector_name: &str) -> Option<FrmConnectors> { FrmConnectors::from_str(connector_name).ok() } pub fn convert_vault_connector(connector_name: &str) -> Option<VaultConnectors> { VaultConnectors::from_str(connector_name).ok() } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] pub enum ReconPermissionScope { #[serde(rename = "R")] Read = 0, #[serde(rename = "RW")] Write = 1, } impl From<PermissionScope> for ReconPermissionScope { fn from(scope: PermissionScope) -> Self { match scope { PermissionScope::Read => Self::Read, PermissionScope::Write => Self::Write, } } } #[cfg(feature = "v2")] #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[serde(rename_all = "UPPERCASE")] #[strum(serialize_all = "UPPERCASE")] pub enum TokenStatus { /// Indicates that the token is active and can be used for payments Active, /// Indicates that the token is suspended from network's end for some reason and can't be used for payments until it is re-activated Suspended, /// Indicates that the token is deactivated and further can't be used for payments Deactivated, }
crates/api_models/src/enums.rs
api_models::src::enums
3,897
true
// File: crates/api_models/src/blocklist.rs // Module: api_models::src::blocklist use common_enums::enums; use common_utils::events::ApiEventMetric; use masking::StrongSecret; use utoipa::ToSchema; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type", content = "data")] pub enum BlocklistRequest { CardBin(String), Fingerprint(String), ExtendedCardBin(String), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GenerateFingerprintRequest { pub card: Card, pub hash_key: StrongSecret<String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct Card { pub card_number: StrongSecret<String>, } pub type AddToBlocklistRequest = BlocklistRequest; pub type DeleteFromBlocklistRequest = BlocklistRequest; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BlocklistResponse { pub fingerprint_id: String, #[schema(value_type = BlocklistDataKind)] pub data_kind: enums::BlocklistDataKind, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct GenerateFingerprintResponsePayload { pub card_fingerprint: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleBlocklistResponse { pub blocklist_guard_status: String, } pub type AddToBlocklistResponse = BlocklistResponse; pub type DeleteFromBlocklistResponse = BlocklistResponse; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ListBlocklistQuery { #[schema(value_type = BlocklistDataKind)] pub data_kind: enums::BlocklistDataKind, #[serde(default = "default_list_limit")] pub limit: u16, #[serde(default)] pub offset: u16, pub client_secret: Option<String>, } fn default_list_limit() -> u16 { 10 } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleBlocklistQuery { #[schema(value_type = BlocklistDataKind)] pub status: bool, } impl ApiEventMetric for BlocklistRequest {} impl ApiEventMetric for BlocklistResponse {} impl ApiEventMetric for ToggleBlocklistResponse {} impl ApiEventMetric for ListBlocklistQuery {} impl ApiEventMetric for GenerateFingerprintRequest {} impl ApiEventMetric for ToggleBlocklistQuery {} impl ApiEventMetric for GenerateFingerprintResponsePayload {} impl ApiEventMetric for Card {}
crates/api_models/src/blocklist.rs
api_models::src::blocklist
606
true
// File: crates/api_models/src/user.rs // Module: api_models::src::user use std::fmt::Debug; use common_enums::{EntityType, TokenPurpose}; use common_utils::{crypto::OptionalEncryptableName, id_type, pii}; use masking::Secret; use utoipa::ToSchema; use crate::user_role::UserStatus; pub mod dashboard_metadata; #[cfg(feature = "dummy_connector")] pub mod sample_data; #[cfg(feature = "control_center_theme")] pub mod theme; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct SignUpWithMerchantIdRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, pub company_name: String, } pub type SignUpWithMerchantIdResponse = AuthorizeResponse; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct SignUpRequest { pub email: pii::Email, pub password: Secret<String>, } pub type SignInRequest = SignUpRequest; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct ConnectAccountRequest { pub email: pii::Email, } pub type ConnectAccountResponse = AuthorizeResponse; #[derive(serde::Serialize, Debug, Clone)] pub struct AuthorizeResponse { pub is_email_sent: bool, //this field is added for audit/debug reasons #[serde(skip_serializing)] pub user_id: String, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ChangePasswordRequest { pub new_password: Secret<String>, pub old_password: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ForgotPasswordRequest { pub email: pii::Email, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ResetPasswordRequest { pub token: Secret<String>, pub password: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct RotatePasswordRequest { pub password: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct InviteUserRequest { pub email: pii::Email, pub name: Secret<String>, pub role_id: String, } #[derive(Debug, serde::Serialize)] pub struct InviteMultipleUserResponse { pub email: pii::Email, pub is_email_sent: bool, #[serde(skip_serializing_if = "Option::is_none")] pub password: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub error: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ReInviteUserRequest { pub email: pii::Email, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct AcceptInviteFromEmailRequest { pub token: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchOrganizationRequest { pub org_id: id_type::OrganizationId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchMerchantRequest { pub merchant_id: id_type::MerchantId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchProfileRequest { pub profile_id: id_type::ProfileId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CloneConnectorSource { pub mca_id: id_type::MerchantConnectorAccountId, pub merchant_id: id_type::MerchantId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CloneConnectorDestination { pub connector_label: Option<String>, pub profile_id: id_type::ProfileId, pub merchant_id: id_type::MerchantId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CloneConnectorRequest { pub source: CloneConnectorSource, pub destination: CloneConnectorDestination, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CreateInternalUserRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, pub role_id: String, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CreateTenantUserRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct UserOrgMerchantCreateRequest { pub organization_name: Secret<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub merchant_name: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PlatformAccountCreateRequest { #[schema(max_length = 64, value_type = String, example = "organization_abc")] pub organization_name: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PlatformAccountCreateResponse { #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_abc")] pub org_id: id_type::OrganizationId, #[schema(value_type = Option<String>, example = "organization_abc")] pub org_name: Option<String>, #[schema(value_type = OrganizationType, example = "standard")] pub org_type: common_enums::OrganizationType, #[schema(value_type = String, example = "merchant_abc")] pub merchant_id: id_type::MerchantId, #[schema(value_type = MerchantAccountType, example = "standard")] pub merchant_account_type: common_enums::MerchantAccountType, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserMerchantCreate { pub company_name: String, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: Option<common_enums::MerchantAccountRequestType>, } #[derive(serde::Serialize, Debug, Clone)] pub struct GetUserDetailsResponse { pub merchant_id: id_type::MerchantId, pub name: Secret<String>, pub email: pii::Email, pub verification_days_left: Option<i64>, pub role_id: String, // This field is added for audit/debug reasons #[serde(skip_serializing)] pub user_id: String, pub org_id: id_type::OrganizationId, pub is_two_factor_auth_setup: bool, pub recovery_codes_left: Option<usize>, pub profile_id: id_type::ProfileId, pub entity_type: EntityType, pub theme_id: Option<String>, pub version: common_enums::ApiVersion, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetUserRoleDetailsRequest { pub email: pii::Email, } #[derive(Debug, serde::Serialize)] pub struct GetUserRoleDetailsResponseV2 { pub role_id: String, pub org: NameIdUnit<Option<String>, id_type::OrganizationId>, pub merchant: Option<NameIdUnit<OptionalEncryptableName, id_type::MerchantId>>, pub profile: Option<NameIdUnit<String, id_type::ProfileId>>, pub status: UserStatus, pub entity_type: EntityType, pub role_name: String, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct NameIdUnit<N: Debug + Clone, I: Debug + Clone> { pub name: N, pub id: I, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyEmailRequest { pub token: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct SendVerifyEmailRequest { pub email: pii::Email, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateUserAccountDetailsRequest { pub name: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SkipTwoFactorAuthQueryParam { pub skip_two_factor_auth: Option<bool>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TokenResponse { pub token: Secret<String>, pub token_type: TokenPurpose, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthStatusResponse { pub totp: bool, pub recovery_code: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthAttempts { pub is_completed: bool, pub remaining_attempts: u8, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthStatusResponseWithAttempts { pub totp: TwoFactorAuthAttempts, pub recovery_code: TwoFactorAuthAttempts, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorStatus { pub status: Option<TwoFactorAuthStatusResponseWithAttempts>, pub is_skippable: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserFromEmailRequest { pub token: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct BeginTotpResponse { pub secret: Option<TotpSecret>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TotpSecret { pub secret: Secret<String>, pub totp_url: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyTotpRequest { pub totp: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyRecoveryCodeRequest { pub recovery_code: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct RecoveryCodes { pub recovery_codes: Vec<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(tag = "auth_type")] #[serde(rename_all = "snake_case")] pub enum AuthConfig { OpenIdConnect { private_config: OpenIdConnectPrivateConfig, public_config: OpenIdConnectPublicConfig, }, MagicLink, Password, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct OpenIdConnectPrivateConfig { pub base_url: String, pub client_id: Secret<String>, pub client_secret: Secret<String>, pub private_key: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct OpenIdConnectPublicConfig { pub name: OpenIdProvider, } #[derive( Debug, serde::Deserialize, serde::Serialize, Copy, Clone, strum::Display, Eq, PartialEq, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OpenIdProvider { Okta, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct OpenIdConnect { pub name: OpenIdProvider, pub base_url: String, pub client_id: String, pub client_secret: Secret<String>, pub private_key: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateUserAuthenticationMethodRequest { pub owner_id: String, pub owner_type: common_enums::Owner, pub auth_method: AuthConfig, pub allow_signup: bool, pub email_domain: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateUserAuthenticationMethodResponse { pub id: String, pub auth_id: String, pub owner_id: String, pub owner_type: common_enums::Owner, pub auth_type: common_enums::UserAuthType, pub email_domain: Option<String>, pub allow_signup: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum UpdateUserAuthenticationMethodRequest { AuthMethod { id: String, auth_config: AuthConfig, }, EmailDomain { owner_id: String, email_domain: String, }, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetUserAuthenticationMethodsRequest { pub auth_id: Option<String>, pub email_domain: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserAuthenticationMethodResponse { pub id: String, pub auth_id: String, pub auth_method: AuthMethodDetails, pub allow_signup: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthMethodDetails { #[serde(rename = "type")] pub auth_type: common_enums::UserAuthType, pub name: Option<OpenIdProvider>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetSsoAuthUrlRequest { pub id: String, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SsoSignInRequest { pub state: Secret<String>, pub code: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthIdAndThemeIdQueryParam { pub auth_id: Option<String>, pub theme_id: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthSelectRequest { pub id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct UserKeyTransferRequest { pub from: u32, pub limit: u32, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserTransferKeyResponse { pub total_transferred: usize, } #[derive(Debug, serde::Serialize)] pub struct ListOrgsForUserResponse { pub org_id: id_type::OrganizationId, pub org_name: Option<String>, pub org_type: common_enums::OrganizationType, } #[derive(Debug, serde::Serialize)] pub struct UserMerchantAccountResponse { pub merchant_id: id_type::MerchantId, pub merchant_name: OptionalEncryptableName, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, pub version: common_enums::ApiVersion, } #[derive(Debug, serde::Serialize)] pub struct ListProfilesForUserInOrgAndMerchantAccountResponse { pub profile_id: id_type::ProfileId, pub profile_name: String, }
crates/api_models/src/user.rs
api_models::src::user
3,045
true
// File: crates/api_models/src/user_role.rs // Module: api_models::src::user_role use common_enums::{ParentGroup, PermissionGroup}; use common_utils::pii; use masking::Secret; pub mod role; #[derive(Debug, serde::Serialize)] pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>); #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum AuthorizationInfo { Group(GroupInfo), GroupWithTag(ParentInfo), } // TODO: To be deprecated #[derive(Debug, serde::Serialize)] pub struct GroupInfo { pub group: PermissionGroup, pub description: &'static str, } #[derive(Debug, serde::Serialize, Clone)] pub struct ParentInfo { pub name: ParentGroup, pub description: &'static str, pub groups: Vec<PermissionGroup>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateUserRoleRequest { pub email: pii::Email, pub role_id: String, } #[derive(Debug, serde::Serialize)] pub enum UserStatus { Active, InvitationSent, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct DeleteUserRoleRequest { pub email: pii::Email, } #[derive(Debug, serde::Serialize)] pub struct ListUsersInEntityResponse { pub email: pii::Email, pub roles: Vec<role::MinimalRoleInfo>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ListInvitationForUserResponse { pub entity_id: String, pub entity_type: common_enums::EntityType, pub entity_name: Option<Secret<String>>, pub role_id: String, } pub type AcceptInvitationsV2Request = Vec<Entity>; pub type AcceptInvitationsPreAuthRequest = Vec<Entity>; #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct Entity { pub entity_id: String, pub entity_type: common_enums::EntityType, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ListUsersInEntityRequest { pub entity_type: Option<common_enums::EntityType>, }
crates/api_models/src/user_role.rs
api_models::src::user_role
445
true
// File: crates/api_models/src/files.rs // Module: api_models::src::files use utoipa::ToSchema; #[derive(Debug, serde::Serialize, ToSchema)] pub struct CreateFileResponse { /// ID of the file created pub file_id: String, } #[derive(Debug, serde::Serialize, ToSchema, Clone)] pub struct FileMetadataResponse { /// ID of the file created pub file_id: String, /// Name of the file pub file_name: Option<String>, /// Size of the file pub file_size: i32, /// Type of the file pub file_type: String, /// File availability pub available: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct FileRetrieveQuery { ///Dispute Id pub dispute_id: Option<String>, }
crates/api_models/src/files.rs
api_models::src::files
187
true
// File: crates/api_models/src/external_service_auth.rs // Module: api_models::src::external_service_auth use common_utils::{id_type, pii}; use masking::Secret; #[derive(Debug, serde::Serialize)] pub struct ExternalTokenResponse { pub token: Secret<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct ExternalVerifyTokenRequest { pub token: Secret<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct ExternalSignoutTokenRequest { pub token: Secret<String>, } #[derive(serde::Serialize, Debug)] #[serde(untagged)] pub enum ExternalVerifyTokenResponse { Hypersense { user_id: String, merchant_id: id_type::MerchantId, name: Secret<String>, email: pii::Email, }, } impl ExternalVerifyTokenResponse { pub fn get_user_id(&self) -> &str { match self { Self::Hypersense { user_id, .. } => user_id, } } }
crates/api_models/src/external_service_auth.rs
api_models::src::external_service_auth
220
true
// File: crates/api_models/src/process_tracker.rs // Module: api_models::src::process_tracker #[cfg(feature = "v2")] pub mod revenue_recovery;
crates/api_models/src/process_tracker.rs
api_models::src::process_tracker
35
true
// File: crates/api_models/src/verify_connector.rs // Module: api_models::src::verify_connector use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::{admin, enums}; #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyConnectorRequest { pub connector_name: enums::Connector, pub connector_account_details: admin::ConnectorAuthType, } common_utils::impl_api_event_type!(Miscellaneous, (VerifyConnectorRequest));
crates/api_models/src/verify_connector.rs
api_models::src::verify_connector
102
true
// File: crates/api_models/src/recon.rs // Module: api_models::src::recon use common_utils::{id_type, pii}; use masking::Secret; use crate::enums; #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ReconUpdateMerchantRequest { pub recon_status: enums::ReconStatus, pub user_email: pii::Email, } #[derive(Debug, serde::Serialize)] pub struct ReconTokenResponse { pub token: Secret<String>, } #[derive(Debug, serde::Serialize)] pub struct ReconStatusResponse { pub recon_status: enums::ReconStatus, } #[derive(serde::Serialize, Debug)] pub struct VerifyTokenResponse { pub merchant_id: id_type::MerchantId, pub user_email: pii::Email, #[serde(skip_serializing_if = "Option::is_none")] pub acl: Option<String>, }
crates/api_models/src/recon.rs
api_models::src::recon
187
true
// File: crates/api_models/src/poll.rs // Module: api_models::src::poll use common_utils::events::{ApiEventMetric, ApiEventsType}; use serde::Serialize; use utoipa::ToSchema; #[derive(Debug, ToSchema, Clone, Serialize)] pub struct PollResponse { /// The poll id pub poll_id: String, /// Status of the poll pub status: PollStatus, } #[derive(Debug, strum::Display, strum::EnumString, Clone, serde::Serialize, ToSchema)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PollStatus { Pending, Completed, NotFound, } impl ApiEventMetric for PollResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Poll { poll_id: self.poll_id.clone(), }) } }
crates/api_models/src/poll.rs
api_models::src::poll
198
true
// File: crates/api_models/src/webhooks.rs // Module: api_models::src::webhooks use common_utils::custom_serde; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; #[cfg(feature = "payouts")] use crate::payouts; use crate::{disputes, enums as api_enums, mandates, payments, refunds}; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Copy)] #[serde(rename_all = "snake_case")] pub enum IncomingWebhookEvent { /// Authorization + Capture failure PaymentIntentFailure, /// Authorization + Capture success PaymentIntentSuccess, PaymentIntentProcessing, PaymentIntentPartiallyFunded, PaymentIntentCancelled, PaymentIntentCancelFailure, PaymentIntentAuthorizationSuccess, PaymentIntentAuthorizationFailure, PaymentIntentExtendAuthorizationSuccess, PaymentIntentExtendAuthorizationFailure, PaymentIntentCaptureSuccess, PaymentIntentCaptureFailure, PaymentIntentExpired, PaymentActionRequired, EventNotSupported, SourceChargeable, SourceTransactionCreated, RefundFailure, RefundSuccess, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, MandateActive, MandateRevoked, EndpointVerification, ExternalAuthenticationARes, FrmApproved, FrmRejected, #[cfg(feature = "payouts")] PayoutSuccess, #[cfg(feature = "payouts")] PayoutFailure, #[cfg(feature = "payouts")] PayoutProcessing, #[cfg(feature = "payouts")] PayoutCancelled, #[cfg(feature = "payouts")] PayoutCreated, #[cfg(feature = "payouts")] PayoutExpired, #[cfg(feature = "payouts")] PayoutReversed, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentFailure, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentSuccess, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentPending, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryInvoiceCancel, SetupWebhook, InvoiceGenerated, } impl IncomingWebhookEvent { /// Convert UCS event type integer to IncomingWebhookEvent /// Maps from proto WebhookEventType enum values to IncomingWebhookEvent variants pub fn from_ucs_event_type(event_type: i32) -> Self { match event_type { 0 => Self::EventNotSupported, // Payment intent events 1 => Self::PaymentIntentFailure, 2 => Self::PaymentIntentSuccess, 3 => Self::PaymentIntentProcessing, 4 => Self::PaymentIntentPartiallyFunded, 5 => Self::PaymentIntentCancelled, 6 => Self::PaymentIntentCancelFailure, 7 => Self::PaymentIntentAuthorizationSuccess, 8 => Self::PaymentIntentAuthorizationFailure, 9 => Self::PaymentIntentCaptureSuccess, 10 => Self::PaymentIntentCaptureFailure, 11 => Self::PaymentIntentExpired, 12 => Self::PaymentActionRequired, // Source events 13 => Self::SourceChargeable, 14 => Self::SourceTransactionCreated, // Refund events 15 => Self::RefundFailure, 16 => Self::RefundSuccess, // Dispute events 17 => Self::DisputeOpened, 18 => Self::DisputeExpired, 19 => Self::DisputeAccepted, 20 => Self::DisputeCancelled, 21 => Self::DisputeChallenged, 22 => Self::DisputeWon, 23 => Self::DisputeLost, // Mandate events 24 => Self::MandateActive, 25 => Self::MandateRevoked, // Miscellaneous events 26 => Self::EndpointVerification, 27 => Self::ExternalAuthenticationARes, 28 => Self::FrmApproved, 29 => Self::FrmRejected, // Payout events #[cfg(feature = "payouts")] 30 => Self::PayoutSuccess, #[cfg(feature = "payouts")] 31 => Self::PayoutFailure, #[cfg(feature = "payouts")] 32 => Self::PayoutProcessing, #[cfg(feature = "payouts")] 33 => Self::PayoutCancelled, #[cfg(feature = "payouts")] 34 => Self::PayoutCreated, #[cfg(feature = "payouts")] 35 => Self::PayoutExpired, #[cfg(feature = "payouts")] 36 => Self::PayoutReversed, _ => Self::EventNotSupported, } } } pub enum WebhookFlow { Payment, #[cfg(feature = "payouts")] Payout, Refund, Dispute, Subscription, ReturnResponse, BankTransfer, Mandate, ExternalAuthentication, FraudCheck, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] Recovery, Setup, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] /// This enum tells about the affect a webhook had on an object pub enum WebhookResponseTracker { #[cfg(feature = "v1")] Payment { payment_id: common_utils::id_type::PaymentId, status: common_enums::IntentStatus, }, #[cfg(feature = "v2")] Payment { payment_id: common_utils::id_type::GlobalPaymentId, status: common_enums::IntentStatus, }, #[cfg(feature = "payouts")] Payout { payout_id: common_utils::id_type::PayoutId, status: common_enums::PayoutStatus, }, #[cfg(feature = "v1")] Refund { payment_id: common_utils::id_type::PaymentId, refund_id: String, status: common_enums::RefundStatus, }, #[cfg(feature = "v2")] Refund { payment_id: common_utils::id_type::GlobalPaymentId, refund_id: String, status: common_enums::RefundStatus, }, #[cfg(feature = "v1")] Dispute { dispute_id: String, payment_id: common_utils::id_type::PaymentId, status: common_enums::DisputeStatus, }, #[cfg(feature = "v2")] Dispute { dispute_id: String, payment_id: common_utils::id_type::GlobalPaymentId, status: common_enums::DisputeStatus, }, Mandate { mandate_id: String, status: common_enums::MandateStatus, }, #[cfg(feature = "v1")] PaymentMethod { payment_method_id: String, status: common_enums::PaymentMethodStatus, }, NoEffect, Relay { relay_id: common_utils::id_type::RelayId, status: common_enums::RelayStatus, }, } impl WebhookResponseTracker { #[cfg(feature = "v1")] pub fn get_payment_id(&self) -> Option<common_utils::id_type::PaymentId> { match self { Self::Payment { payment_id, .. } | Self::Refund { payment_id, .. } | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()), Self::NoEffect | Self::Mandate { .. } | Self::PaymentMethod { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, Self::Relay { .. } => None, } } #[cfg(feature = "v1")] pub fn get_payment_method_id(&self) -> Option<String> { match self { Self::PaymentMethod { payment_method_id, .. } => Some(payment_method_id.to_owned()), Self::Payment { .. } | Self::Refund { .. } | Self::Dispute { .. } | Self::NoEffect | Self::Mandate { .. } | Self::Relay { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, } } #[cfg(feature = "v2")] pub fn get_payment_id(&self) -> Option<common_utils::id_type::GlobalPaymentId> { match self { Self::Payment { payment_id, .. } | Self::Refund { payment_id, .. } | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()), Self::NoEffect | Self::Mandate { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, Self::Relay { .. } => None, } } } impl From<IncomingWebhookEvent> for WebhookFlow { fn from(evt: IncomingWebhookEvent) -> Self { match evt { IncomingWebhookEvent::PaymentIntentFailure | IncomingWebhookEvent::PaymentIntentSuccess | IncomingWebhookEvent::PaymentIntentProcessing | IncomingWebhookEvent::PaymentActionRequired | IncomingWebhookEvent::PaymentIntentPartiallyFunded | IncomingWebhookEvent::PaymentIntentCancelled | IncomingWebhookEvent::PaymentIntentCancelFailure | IncomingWebhookEvent::PaymentIntentAuthorizationSuccess | IncomingWebhookEvent::PaymentIntentAuthorizationFailure | IncomingWebhookEvent::PaymentIntentCaptureSuccess | IncomingWebhookEvent::PaymentIntentCaptureFailure | IncomingWebhookEvent::PaymentIntentExpired | IncomingWebhookEvent::PaymentIntentExtendAuthorizationSuccess | IncomingWebhookEvent::PaymentIntentExtendAuthorizationFailure => Self::Payment, IncomingWebhookEvent::EventNotSupported => Self::ReturnResponse, IncomingWebhookEvent::RefundSuccess | IncomingWebhookEvent::RefundFailure => { Self::Refund } IncomingWebhookEvent::MandateActive | IncomingWebhookEvent::MandateRevoked => { Self::Mandate } IncomingWebhookEvent::DisputeOpened | IncomingWebhookEvent::DisputeAccepted | IncomingWebhookEvent::DisputeExpired | IncomingWebhookEvent::DisputeCancelled | IncomingWebhookEvent::DisputeChallenged | IncomingWebhookEvent::DisputeWon | IncomingWebhookEvent::DisputeLost => Self::Dispute, IncomingWebhookEvent::EndpointVerification => Self::ReturnResponse, IncomingWebhookEvent::SourceChargeable | IncomingWebhookEvent::SourceTransactionCreated => Self::BankTransfer, IncomingWebhookEvent::ExternalAuthenticationARes => Self::ExternalAuthentication, IncomingWebhookEvent::FrmApproved | IncomingWebhookEvent::FrmRejected => { Self::FraudCheck } #[cfg(feature = "payouts")] IncomingWebhookEvent::PayoutSuccess | IncomingWebhookEvent::PayoutFailure | IncomingWebhookEvent::PayoutProcessing | IncomingWebhookEvent::PayoutCancelled | IncomingWebhookEvent::PayoutCreated | IncomingWebhookEvent::PayoutExpired | IncomingWebhookEvent::PayoutReversed => Self::Payout, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] IncomingWebhookEvent::RecoveryInvoiceCancel | IncomingWebhookEvent::RecoveryPaymentFailure | IncomingWebhookEvent::RecoveryPaymentPending | IncomingWebhookEvent::RecoveryPaymentSuccess => Self::Recovery, IncomingWebhookEvent::SetupWebhook => Self::Setup, IncomingWebhookEvent::InvoiceGenerated => Self::Subscription, } } } pub type MerchantWebhookConfig = std::collections::HashSet<IncomingWebhookEvent>; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum RefundIdType { RefundId(String), ConnectorRefundId(String), } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum MandateIdType { MandateId(String), ConnectorMandateId(String), } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum AuthenticationIdType { AuthenticationId(common_utils::id_type::AuthenticationId), ConnectorAuthenticationId(String), } #[cfg(feature = "payouts")] #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum PayoutIdType { PayoutAttemptId(String), ConnectorPayoutId(String), } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum ObjectReferenceId { PaymentId(payments::PaymentIdType), RefundId(RefundIdType), MandateId(MandateIdType), ExternalAuthenticationID(AuthenticationIdType), #[cfg(feature = "payouts")] PayoutId(PayoutIdType), #[cfg(all(feature = "revenue_recovery", feature = "v2"))] InvoiceId(InvoiceIdType), SubscriptionId(common_utils::id_type::SubscriptionId), } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum InvoiceIdType { ConnectorInvoiceId(String), } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl ObjectReferenceId { pub fn get_connector_transaction_id_as_string( self, ) -> Result<String, common_utils::errors::ValidationError> { match self { Self::PaymentId( payments::PaymentIdType::ConnectorTransactionId(id) ) => Ok(id), Self::PaymentId(_)=>Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "ConnectorTransactionId variant of PaymentId is required but received otherr variant", }, ), Self::RefundId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received RefundId", }, ), Self::MandateId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received MandateId", }, ), Self::ExternalAuthenticationID(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received ExternalAuthenticationID", }, ), #[cfg(feature = "payouts")] Self::PayoutId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received PayoutId", }, ), Self::InvoiceId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received InvoiceId", }, ), Self::SubscriptionId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received SubscriptionId", }, ), } } } pub struct IncomingWebhookDetails { pub object_reference_id: ObjectReferenceId, pub resource_object: Vec<u8>, } #[derive(Debug, Serialize, ToSchema)] pub struct OutgoingWebhook { /// The merchant id of the merchant #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique event id for each webhook pub event_id: String, /// The type of event this webhook corresponds to. #[schema(value_type = EventType)] pub event_type: api_enums::EventType, /// This is specific to the flow, for ex: it will be `PaymentsResponse` for payments flow pub content: OutgoingWebhookContent, /// The time at which webhook was sent #[serde(default, with = "custom_serde::iso8601")] pub timestamp: PrimitiveDateTime, } #[derive(Debug, Clone, Serialize, ToSchema)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] #[cfg(feature = "v1")] pub enum OutgoingWebhookContent { #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")] PaymentDetails(Box<payments::PaymentsResponse>), #[schema(value_type = RefundResponse, title = "RefundResponse")] RefundDetails(Box<refunds::RefundResponse>), #[schema(value_type = DisputeResponse, title = "DisputeResponse")] DisputeDetails(Box<disputes::DisputeResponse>), #[schema(value_type = MandateResponse, title = "MandateResponse")] MandateDetails(Box<mandates::MandateResponse>), #[cfg(feature = "payouts")] #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")] PayoutDetails(Box<payouts::PayoutCreateResponse>), } #[derive(Debug, Clone, Serialize, ToSchema)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] #[cfg(feature = "v2")] pub enum OutgoingWebhookContent { #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")] PaymentDetails(Box<payments::PaymentsResponse>), #[schema(value_type = RefundResponse, title = "RefundResponse")] RefundDetails(Box<refunds::RefundResponse>), #[schema(value_type = DisputeResponse, title = "DisputeResponse")] DisputeDetails(Box<disputes::DisputeResponse>), #[schema(value_type = MandateResponse, title = "MandateResponse")] MandateDetails(Box<mandates::MandateResponse>), #[cfg(feature = "payouts")] #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")] PayoutDetails(Box<payouts::PayoutCreateResponse>), } #[derive(Debug, Clone, Serialize)] pub struct ConnectorWebhookSecrets { pub secret: Vec<u8>, pub additional_secret: Option<masking::Secret<String>>, } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl IncomingWebhookEvent { pub fn is_recovery_transaction_event(&self) -> bool { matches!( self, Self::RecoveryPaymentFailure | Self::RecoveryPaymentSuccess | Self::RecoveryPaymentPending ) } }
crates/api_models/src/webhooks.rs
api_models::src::webhooks
4,129
true
// File: crates/api_models/src/api_keys.rs // Module: api_models::src::api_keys use common_utils::custom_serde; use masking::StrongSecret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; /// The request body for creating an API Key. #[derive(Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct CreateApiKeyRequest { /// A unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// A description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// An expiration date for the API Key. Although we allow keys to never expire, we recommend /// rotating your keys once every 6 months. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, } /// The response body for creating an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct CreateApiKeyResponse { /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// The description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// The plaintext API Key used for server-side API access. Ensure you store the API Key /// securely as you will not be able to see it again. #[schema(value_type = String, max_length = 128)] pub api_key: StrongSecret<String>, /// The time at which the API Key was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The expiration date for the API Key. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, /* /// The date and time indicating when the API Key was last used. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_used: Option<PrimitiveDateTime>, */ } /// The response body for retrieving an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct RetrieveApiKeyResponse { /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// The description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// The first few characters of the plaintext API Key to help you identify it. #[schema(value_type = String, max_length = 64)] pub prefix: StrongSecret<String>, /// The time at which the API Key was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The expiration date for the API Key. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, /* /// The date and time indicating when the API Key was last used. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_used: Option<PrimitiveDateTime>, */ } /// The request body for updating an API Key. #[derive(Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct UpdateApiKeyRequest { /// A unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: Option<String>, /// A description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// An expiration date for the API Key. Although we allow keys to never expire, we recommend /// rotating your keys once every 6 months. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: Option<ApiKeyExpiration>, #[serde(skip_deserializing)] #[schema(value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, #[serde(skip_deserializing)] #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, } /// The response body for revoking an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct RevokeApiKeyResponse { /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// Indicates whether the API key was revoked or not. #[schema(example = "true")] pub revoked: bool, } /// The constraints that are applicable when listing API Keys associated with a merchant account. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct ListApiKeyConstraints { /// The maximum number of API Keys to include in the response. pub limit: Option<i64>, /// The number of API Keys to skip when retrieving the list of API keys. pub skip: Option<i64>, } /// The expiration date and time for an API Key. #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum ApiKeyExpiration { /// The API Key does not expire. #[serde(with = "never")] Never, /// The API Key expires at the specified date and time. #[serde(with = "custom_serde::iso8601")] DateTime(PrimitiveDateTime), } impl From<ApiKeyExpiration> for Option<PrimitiveDateTime> { fn from(expiration: ApiKeyExpiration) -> Self { match expiration { ApiKeyExpiration::Never => None, ApiKeyExpiration::DateTime(date_time) => Some(date_time), } } } impl From<Option<PrimitiveDateTime>> for ApiKeyExpiration { fn from(date_time: Option<PrimitiveDateTime>) -> Self { date_time.map_or(Self::Never, Self::DateTime) } } // This implementation is required as otherwise, `serde` would serialize and deserialize // `ApiKeyExpiration::Never` as `null`, which is not preferable. // Reference: https://github.com/serde-rs/serde/issues/1560#issuecomment-506915291 mod never { const NEVER: &str = "never"; pub fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(NEVER) } pub fn deserialize<'de, D>(deserializer: D) -> Result<(), D::Error> where D: serde::Deserializer<'de>, { struct NeverVisitor; impl serde::de::Visitor<'_> for NeverVisitor { type Value = (); fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, r#""{NEVER}""#) } fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> { if value == NEVER { Ok(()) } else { Err(E::invalid_value(serde::de::Unexpected::Str(value), &self)) } } } deserializer.deserialize_str(NeverVisitor) } } impl<'a> ToSchema<'a> for ApiKeyExpiration { fn schema() -> ( &'a str, utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>, ) { use utoipa::openapi::{KnownFormat, ObjectBuilder, OneOfBuilder, SchemaFormat, SchemaType}; ( "ApiKeyExpiration", OneOfBuilder::new() .item( ObjectBuilder::new() .schema_type(SchemaType::String) .enum_values(Some(["never"])), ) .item( ObjectBuilder::new() .schema_type(SchemaType::String) .format(Some(SchemaFormat::KnownFormat(KnownFormat::DateTime))), ) .into(), ) } } #[cfg(test)] mod api_key_expiration_tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_serialization() { assert_eq!( serde_json::to_string(&ApiKeyExpiration::Never).unwrap(), r#""never""# ); let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap(); let time = time::Time::from_hms(11, 12, 13).unwrap(); assert_eq!( serde_json::to_string(&ApiKeyExpiration::DateTime(PrimitiveDateTime::new( date, time ))) .unwrap(), r#""2022-09-10T11:12:13.000Z""# ); } #[test] fn test_deserialization() { assert_eq!( serde_json::from_str::<ApiKeyExpiration>(r#""never""#).unwrap(), ApiKeyExpiration::Never ); let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap(); let time = time::Time::from_hms(11, 12, 13).unwrap(); assert_eq!( serde_json::from_str::<ApiKeyExpiration>(r#""2022-09-10T11:12:13.000Z""#).unwrap(), ApiKeyExpiration::DateTime(PrimitiveDateTime::new(date, time)) ); } #[test] fn test_null() { let result = serde_json::from_str::<ApiKeyExpiration>("null"); assert!(result.is_err()); let result = serde_json::from_str::<Option<ApiKeyExpiration>>("null").unwrap(); assert_eq!(result, None); } }
crates/api_models/src/api_keys.rs
api_models::src::api_keys
2,788
true
// File: crates/api_models/src/analytics.rs // Module: api_models::src::analytics use std::collections::HashSet; pub use common_utils::types::TimeRange; use common_utils::{events::ApiEventMetric, pii::EmailStrategy, types::authentication::AuthInfo}; use masking::Secret; use self::{ active_payments::ActivePaymentsMetrics, api_event::{ApiEventDimensions, ApiEventMetrics}, auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetrics}, disputes::{DisputeDimensions, DisputeMetrics}, frm::{FrmDimensions, FrmMetrics}, payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics}, refunds::{RefundDimensions, RefundDistributions, RefundMetrics}, sdk_events::{SdkEventDimensions, SdkEventMetrics}, }; pub mod active_payments; pub mod api_event; pub mod auth_events; pub mod connector_events; pub mod disputes; pub mod frm; pub mod outgoing_webhook_event; pub mod payment_intents; pub mod payments; pub mod refunds; pub mod routing_events; pub mod sdk_events; pub mod search; #[derive(Debug, serde::Serialize)] pub struct NameDescription { pub name: String, pub desc: String, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetInfoResponse { pub metrics: Vec<NameDescription>, pub download_dimensions: Option<Vec<NameDescription>>, pub dimensions: Vec<NameDescription>, } #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] pub struct TimeSeries { pub granularity: Granularity, } #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] pub enum Granularity { #[serde(rename = "G_ONEMIN")] OneMin, #[serde(rename = "G_FIVEMIN")] FiveMin, #[serde(rename = "G_FIFTEENMIN")] FifteenMin, #[serde(rename = "G_THIRTYMIN")] ThirtyMin, #[serde(rename = "G_ONEHOUR")] OneHour, #[serde(rename = "G_ONEDAY")] OneDay, } pub trait ForexMetric { fn is_forex_metric(&self) -> bool; } #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct AnalyticsRequest { pub payment_intent: Option<GetPaymentIntentMetricRequest>, pub payment_attempt: Option<GetPaymentMetricRequest>, pub refund: Option<GetRefundMetricRequest>, pub dispute: Option<GetDisputeMetricRequest>, } impl AnalyticsRequest { pub fn requires_forex_functionality(&self) -> bool { self.payment_attempt .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .payment_intent .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .refund .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .dispute .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentDimensions>, #[serde(default)] pub filters: payments::PaymentFilters, pub metrics: HashSet<PaymentMetrics>, pub distribution: Option<PaymentDistributionBody>, #[serde(default)] pub delta: bool, } #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] pub enum QueryLimit { #[serde(rename = "TOP_5")] Top5, #[serde(rename = "TOP_10")] Top10, } #[allow(clippy::from_over_into)] impl Into<u64> for QueryLimit { fn into(self) -> u64 { match self { Self::Top5 => 5, Self::Top10 => 10, } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentDistributionBody { pub distribution_for: PaymentDistributions, pub distribution_cardinality: QueryLimit, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundDistributionBody { pub distribution_for: RefundDistributions, pub distribution_cardinality: QueryLimit, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ReportRequest { pub time_range: TimeRange, pub emails: Option<Vec<Secret<String, EmailStrategy>>>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GenerateReportRequest { pub request: ReportRequest, pub merchant_id: Option<common_utils::id_type::MerchantId>, pub auth: AuthInfo, pub email: Secret<String, EmailStrategy>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentIntentMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentIntentDimensions>, #[serde(default)] pub filters: payment_intents::PaymentIntentFilters, pub metrics: HashSet<PaymentIntentMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetRefundMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<RefundDimensions>, #[serde(default)] pub filters: refunds::RefundFilters, pub metrics: HashSet<RefundMetrics>, pub distribution: Option<RefundDistributionBody>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetFrmMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<FrmDimensions>, #[serde(default)] pub filters: frm::FrmFilters, pub metrics: HashSet<FrmMetrics>, #[serde(default)] pub delta: bool, } impl ApiEventMetric for GetFrmMetricRequest {} #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSdkEventMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<SdkEventDimensions>, #[serde(default)] pub filters: sdk_events::SdkEventFilters, pub metrics: HashSet<SdkEventMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetAuthEventMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<AuthEventDimensions>, #[serde(default)] pub filters: AuthEventFilters, #[serde(default)] pub metrics: HashSet<AuthEventMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetActivePaymentsMetricRequest { #[serde(default)] pub metrics: HashSet<ActivePaymentsMetrics>, pub time_range: TimeRange, } #[derive(Debug, serde::Serialize)] pub struct AnalyticsMetadata { pub current_time_range: TimeRange, } #[derive(Debug, serde::Serialize)] pub struct PaymentsAnalyticsMetadata { pub total_payment_processed_amount: Option<u64>, pub total_payment_processed_amount_in_usd: Option<u64>, pub total_payment_processed_amount_without_smart_retries: Option<u64>, pub total_payment_processed_amount_without_smart_retries_usd: Option<u64>, pub total_payment_processed_count: Option<u64>, pub total_payment_processed_count_without_smart_retries: Option<u64>, pub total_failure_reasons_count: Option<u64>, pub total_failure_reasons_count_without_smart_retries: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct PaymentIntentsAnalyticsMetadata { pub total_success_rate: Option<f64>, pub total_success_rate_without_smart_retries: Option<f64>, pub total_smart_retried_amount: Option<u64>, pub total_smart_retried_amount_without_smart_retries: Option<u64>, pub total_payment_processed_amount: Option<u64>, pub total_payment_processed_amount_without_smart_retries: Option<u64>, pub total_smart_retried_amount_in_usd: Option<u64>, pub total_smart_retried_amount_without_smart_retries_in_usd: Option<u64>, pub total_payment_processed_amount_in_usd: Option<u64>, pub total_payment_processed_amount_without_smart_retries_in_usd: Option<u64>, pub total_payment_processed_count: Option<u64>, pub total_payment_processed_count_without_smart_retries: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct RefundsAnalyticsMetadata { pub total_refund_success_rate: Option<f64>, pub total_refund_processed_amount: Option<u64>, pub total_refund_processed_amount_in_usd: Option<u64>, pub total_refund_processed_count: Option<u64>, pub total_refund_reason_count: Option<u64>, pub total_refund_error_message_count: Option<u64>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentFiltersResponse { pub query_data: Vec<FilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct FilterValue { pub dimension: PaymentDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentIntentFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentIntentDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentIntentFiltersResponse { pub query_data: Vec<PaymentIntentFilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentIntentFilterValue { pub dimension: PaymentIntentDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetRefundFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<RefundDimensions>, } #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct RefundFiltersResponse { pub query_data: Vec<RefundFilterValue>, } #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct RefundFilterValue { pub dimension: RefundDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetFrmFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<FrmDimensions>, } impl ApiEventMetric for GetFrmFilterRequest {} #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct FrmFiltersResponse { pub query_data: Vec<FrmFilterValue>, } impl ApiEventMetric for FrmFiltersResponse {} #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct FrmFilterValue { pub dimension: FrmDimensions, pub values: Vec<String>, } impl ApiEventMetric for FrmFilterValue {} #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSdkEventFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<SdkEventDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct SdkEventFiltersResponse { pub query_data: Vec<SdkEventFilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct SdkEventFilterValue { pub dimension: SdkEventDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Serialize)] pub struct DisputesAnalyticsMetadata { pub total_disputed_amount: Option<u64>, pub total_dispute_lost_amount: Option<u64>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct MetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [AnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentsMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [PaymentsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentIntentsMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [PaymentIntentsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundsMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [RefundsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct DisputesMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [DisputesAnalyticsMetadata; 1], } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetApiEventFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<ApiEventDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ApiEventFiltersResponse { pub query_data: Vec<ApiEventFilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ApiEventFilterValue { pub dimension: ApiEventDimensions, pub values: Vec<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetApiEventMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<ApiEventDimensions>, #[serde(default)] pub filters: api_event::ApiEventFilters, pub metrics: HashSet<ApiEventMetrics>, #[serde(default)] pub delta: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetDisputeFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<DisputeDimensions>, } #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DisputeFiltersResponse { pub query_data: Vec<DisputeFilterValue>, } #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DisputeFilterValue { pub dimension: DisputeDimensions, pub values: Vec<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetDisputeMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<DisputeDimensions>, #[serde(default)] pub filters: disputes::DisputeFilters, pub metrics: HashSet<DisputeMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, Default, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct SankeyResponse { pub count: i64, pub status: String, pub refunds_status: Option<String>, pub dispute_status: Option<String>, pub first_attempt: i64, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetAuthEventFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<AuthEventDimensions>, } #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthEventFiltersResponse { pub query_data: Vec<AuthEventFilterValue>, } #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthEventFilterValue { pub dimension: AuthEventDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthEventMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [AuthEventsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] pub struct AuthEventsAnalyticsMetadata { pub total_error_message_count: Option<u64>, }
crates/api_models/src/analytics.rs
api_models::src::analytics
3,994
true
// File: crates/api_models/src/errors.rs // Module: api_models::src::errors pub mod actix; pub mod types;
crates/api_models/src/errors.rs
api_models::src::errors
29
true
// File: crates/api_models/src/customers.rs // Module: api_models::src::customers use common_utils::{crypto, custom_serde, id_type, pii, types::Description}; use masking::Secret; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::payments; /// The customer details #[cfg(feature = "v1")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerRequest { /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")] #[serde(skip)] pub merchant_id: id_type::MerchantId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = Option<String>, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// Customer's tax registration ID #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerListRequest { /// Offset #[schema(example = 32)] pub offset: Option<u32>, /// Limit #[schema(example = 32)] pub limit: Option<u16>, pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerListRequestWithConstraints { /// Offset #[schema(example = 32)] pub offset: Option<u32>, /// Limit #[schema(example = 32)] pub limit: Option<u16>, /// Unique identifier for a customer pub customer_id: Option<id_type::CustomerId>, /// Filter with created time range #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, } #[cfg(feature = "v1")] impl CustomerRequest { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { Some( self.customer_id .to_owned() .unwrap_or_else(common_utils::generate_customer_id_of_default_length), ) } pub fn get_address(&self) -> Option<payments::AddressDetails> { self.address.clone() } pub fn get_optional_email(&self) -> Option<pii::Email> { self.email.clone() } } /// The customer details #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerRequest { /// The merchant identifier for the customer object. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = String, example = "Jon Test")] pub name: Secret<String>, /// The customer's email address #[schema(value_type = String, max_length = 255, example = "JonTest@test.com")] pub email: pii::Email, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v2")] impl CustomerRequest { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { self.merchant_reference_id.clone() } pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> { self.default_billing_address.clone() } pub fn get_default_customer_shipping_address(&self) -> Option<payments::AddressDetails> { self.default_shipping_address.clone() } pub fn get_optional_email(&self) -> Option<pii::Email> { Some(self.email.clone()) } } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct CustomerResponse { /// The identifier for the customer object #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: crypto::OptionalEncryptableName, /// The customer's email address #[schema(value_type = Option<String>,max_length = 255, example = "JonTest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// The customer's phone number #[schema(value_type = Option<String>,max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// A timestamp (ISO 8601 code) that determines when the customer was created #[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")] #[serde(with = "custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The identifier for the default payment method. #[schema(max_length = 64, example = "pm_djh2837dwduh890123")] pub default_payment_method_id: Option<String>, /// The customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: crypto::OptionalEncryptableSecretString, } #[cfg(feature = "v1")] impl CustomerResponse { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { Some(self.customer_id.clone()) } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct CustomerResponse { /// Unique identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub id: id_type::GlobalCustomerId, /// The identifier for the customer object #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// Connector specific customer reference ids #[schema(value_type = Option<Object>, example = json!({"mca_hwySG2NtpzX0qr7toOy8": "cus_Rnm2pDKGyQi506"}))] pub connector_customer_ids: Option<common_types::customers::ConnectorCustomerMap>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: crypto::OptionalEncryptableName, /// The customer's email address #[schema(value_type = Option<String> ,max_length = 255, example = "JonTest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// The customer's phone number #[schema(value_type = Option<String>,max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// A timestamp (ISO 8601 code) that determines when the customer was created #[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")] #[serde(with = "custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The identifier for the default payment method. #[schema(value_type = Option<String>, max_length = 64, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// The customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: crypto::OptionalEncryptableSecretString, } #[cfg(feature = "v2")] impl CustomerResponse { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { self.merchant_reference_id.clone() } } #[cfg(feature = "v1")] #[derive(Debug, Deserialize, Serialize, ToSchema)] pub struct CustomerDeleteResponse { /// The identifier for the customer object #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// Whether customer was deleted or not #[schema(example = false)] pub customer_deleted: bool, /// Whether address was deleted or not #[schema(example = false)] pub address_deleted: bool, /// Whether payment methods deleted or not #[schema(example = false)] pub payment_methods_deleted: bool, } #[cfg(feature = "v2")] #[derive(Debug, Deserialize, Serialize, ToSchema)] pub struct CustomerDeleteResponse { /// Unique identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub id: id_type::GlobalCustomerId, /// The identifier for the customer object #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// Whether customer was deleted or not #[schema(example = false)] pub customer_deleted: bool, /// Whether address was deleted or not #[schema(example = false)] pub address_deleted: bool, /// Whether payment methods deleted or not #[schema(example = false)] pub payment_methods_deleted: bool, } /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[cfg(feature = "v1")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerUpdateRequest { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")] #[serde(skip)] pub merchant_id: id_type::MerchantId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = Option<String>, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// Customer's tax registration ID #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v1")] impl CustomerUpdateRequest { pub fn get_address(&self) -> Option<payments::AddressDetails> { self.address.clone() } } #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerUpdateRequest { /// The customer's name #[schema(max_length = 255, value_type = String, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = String, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the payment method #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// The customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v2")] impl CustomerUpdateRequest { pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> { self.default_billing_address.clone() } pub fn get_default_customer_shipping_address(&self) -> Option<payments::AddressDetails> { self.default_shipping_address.clone() } } #[cfg(feature = "v1")] #[derive(Debug, Serialize)] pub struct CustomerUpdateRequestInternal { pub customer_id: id_type::CustomerId, pub request: CustomerUpdateRequest, } #[cfg(feature = "v2")] #[derive(Debug, Serialize)] pub struct CustomerUpdateRequestInternal { pub id: id_type::GlobalCustomerId, pub request: CustomerUpdateRequest, } #[derive(Debug, Serialize, ToSchema)] pub struct CustomerListResponse { /// List of customers pub data: Vec<CustomerResponse>, /// Total count of customers pub total_count: usize, }
crates/api_models/src/customers.rs
api_models::src::customers
4,831
true
// File: crates/api_models/src/gsm.rs // Module: api_models::src::gsm use utoipa::ToSchema; use crate::enums as api_enums; #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmCreateRequest { /// The connector through which payment has gone through #[schema(value_type = Connector)] pub connector: api_enums::Connector, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, /// status provided by the router pub status: String, /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] #[schema(value_type = GsmDecision)] pub decision: api_enums::GsmDecision, /// indicates if step_up retry is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub step_up_possible: bool, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to #[schema(value_type = Option<ErrorCategory>)] pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub clear_pan_possible: bool, /// Indicates the GSM feature associated with the request, /// such as retry mechanisms or other specific functionalities provided by the system. #[schema(value_type = Option<GsmFeature>)] pub feature: Option<api_enums::GsmFeature>, /// 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. #[schema(value_type = Option<GsmFeatureData>)] pub feature_data: Option<common_types::domain::GsmFeatureData>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmRetrieveRequest { /// The connector through which payment has gone through #[schema(value_type = Connector)] pub connector: api_enums::Connector, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmUpdateRequest { /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, /// status provided by the router pub status: Option<String>, /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] #[schema(value_type = Option<GsmDecision>)] pub decision: Option<api_enums::GsmDecision>, /// indicates if step_up retry is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub step_up_possible: Option<bool>, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to #[schema(value_type = Option<ErrorCategory>)] pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub clear_pan_possible: Option<bool>, /// Indicates the GSM feature associated with the request, /// such as retry mechanisms or other specific functionalities provided by the system. #[schema(value_type = Option<GsmFeature>)] pub feature: Option<api_enums::GsmFeature>, /// 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. #[schema(value_type = Option<GsmFeatureData>)] pub feature_data: Option<common_types::domain::GsmFeatureData>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmDeleteRequest { /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct GsmDeleteResponse { pub gsm_rule_delete: bool, /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, } #[derive(serde::Serialize, Debug, ToSchema)] pub struct GsmResponse { /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, /// status provided by the router pub status: String, /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] #[schema(value_type = GsmDecision)] pub decision: api_enums::GsmDecision, /// indicates if step_up retry is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub step_up_possible: bool, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to #[schema(value_type = Option<ErrorCategory>)] pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub clear_pan_possible: bool, /// Indicates the GSM feature associated with the request, /// such as retry mechanisms or other specific functionalities provided by the system. #[schema(value_type = GsmFeature)] pub feature: api_enums::GsmFeature, /// 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. #[schema(value_type = GsmFeatureData)] pub feature_data: Option<common_types::domain::GsmFeatureData>, }
crates/api_models/src/gsm.rs
api_models::src::gsm
1,881
true
// File: crates/api_models/src/currency.rs // Module: api_models::src::currency use common_utils::{events::ApiEventMetric, types::MinorUnit}; /// QueryParams to be send to convert the amount -> from_currency -> to_currency #[derive(Debug, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct CurrencyConversionParams { pub amount: MinorUnit, pub to_currency: String, pub from_currency: String, } /// Response to be send for convert currency route #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct CurrencyConversionResponse { pub converted_amount: String, pub currency: String, } impl ApiEventMetric for CurrencyConversionResponse {} impl ApiEventMetric for CurrencyConversionParams {}
crates/api_models/src/currency.rs
api_models::src::currency
167
true
// File: crates/api_models/src/profile_acquirer.rs // Module: api_models::src::profile_acquirer use serde::{Deserialize, Serialize}; use utoipa::ToSchema; #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct ProfileAcquirerCreate { /// 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::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= f64,example = 0.01)] pub acquirer_fraud_rate: f64, /// Parent profile id to link the acquirer account with #[schema(value_type= String,example = "pro_ky0yNyOXXlA5hF8JzE5q")] pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Serialize, Deserialize, ToSchema, Clone)] pub struct ProfileAcquirerResponse { /// The unique identifier of the profile acquirer #[schema(value_type= String,example = "pro_acq_LCRdERuylQvNQ4qh3QE0")] pub profile_acquirer_id: common_utils::id_type::ProfileAcquirerId, /// 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::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= f64,example = 0.01)] pub acquirer_fraud_rate: f64, /// Parent profile id to link the acquirer account with #[schema(value_type= String,example = "pro_ky0yNyOXXlA5hF8JzE5q")] pub profile_id: common_utils::id_type::ProfileId, } impl common_utils::events::ApiEventMetric for ProfileAcquirerCreate {} impl common_utils::events::ApiEventMetric for ProfileAcquirerResponse {} impl From<( common_utils::id_type::ProfileAcquirerId, &common_utils::id_type::ProfileId, &common_types::domain::AcquirerConfig, )> for ProfileAcquirerResponse { fn from( (profile_acquirer_id, profile_id, acquirer_config): ( common_utils::id_type::ProfileAcquirerId, &common_utils::id_type::ProfileId, &common_types::domain::AcquirerConfig, ), ) -> Self { Self { profile_acquirer_id, profile_id: profile_id.clone(), acquirer_assigned_merchant_id: acquirer_config.acquirer_assigned_merchant_id.clone(), merchant_name: acquirer_config.merchant_name.clone(), network: acquirer_config.network.clone(), acquirer_bin: acquirer_config.acquirer_bin.clone(), acquirer_ica: acquirer_config.acquirer_ica.clone(), acquirer_fraud_rate: acquirer_config.acquirer_fraud_rate, } } } #[derive(Debug, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProfileAcquirerUpdate { #[schema(value_type = Option<String>, example = "M987654321")] pub acquirer_assigned_merchant_id: Option<String>, #[schema(value_type = Option<String>, example = "Updated Retailer Name")] pub merchant_name: Option<String>, #[schema(value_type = Option<String>, example = "MASTERCARD")] pub network: Option<common_enums::enums::CardNetwork>, #[schema(value_type = Option<String>, example = "987654")] pub acquirer_bin: Option<String>, #[schema(value_type = Option<String>, example = "501299")] pub acquirer_ica: Option<String>, #[schema(value_type = Option<f64>, example = "0.02")] pub acquirer_fraud_rate: Option<f64>, } impl common_utils::events::ApiEventMetric for ProfileAcquirerUpdate {}
crates/api_models/src/profile_acquirer.rs
api_models::src::profile_acquirer
1,156
true