id
stringlengths 24
57
| type
stringclasses 1
value | granularity
stringclasses 4
values | content
stringlengths 8.08k
87.1k
| metadata
dict |
|---|---|---|---|---|
large_file_-8396163799211668835
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: test_utils
File: crates/test_utils/src/connector_auth.rs
</path>
<file>
use std::{collections::HashMap, env};
use masking::Secret;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ConnectorAuthentication {
pub aci: Option<BodyKey>,
#[cfg(not(feature = "payouts"))]
pub adyen: Option<BodyKey>,
#[cfg(feature = "payouts")]
pub adyenplatform: Option<HeaderKey>,
pub affirm: Option<HeaderKey>,
#[cfg(feature = "payouts")]
pub adyen: Option<SignatureKey>,
#[cfg(not(feature = "payouts"))]
pub adyen_uk: Option<BodyKey>,
#[cfg(feature = "payouts")]
pub adyen_uk: Option<SignatureKey>,
pub airwallex: Option<BodyKey>,
pub amazonpay: Option<BodyKey>,
pub archipel: Option<NoKey>,
pub authipay: Option<SignatureKey>,
pub authorizedotnet: Option<BodyKey>,
pub bambora: Option<BodyKey>,
pub bamboraapac: Option<HeaderKey>,
pub bankofamerica: Option<SignatureKey>,
pub barclaycard: Option<SignatureKey>,
pub billwerk: Option<HeaderKey>,
pub bitpay: Option<HeaderKey>,
pub blackhawknetwork: Option<HeaderKey>,
pub calida: Option<HeaderKey>,
pub bluesnap: Option<BodyKey>,
pub boku: Option<BodyKey>,
pub breadpay: Option<BodyKey>,
pub cardinal: Option<SignatureKey>,
pub cashtocode: Option<BodyKey>,
pub celero: Option<HeaderKey>,
pub chargebee: Option<HeaderKey>,
pub checkbook: Option<BodyKey>,
pub checkout: Option<SignatureKey>,
pub coinbase: Option<HeaderKey>,
pub coingate: Option<HeaderKey>,
pub cryptopay: Option<BodyKey>,
pub cybersource: Option<SignatureKey>,
pub datatrans: Option<HeaderKey>,
pub deutschebank: Option<SignatureKey>,
pub digitalvirgo: Option<HeaderKey>,
pub dlocal: Option<SignatureKey>,
#[cfg(feature = "dummy_connector")]
pub dummyconnector: Option<HeaderKey>,
pub dwolla: Option<HeaderKey>,
pub ebanx: Option<HeaderKey>,
pub elavon: Option<HeaderKey>,
pub facilitapay: Option<BodyKey>,
pub finix: Option<HeaderKey>,
pub fiserv: Option<SignatureKey>,
pub fiservemea: Option<HeaderKey>,
pub fiuu: Option<HeaderKey>,
pub flexiti: Option<HeaderKey>,
pub forte: Option<MultiAuthKey>,
pub getnet: Option<HeaderKey>,
pub gigadat: Option<SignatureKey>,
pub globalpay: Option<BodyKey>,
pub globepay: Option<BodyKey>,
pub gocardless: Option<HeaderKey>,
pub gpayments: Option<HeaderKey>,
pub helcim: Option<HeaderKey>,
pub hipay: Option<HeaderKey>,
pub hyperswitch_vault: Option<SignatureKey>,
pub hyperwallet: Option<BodyKey>,
pub iatapay: Option<SignatureKey>,
pub inespay: Option<HeaderKey>,
pub itaubank: Option<MultiAuthKey>,
pub jpmorgan: Option<BodyKey>,
pub juspaythreedsserver: Option<HeaderKey>,
pub katapult: Option<HeaderKey>,
pub loonio: Option<HeaderKey>,
pub mifinity: Option<HeaderKey>,
pub mollie: Option<BodyKey>,
pub moneris: Option<SignatureKey>,
pub mpgs: Option<HeaderKey>,
pub multisafepay: Option<HeaderKey>,
pub netcetera: Option<HeaderKey>,
pub nexinets: Option<BodyKey>,
pub nexixpay: Option<HeaderKey>,
pub nomupay: Option<BodyKey>,
pub noon: Option<SignatureKey>,
pub nordea: Option<SignatureKey>,
pub novalnet: Option<HeaderKey>,
pub nmi: Option<HeaderKey>,
pub nuvei: Option<SignatureKey>,
pub opayo: Option<HeaderKey>,
pub opennode: Option<HeaderKey>,
pub paybox: Option<HeaderKey>,
pub payeezy: Option<SignatureKey>,
pub payload: Option<CurrencyAuthKey>,
pub payme: Option<BodyKey>,
pub payone: Option<HeaderKey>,
pub paypal: Option<BodyKey>,
pub paysafe: Option<BodyKey>,
pub paystack: Option<HeaderKey>,
pub paytm: Option<HeaderKey>,
pub payu: Option<BodyKey>,
pub peachpayments: Option<HeaderKey>,
pub phonepe: Option<HeaderKey>,
pub placetopay: Option<BodyKey>,
pub plaid: Option<BodyKey>,
pub powertranz: Option<BodyKey>,
pub prophetpay: Option<HeaderKey>,
pub rapyd: Option<BodyKey>,
pub razorpay: Option<BodyKey>,
pub recurly: Option<HeaderKey>,
pub redsys: Option<HeaderKey>,
pub santander: Option<BodyKey>,
pub shift4: Option<HeaderKey>,
pub sift: Option<HeaderKey>,
pub silverflow: Option<SignatureKey>,
pub square: Option<BodyKey>,
pub stax: Option<HeaderKey>,
pub stripe: Option<HeaderKey>,
pub stripebilling: Option<HeaderKey>,
pub taxjar: Option<HeaderKey>,
pub tesouro: Option<HeaderKey>,
pub threedsecureio: Option<HeaderKey>,
pub thunes: Option<HeaderKey>,
pub tokenex: Option<BodyKey>,
pub tokenio: Option<HeaderKey>,
pub stripe_au: Option<HeaderKey>,
pub stripe_uk: Option<HeaderKey>,
pub trustpay: Option<SignatureKey>,
pub trustpayments: Option<HeaderKey>,
pub tsys: Option<SignatureKey>,
pub unified_authentication_service: Option<HeaderKey>,
pub vgs: Option<SignatureKey>,
pub volt: Option<HeaderKey>,
pub wellsfargo: Option<HeaderKey>,
// pub wellsfargopayout: Option<HeaderKey>,
pub wise: Option<BodyKey>,
pub worldpay: Option<BodyKey>,
pub worldpayvantiv: Option<HeaderKey>,
pub worldpayxml: Option<HeaderKey>,
pub xendit: Option<HeaderKey>,
pub worldline: Option<SignatureKey>,
pub zen: Option<HeaderKey>,
pub zsl: Option<BodyKey>,
pub automation_configs: Option<AutomationConfigs>,
pub users: Option<UsersConfigs>,
}
impl Default for ConnectorAuthentication {
fn default() -> Self {
Self::new()
}
}
#[allow(dead_code)]
impl ConnectorAuthentication {
/// # Panics
///
/// Will panic if `CONNECTOR_AUTH_FILE_PATH` env is not set
#[allow(clippy::expect_used)]
pub fn new() -> Self {
// Do `export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"`
// before running tests in shell
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.expect("Connector authentication file path not set");
toml::from_str(
&std::fs::read_to_string(path).expect("connector authentication config file not found"),
)
.expect("Failed to read connector authentication config file")
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct ConnectorAuthenticationMap(HashMap<String, ConnectorAuthType>);
impl Default for ConnectorAuthenticationMap {
fn default() -> Self {
Self::new()
}
}
// This is a temporary solution to avoid rust compiler from complaining about unused function
#[allow(dead_code)]
impl ConnectorAuthenticationMap {
pub fn inner(&self) -> &HashMap<String, ConnectorAuthType> {
&self.0
}
/// # Panics
///
/// Will panic if `CONNECTOR_AUTH_FILE_PATH` env is not set
#[allow(clippy::expect_used)]
pub fn new() -> Self {
// Do `export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"`
// before running tests in shell
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.expect("connector authentication file path not set");
// Read the file contents to a JsonString
let contents =
&std::fs::read_to_string(path).expect("Failed to read connector authentication file");
// Deserialize the JsonString to a HashMap
let auth_config: HashMap<String, toml::Value> =
toml::from_str(contents).expect("Failed to deserialize TOML file");
// auth_config contains the data in below given format:
// {
// "connector_name": Table(
// {
// "api_key": String(
// "API_Key",
// ),
// "api_secret": String(
// "Secret key",
// ),
// "key1": String(
// "key1",
// ),
// "key2": String(
// "key2",
// ),
// },
// ),
// "connector_name": Table(
// ...
// }
// auth_map refines and extracts required information
let auth_map = auth_config
.into_iter()
.map(|(connector_name, config)| {
let auth_type = match config {
toml::Value::Table(mut table) => {
if let Some(auth_key_map_value) = table.remove("auth_key_map") {
// This is a CurrencyAuthKey
if let toml::Value::Table(auth_key_map_table) = auth_key_map_value {
let mut parsed_auth_map = HashMap::new();
for (currency, val) in auth_key_map_table {
if let Ok(currency_enum) =
currency.parse::<common_enums::Currency>()
{
parsed_auth_map
.insert(currency_enum, Secret::new(val.to_string()));
}
}
ConnectorAuthType::CurrencyAuthKey {
auth_key_map: parsed_auth_map,
}
} else {
ConnectorAuthType::NoKey
}
} else {
match (
table.get("api_key"),
table.get("key1"),
table.get("api_secret"),
table.get("key2"),
) {
(Some(api_key), None, None, None) => ConnectorAuthType::HeaderKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
},
(Some(api_key), Some(key1), None, None) => {
ConnectorAuthType::BodyKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
}
}
(Some(api_key), Some(key1), Some(api_secret), None) => {
ConnectorAuthType::SignatureKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
api_secret: Secret::new(
api_secret.as_str().unwrap_or_default().to_string(),
),
}
}
(Some(api_key), Some(key1), Some(api_secret), Some(key2)) => {
ConnectorAuthType::MultiAuthKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
api_secret: Secret::new(
api_secret.as_str().unwrap_or_default().to_string(),
),
key2: Secret::new(
key2.as_str().unwrap_or_default().to_string(),
),
}
}
_ => ConnectorAuthType::NoKey,
}
}
}
_ => ConnectorAuthType::NoKey,
};
(connector_name, auth_type)
})
.collect();
Self(auth_map)
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct HeaderKey {
pub api_key: Secret<String>,
}
impl From<HeaderKey> for ConnectorAuthType {
fn from(key: HeaderKey) -> Self {
Self::HeaderKey {
api_key: key.api_key,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BodyKey {
pub api_key: Secret<String>,
pub key1: Secret<String>,
}
impl From<BodyKey> for ConnectorAuthType {
fn from(key: BodyKey) -> Self {
Self::BodyKey {
api_key: key.api_key,
key1: key.key1,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SignatureKey {
pub api_key: Secret<String>,
pub key1: Secret<String>,
pub api_secret: Secret<String>,
}
impl From<SignatureKey> for ConnectorAuthType {
fn from(key: SignatureKey) -> Self {
Self::SignatureKey {
api_key: key.api_key,
key1: key.key1,
api_secret: key.api_secret,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MultiAuthKey {
pub api_key: Secret<String>,
pub key1: Secret<String>,
pub api_secret: Secret<String>,
pub key2: Secret<String>,
}
impl From<MultiAuthKey> for ConnectorAuthType {
fn from(key: MultiAuthKey) -> Self {
Self::MultiAuthKey {
api_key: key.api_key,
key1: key.key1,
api_secret: key.api_secret,
key2: key.key2,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CurrencyAuthKey {
pub auth_key_map: HashMap<String, toml::Value>,
}
impl From<CurrencyAuthKey> for ConnectorAuthType {
fn from(key: CurrencyAuthKey) -> Self {
let mut auth_map = HashMap::new();
for (currency, auth_data) in key.auth_key_map {
if let Ok(currency_enum) = currency.parse::<common_enums::Currency>() {
auth_map.insert(currency_enum, Secret::new(auth_data.to_string()));
}
}
Self::CurrencyAuthKey {
auth_key_map: auth_map,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NoKey {}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AutomationConfigs {
pub hs_base_url: Option<String>,
pub hs_api_key: Option<String>,
pub hs_api_keys: Option<String>,
pub hs_webhook_url: Option<String>,
pub hs_test_env: Option<String>,
pub hs_test_browser: Option<String>,
pub chrome_profile_path: Option<String>,
pub firefox_profile_path: Option<String>,
pub pypl_email: Option<String>,
pub pypl_pass: Option<String>,
pub gmail_email: Option<String>,
pub gmail_pass: Option<String>,
pub clearpay_email: Option<String>,
pub clearpay_pass: Option<String>,
pub configs_url: Option<String>,
pub stripe_pub_key: Option<String>,
pub testcases_path: Option<String>,
pub bluesnap_gateway_merchant_id: Option<String>,
pub globalpay_gateway_merchant_id: Option<String>,
pub authorizedotnet_gateway_merchant_id: Option<String>,
pub run_minimum_steps: Option<bool>,
pub airwallex_merchant_name: Option<String>,
pub adyen_bancontact_username: Option<String>,
pub adyen_bancontact_pass: Option<String>,
}
#[derive(Default, Debug, Clone, serde::Deserialize)]
#[serde(tag = "auth_type")]
pub enum ConnectorAuthType {
HeaderKey {
api_key: Secret<String>,
},
BodyKey {
api_key: Secret<String>,
key1: Secret<String>,
},
SignatureKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
},
MultiAuthKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
key2: Secret<String>,
},
CurrencyAuthKey {
auth_key_map: HashMap<common_enums::Currency, Secret<String>>,
},
#[default]
NoKey,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UsersConfigs {
pub user_email: String,
pub user_password: String,
pub wrong_password: String,
pub user_base_email_for_signup: String,
pub user_domain_for_signup: String,
}
</file>
|
{
"crate": "test_utils",
"file": "crates/test_utils/src/connector_auth.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3687
}
|
large_file_-8841924901047842859
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: test_utils
File: crates/test_utils/src/newman_runner.rs
</path>
<file>
use std::{
env,
fs::{self, OpenOptions},
io::{self, Write},
path::Path,
process::{exit, Command},
};
use anyhow::{Context, Result};
use clap::{arg, command, Parser, ValueEnum};
use masking::PeekInterface;
use regex::Regex;
use crate::connector_auth::{
ConnectorAuthType, ConnectorAuthentication, ConnectorAuthenticationMap,
};
#[derive(ValueEnum, Clone, Copy)]
pub enum Module {
Connector,
Users,
}
#[derive(Parser)]
#[command(version, about = "Postman collection runner using newman!", long_about = None)]
pub struct Args {
/// Admin API Key of the environment
#[arg(short, long)]
admin_api_key: String,
/// Base URL of the Hyperswitch environment
#[arg(short, long)]
base_url: String,
/// Name of the connector
#[arg(short, long)]
connector_name: Option<String>,
/// Name of the module
#[arg(short, long)]
module_name: Option<Module>,
/// Custom headers
#[arg(short = 'H', long = "header")]
custom_headers: Option<Vec<String>>,
/// Minimum delay in milliseconds to be added before sending a request
/// By default, 7 milliseconds will be the delay
#[arg(short, long, default_value_t = 7)]
delay_request: u32,
/// Folder name of specific tests
#[arg(short, long = "folder")]
folders: Option<String>,
/// Optional Verbose logs
#[arg(short, long)]
verbose: bool,
}
impl Args {
/// Getter for the `module_name` field
pub fn get_module_name(&self) -> Option<Module> {
self.module_name
}
}
pub struct ReturnArgs {
pub newman_command: Command,
pub modified_file_paths: Vec<Option<String>>,
pub collection_path: String,
}
// Generates the name of the collection JSON file for the specified connector.
// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-json/stripe.postman_collection.json
#[inline]
fn get_collection_path(name: impl AsRef<str>) -> String {
format!(
"postman/collection-json/{}.postman_collection.json",
name.as_ref()
)
}
// Generates the name of the collection directory for the specified connector.
// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-dir/stripe
#[inline]
fn get_dir_path(name: impl AsRef<str>) -> String {
format!("postman/collection-dir/{}", name.as_ref())
}
// This function currently allows you to add only custom headers.
// In future, as we scale, this can be modified based on the need
fn insert_content<T, U>(dir: T, content_to_insert: U) -> io::Result<()>
where
T: AsRef<Path>,
U: AsRef<str>,
{
let file_name = "event.prerequest.js";
let file_path = dir.as_ref().join(file_name);
// Open the file in write mode or create it if it doesn't exist
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open(file_path)?;
write!(file, "{}", content_to_insert.as_ref())?;
Ok(())
}
// This function gives runner for connector or a module
pub fn generate_runner() -> Result<ReturnArgs> {
let args = Args::parse();
match args.get_module_name() {
Some(Module::Users) => generate_newman_command_for_users(),
Some(Module::Connector) => generate_newman_command_for_connector(),
// Running connector tests when no module is passed to keep the previous test behavior same
None => generate_newman_command_for_connector(),
}
}
pub fn generate_newman_command_for_users() -> Result<ReturnArgs> {
let args = Args::parse();
let base_url = args.base_url;
let admin_api_key = args.admin_api_key;
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.with_context(|| "connector authentication file path not set")?;
let authentication: ConnectorAuthentication = toml::from_str(
&fs::read_to_string(path)
.with_context(|| "connector authentication config file not found")?,
)
.with_context(|| "connector authentication file path not set")?;
let users_configs = authentication
.users
.with_context(|| "user configs not found in authentication file")?;
let collection_path = get_collection_path("users");
let mut newman_command = Command::new("newman");
newman_command.args(["run", &collection_path]);
newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]);
newman_command.args(["--env-var", &format!("baseUrl={base_url}")]);
newman_command.args([
"--env-var",
&format!("user_email={}", users_configs.user_email),
]);
newman_command.args([
"--env-var",
&format!(
"user_base_email_for_signup={}",
users_configs.user_base_email_for_signup
),
]);
newman_command.args([
"--env-var",
&format!(
"user_domain_for_signup={}",
users_configs.user_domain_for_signup
),
]);
newman_command.args([
"--env-var",
&format!("user_password={}", users_configs.user_password),
]);
newman_command.args([
"--env-var",
&format!("wrong_password={}", users_configs.wrong_password),
]);
newman_command.args([
"--delay-request",
format!("{}", &args.delay_request).as_str(),
]);
newman_command.arg("--color").arg("on");
if args.verbose {
newman_command.arg("--verbose");
}
Ok(ReturnArgs {
newman_command,
modified_file_paths: vec![],
collection_path,
})
}
pub fn generate_newman_command_for_connector() -> Result<ReturnArgs> {
let args = Args::parse();
let connector_name = args
.connector_name
.with_context(|| "invalid parameters: connector/module name not found in arguments")?;
let base_url = args.base_url;
let admin_api_key = args.admin_api_key;
let collection_path = get_collection_path(&connector_name);
let collection_dir_path = get_dir_path(&connector_name);
let auth_map = ConnectorAuthenticationMap::new();
let inner_map = auth_map.inner();
/*
Newman runner
Certificate keys are added through secrets in CI, so there's no need to explicitly pass it as arguments.
It can be overridden by explicitly passing certificates as arguments.
If the collection requires certificates (Stripe collection for example) during the merchant connector account create step,
then Stripe's certificates will be passed implicitly (for now).
If any other connector requires certificates to be passed, that has to be passed explicitly for now.
*/
let mut newman_command = Command::new("newman");
newman_command.args(["run", &collection_path]);
newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]);
newman_command.args(["--env-var", &format!("baseUrl={base_url}")]);
let custom_header_exist = check_for_custom_headers(args.custom_headers, &collection_dir_path);
// validation of connector is needed here as a work around to the limitation of the fork of newman that Hyperswitch uses
let (connector_name, modified_collection_file_paths) =
check_connector_for_dynamic_amount(&connector_name);
if let Some(auth_type) = inner_map.get(connector_name) {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
]);
}
ConnectorAuthType::BodyKey { api_key, key1 } => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
]);
}
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
"--env-var",
&format!("connector_api_secret={}", api_secret.peek()),
]);
}
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
key2,
api_secret,
} => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
"--env-var",
&format!("connector_key2={}", key2.peek()),
"--env-var",
&format!("connector_api_secret={}", api_secret.peek()),
]);
}
// Handle other ConnectorAuthType variants
_ => {
eprintln!("Invalid authentication type.");
}
}
} else {
eprintln!("Connector not found.");
}
// Add additional environment variables if present
if let Ok(gateway_merchant_id) = env::var("GATEWAY_MERCHANT_ID") {
newman_command.args([
"--env-var",
&format!("gateway_merchant_id={gateway_merchant_id}"),
]);
}
if let Ok(gpay_certificate) = env::var("GPAY_CERTIFICATE") {
newman_command.args(["--env-var", &format!("certificate={gpay_certificate}")]);
}
if let Ok(gpay_certificate_keys) = env::var("GPAY_CERTIFICATE_KEYS") {
newman_command.args([
"--env-var",
&format!("certificate_keys={gpay_certificate_keys}"),
]);
}
if let Ok(merchant_api_key) = env::var("MERCHANT_API_KEY") {
newman_command.args(["--env-var", &format!("merchant_api_key={merchant_api_key}")]);
}
newman_command.args([
"--delay-request",
format!("{}", &args.delay_request).as_str(),
]);
newman_command.arg("--color").arg("on");
// Add flags for running specific folders
if let Some(folders) = &args.folders {
let folder_names: Vec<String> = folders.split(',').map(|s| s.trim().to_string()).collect();
for folder_name in folder_names {
if !folder_name.contains("QuickStart") {
// This is a quick fix, "QuickStart" is intentional to have merchant account and API keys set up
// This will be replaced by a more robust and efficient account creation or reuse existing old account
newman_command.args(["--folder", "QuickStart"]);
}
newman_command.args(["--folder", &folder_name]);
}
}
if args.verbose {
newman_command.arg("--verbose");
}
Ok(ReturnArgs {
newman_command,
modified_file_paths: vec![modified_collection_file_paths, custom_header_exist],
collection_path,
})
}
pub fn check_for_custom_headers(headers: Option<Vec<String>>, path: &str) -> Option<String> {
if let Some(headers) = &headers {
for header in headers {
if let Some((key, value)) = header.split_once(':') {
let content_to_insert =
format!(r#"pm.request.headers.add({{key: "{key}", value: "{value}"}});"#);
if let Err(err) = insert_content(path, &content_to_insert) {
eprintln!("An error occurred while inserting the custom header: {err}");
}
} else {
eprintln!("Invalid header format: {header}");
}
}
return Some(format!("{path}/event.prerequest.js"));
}
None
}
// If the connector name exists in dynamic_amount_connectors,
// the corresponding collection is modified at runtime to remove double quotes
pub fn check_connector_for_dynamic_amount(connector_name: &str) -> (&str, Option<String>) {
let collection_dir_path = get_dir_path(connector_name);
let dynamic_amount_connectors = ["nmi", "powertranz"];
if dynamic_amount_connectors.contains(&connector_name) {
return remove_quotes_for_integer_values(connector_name).unwrap_or((connector_name, None));
}
/*
If connector name does not exist in dynamic_amount_connectors but we want to run it with custom headers,
since we're running from collections directly, we'll have to export the collection again and it is much simpler.
We could directly inject the custom-headers using regex, but it is not encouraged as it is hard
to determine the place of edit.
*/
export_collection(connector_name, collection_dir_path);
(connector_name, None)
}
/*
Existing issue with the fork of newman is that, it requires you to pass variables like `{{value}}` within
double quotes without which it fails to execute.
For integer values like `amount`, this is a bummer as it flags the value stating it is of type
string and not integer.
Refactoring is done in 2 steps:
- Export the collection to json (although the json will be up-to-date, we export it again for safety)
- Use regex to replace the values which removes double quotes from integer values
Ex: \"{{amount}}\" -> {{amount}}
*/
pub fn remove_quotes_for_integer_values(
connector_name: &str,
) -> Result<(&str, Option<String>), io::Error> {
let collection_path = get_collection_path(connector_name);
let collection_dir_path = get_dir_path(connector_name);
let values_to_replace = [
"amount",
"another_random_number",
"capture_amount",
"random_number",
"refund_amount",
];
export_collection(connector_name, collection_dir_path);
let mut contents = fs::read_to_string(&collection_path)?;
for value_to_replace in values_to_replace {
if let Ok(re) = Regex::new(&format!(
r#"\\"(?P<field>\{{\{{{value_to_replace}\}}\}})\\""#,
)) {
contents = re.replace_all(&contents, "$field").to_string();
} else {
eprintln!("Regex validation failed.");
}
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.open(&collection_path)?;
file.write_all(contents.as_bytes())?;
}
Ok((connector_name, Some(collection_path)))
}
pub fn export_collection(connector_name: &str, collection_dir_path: String) {
let collection_path = get_collection_path(connector_name);
let mut newman_command = Command::new("newman");
newman_command.args([
"dir-import".to_owned(),
collection_dir_path,
"-o".to_owned(),
collection_path.clone(),
]);
match newman_command.spawn().and_then(|mut child| child.wait()) {
Ok(exit_status) => {
if exit_status.success() {
println!("Conversion of collection from directory structure to json successful!");
} else {
eprintln!("Conversion of collection from directory structure to json failed!");
exit(exit_status.code().unwrap_or(1));
}
}
Err(err) => {
eprintln!("Failed to execute dir-import: {err:?}");
exit(1);
}
}
}
</file>
|
{
"crate": "test_utils",
"file": "crates/test_utils/src/newman_runner.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3313
}
|
large_file_-119254237565545271
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid_wasm
File: crates/euclid_wasm/src/lib.rs
</path>
<file>
#![allow(non_upper_case_globals)]
mod types;
mod utils;
use std::{
collections::{HashMap, HashSet},
str::FromStr,
sync::OnceLock,
};
use api_models::{
enums as api_model_enums, routing::ConnectorSelection,
surcharge_decision_configs::SurchargeDecisionConfigs,
};
use common_enums::RoutableConnectors;
use common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule;
use connector_configs::{
common_config::{ConnectorApiIntegrationPayload, DashboardRequestPayload},
connector,
};
use currency_conversion::{
conversion::convert as convert_currency, types as currency_conversion_types,
};
use euclid::{
backend::{inputs, interpreter::InterpreterBackend, EuclidBackend},
dssa::{self, analyzer, graph::CgraphExt, state_machine},
frontend::{
ast,
dir::{self, enums as dir_enums, EuclidDirFilter},
},
};
use strum::{EnumMessage, EnumProperty, VariantNames};
use wasm_bindgen::prelude::*;
use crate::utils::JsResultExt;
type JsResult = Result<JsValue, JsValue>;
use api_models::payment_methods::CountryCodeWithName;
#[cfg(feature = "payouts")]
use common_enums::PayoutStatus;
use common_enums::{
CountryAlpha2, DisputeStatus, EventClass, EventType, IntentStatus, MandateStatus,
MerchantCategoryCode, MerchantCategoryCodeWithName, RefundStatus,
};
use strum::IntoEnumIterator;
struct SeedData {
cgraph: hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>,
connectors: Vec<ast::ConnectorChoice>,
}
static SEED_DATA: OnceLock<SeedData> = OnceLock::new();
static SEED_FOREX: OnceLock<currency_conversion_types::ExchangeRates> = OnceLock::new();
/// This function can be used by the frontend to educate wasm about the forex rates data.
/// The input argument is a struct fields base_currency and conversion where later is all the conversions associated with the base_currency
/// to all different currencies present.
#[wasm_bindgen(js_name = setForexData)]
pub fn seed_forex(forex: JsValue) -> JsResult {
let forex: currency_conversion_types::ExchangeRates = serde_wasm_bindgen::from_value(forex)?;
SEED_FOREX
.set(forex)
.map_err(|_| "Forex has already been seeded".to_string())
.err_to_js()?;
Ok(JsValue::NULL)
}
/// This function can be used to perform currency_conversion on the input amount, from_currency,
/// to_currency which are all expected to be one of currencies we already have in our Currency
/// enum.
#[wasm_bindgen(js_name = convertCurrency)]
pub fn convert_forex_value(amount: i64, from_currency: JsValue, to_currency: JsValue) -> JsResult {
let forex_data = SEED_FOREX
.get()
.ok_or("Forex Data not seeded")
.err_to_js()?;
let from_currency: common_enums::Currency = serde_wasm_bindgen::from_value(from_currency)?;
let to_currency: common_enums::Currency = serde_wasm_bindgen::from_value(to_currency)?;
let converted_amount = convert_currency(forex_data, from_currency, to_currency, amount)
.map_err(|_| "conversion not possible for provided values")
.err_to_js()?;
Ok(serde_wasm_bindgen::to_value(&converted_amount)?)
}
/// This function can be used by the frontend to get all the two letter country codes
/// along with their country names.
#[wasm_bindgen(js_name=getTwoLetterCountryCode)]
pub fn get_two_letter_country_code() -> JsResult {
let country_code_with_name = CountryAlpha2::iter()
.map(|country_code| CountryCodeWithName {
code: country_code,
name: common_enums::Country::from_alpha2(country_code),
})
.collect::<Vec<_>>();
Ok(serde_wasm_bindgen::to_value(&country_code_with_name)?)
}
/// This function can be used by the frontend to get all the merchant category codes
/// along with their names.
#[wasm_bindgen(js_name=getMerchantCategoryCodeWithName)]
pub fn get_merchant_category_code_with_name() -> JsResult {
let merchant_category_codes_with_name = MerchantCategoryCode::iter()
.map(|mcc_value| MerchantCategoryCodeWithName {
code: mcc_value,
name: mcc_value.to_merchant_category_name(),
})
.collect::<Vec<_>>();
Ok(serde_wasm_bindgen::to_value(
&merchant_category_codes_with_name,
)?)
}
/// This function can be used by the frontend to provide the WASM with information about
/// all the merchant's connector accounts. The input argument is a vector of all the merchant's
/// connector accounts from the API.
#[cfg(feature = "v1")]
#[wasm_bindgen(js_name = seedKnowledgeGraph)]
pub fn seed_knowledge_graph(mcas: JsValue) -> JsResult {
let mcas: Vec<api_models::admin::MerchantConnectorResponse> =
serde_wasm_bindgen::from_value(mcas)?;
let connectors: Vec<ast::ConnectorChoice> = mcas
.iter()
.map(|mca| {
Ok::<_, strum::ParseError>(ast::ConnectorChoice {
connector: RoutableConnectors::from_str(&mca.connector_name)?,
})
})
.collect::<Result<_, _>>()
.map_err(|_| "invalid connector name received")
.err_to_js()?;
let pm_filter = kgraph_utils::types::PaymentMethodFilters(HashMap::new());
let config = kgraph_utils::types::CountryCurrencyFilter {
connector_configs: HashMap::new(),
default_configs: Some(pm_filter),
};
let mca_graph = kgraph_utils::mca::make_mca_graph(mcas, &config).err_to_js()?;
let analysis_graph = hyperswitch_constraint_graph::ConstraintGraph::combine(
&mca_graph,
&dssa::truth::ANALYSIS_GRAPH,
)
.err_to_js()?;
SEED_DATA
.set(SeedData {
cgraph: analysis_graph,
connectors,
})
.map_err(|_| "Knowledge Graph has been already seeded".to_string())
.err_to_js()?;
Ok(JsValue::NULL)
}
/// This function allows the frontend to get all the merchant's configured
/// connectors that are valid for a rule based on the conditions specified in
/// the rule
#[wasm_bindgen(js_name = getValidConnectorsForRule)]
pub fn get_valid_connectors_for_rule(rule: JsValue) -> JsResult {
let seed_data = SEED_DATA.get().ok_or("Data not seeded").err_to_js()?;
let rule: ast::Rule<ConnectorSelection> = serde_wasm_bindgen::from_value(rule)?;
let dir_rule = ast::lowering::lower_rule(rule).err_to_js()?;
let mut valid_connectors: Vec<(ast::ConnectorChoice, dir::DirValue)> = seed_data
.connectors
.iter()
.cloned()
.map(|choice| (choice.clone(), dir::DirValue::Connector(Box::new(choice))))
.collect();
let mut invalid_connectors: HashSet<ast::ConnectorChoice> = HashSet::new();
let mut ctx_manager = state_machine::RuleContextManager::new(&dir_rule, &[]);
let dummy_meta = HashMap::new();
// For every conjunctive context in the Rule, verify validity of all still-valid connectors
// using the knowledge graph
while let Some(ctx) = ctx_manager.advance_mut().err_to_js()? {
// Standalone conjunctive context analysis to ensure the context itself is valid before
// checking it against merchant's connectors
seed_data
.cgraph
.perform_context_analysis(
ctx,
&mut hyperswitch_constraint_graph::Memoization::new(),
None,
)
.err_to_js()?;
// Update conjunctive context and run analysis on all of merchant's connectors.
for (conn, choice) in &valid_connectors {
if invalid_connectors.contains(conn) {
continue;
}
let ctx_val = dssa::types::ContextValue::assertion(choice, &dummy_meta);
ctx.push(ctx_val);
let analysis_result = seed_data.cgraph.perform_context_analysis(
ctx,
&mut hyperswitch_constraint_graph::Memoization::new(),
None,
);
if analysis_result.is_err() {
invalid_connectors.insert(conn.clone());
}
ctx.pop();
}
}
valid_connectors.retain(|(k, _)| !invalid_connectors.contains(k));
let valid_connectors: Vec<ast::ConnectorChoice> =
valid_connectors.into_iter().map(|c| c.0).collect();
Ok(serde_wasm_bindgen::to_value(&valid_connectors)?)
}
#[wasm_bindgen(js_name = analyzeProgram)]
pub fn analyze_program(js_program: JsValue) -> JsResult {
let program: ast::Program<ConnectorSelection> = serde_wasm_bindgen::from_value(js_program)?;
analyzer::analyze(program, SEED_DATA.get().map(|sd| &sd.cgraph)).err_to_js()?;
Ok(JsValue::NULL)
}
#[wasm_bindgen(js_name = runProgram)]
pub fn run_program(program: JsValue, input: JsValue) -> JsResult {
let program: ast::Program<ConnectorSelection> = serde_wasm_bindgen::from_value(program)?;
let input: inputs::BackendInput = serde_wasm_bindgen::from_value(input)?;
let backend = InterpreterBackend::with_program(program).err_to_js()?;
let res: euclid::backend::BackendOutput<ConnectorSelection> =
backend.execute(input).err_to_js()?;
Ok(serde_wasm_bindgen::to_value(&res)?)
}
#[wasm_bindgen(js_name = getAllConnectors)]
pub fn get_all_connectors() -> JsResult {
Ok(serde_wasm_bindgen::to_value(RoutableConnectors::VARIANTS)?)
}
#[wasm_bindgen(js_name = getAllKeys)]
pub fn get_all_keys() -> JsResult {
let excluded_keys = [
"Connector",
// 3DS Decision Rule Keys should not be included in the payument routing keys
"issuer_name",
"issuer_country",
"customer_device_platform",
"customer_device_type",
"customer_device_display_size",
"acquirer_country",
"acquirer_fraud_rate",
];
let keys: Vec<&'static str> = dir::DirKeyKind::VARIANTS
.iter()
.copied()
.filter(|s| !excluded_keys.contains(s))
.collect();
Ok(serde_wasm_bindgen::to_value(&keys)?)
}
#[wasm_bindgen(js_name = getKeyType)]
pub fn get_key_type(key: &str) -> Result<String, String> {
let key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?;
let key_str = key.get_type().to_string();
Ok(key_str)
}
#[wasm_bindgen(js_name = getThreeDsKeys)]
pub fn get_three_ds_keys() -> JsResult {
let keys = <common_types::payments::ConditionalConfigs as EuclidDirFilter>::ALLOWED;
Ok(serde_wasm_bindgen::to_value(keys)?)
}
#[wasm_bindgen(js_name= getSurchargeKeys)]
pub fn get_surcharge_keys() -> JsResult {
let keys = <SurchargeDecisionConfigs as EuclidDirFilter>::ALLOWED;
Ok(serde_wasm_bindgen::to_value(keys)?)
}
#[wasm_bindgen(js_name= getThreeDsDecisionRuleKeys)]
pub fn get_three_ds_decision_rule_keys() -> JsResult {
let keys = <ThreeDSDecisionRule as EuclidDirFilter>::ALLOWED;
Ok(serde_wasm_bindgen::to_value(keys)?)
}
#[wasm_bindgen(js_name=parseToString)]
pub fn parser(val: String) -> String {
ron_parser::my_parse(val)
}
#[wasm_bindgen(js_name = getVariantValues)]
pub fn get_variant_values(key: &str) -> Result<JsValue, JsValue> {
let key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?;
let variants: &[&str] = match key {
dir::DirKeyKind::PaymentMethod => dir_enums::PaymentMethod::VARIANTS,
dir::DirKeyKind::CardType => dir_enums::CardType::VARIANTS,
dir::DirKeyKind::CardNetwork => dir_enums::CardNetwork::VARIANTS,
dir::DirKeyKind::PayLaterType => dir_enums::PayLaterType::VARIANTS,
dir::DirKeyKind::WalletType => dir_enums::WalletType::VARIANTS,
dir::DirKeyKind::BankRedirectType => dir_enums::BankRedirectType::VARIANTS,
dir::DirKeyKind::CryptoType => dir_enums::CryptoType::VARIANTS,
dir::DirKeyKind::RewardType => dir_enums::RewardType::VARIANTS,
dir::DirKeyKind::AuthenticationType => dir_enums::AuthenticationType::VARIANTS,
dir::DirKeyKind::CaptureMethod => dir_enums::CaptureMethod::VARIANTS,
dir::DirKeyKind::PaymentCurrency => dir_enums::PaymentCurrency::VARIANTS,
dir::DirKeyKind::BusinessCountry => dir_enums::Country::VARIANTS,
dir::DirKeyKind::BillingCountry => dir_enums::Country::VARIANTS,
dir::DirKeyKind::BankTransferType => dir_enums::BankTransferType::VARIANTS,
dir::DirKeyKind::UpiType => dir_enums::UpiType::VARIANTS,
dir::DirKeyKind::SetupFutureUsage => dir_enums::SetupFutureUsage::VARIANTS,
dir::DirKeyKind::PaymentType => dir_enums::PaymentType::VARIANTS,
dir::DirKeyKind::MandateType => dir_enums::MandateType::VARIANTS,
dir::DirKeyKind::MandateAcceptanceType => dir_enums::MandateAcceptanceType::VARIANTS,
dir::DirKeyKind::CardRedirectType => dir_enums::CardRedirectType::VARIANTS,
dir::DirKeyKind::GiftCardType => dir_enums::GiftCardType::VARIANTS,
dir::DirKeyKind::VoucherType => dir_enums::VoucherType::VARIANTS,
dir::DirKeyKind::BankDebitType => dir_enums::BankDebitType::VARIANTS,
dir::DirKeyKind::RealTimePaymentType => dir_enums::RealTimePaymentType::VARIANTS,
dir::DirKeyKind::OpenBankingType => dir_enums::OpenBankingType::VARIANTS,
dir::DirKeyKind::MobilePaymentType => dir_enums::MobilePaymentType::VARIANTS,
dir::DirKeyKind::IssuerCountry => dir_enums::Country::VARIANTS,
dir::DirKeyKind::AcquirerCountry => dir_enums::Country::VARIANTS,
dir::DirKeyKind::CustomerDeviceType => dir_enums::CustomerDeviceType::VARIANTS,
dir::DirKeyKind::CustomerDevicePlatform => dir_enums::CustomerDevicePlatform::VARIANTS,
dir::DirKeyKind::CustomerDeviceDisplaySize => {
dir_enums::CustomerDeviceDisplaySize::VARIANTS
}
dir::DirKeyKind::PaymentAmount
| dir::DirKeyKind::Connector
| dir::DirKeyKind::CardBin
| dir::DirKeyKind::BusinessLabel
| dir::DirKeyKind::MetaData
| dir::DirKeyKind::IssuerName
| dir::DirKeyKind::AcquirerFraudRate => Err("Key does not have variants".to_string())?,
};
Ok(serde_wasm_bindgen::to_value(variants)?)
}
#[wasm_bindgen(js_name = addTwo)]
pub fn add_two(n1: i64, n2: i64) -> i64 {
n1 + n2
}
#[wasm_bindgen(js_name = getDescriptionCategory)]
pub fn get_description_category() -> JsResult {
let keys = dir::DirKeyKind::VARIANTS
.iter()
.copied()
.filter(|s| s != &"Connector")
.collect::<Vec<&'static str>>();
let mut category: HashMap<Option<&str>, Vec<types::Details<'_>>> = HashMap::new();
for key in keys {
let dir_key =
dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?;
let details = types::Details {
description: dir_key.get_detailed_message(),
kind: dir_key.clone(),
};
category
.entry(dir_key.get_str("Category"))
.and_modify(|val| val.push(details.clone()))
.or_insert(vec![details]);
}
Ok(serde_wasm_bindgen::to_value(&category)?)
}
#[wasm_bindgen(js_name = getConnectorConfig)]
pub fn get_connector_config(key: &str) -> JsResult {
let key = api_model_enums::Connector::from_str(key)
.map_err(|_| "Invalid key received".to_string())?;
let res = connector::ConnectorConfig::get_connector_config(key)?;
Ok(serde_wasm_bindgen::to_value(&res)?)
}
#[cfg(feature = "payouts")]
#[wasm_bindgen(js_name = getPayoutConnectorConfig)]
pub fn get_payout_connector_config(key: &str) -> JsResult {
let key = api_model_enums::PayoutConnectors::from_str(key)
.map_err(|_| "Invalid key received".to_string())?;
let res = connector::ConnectorConfig::get_payout_connector_config(key)?;
Ok(serde_wasm_bindgen::to_value(&res)?)
}
#[wasm_bindgen(js_name = getAuthenticationConnectorConfig)]
pub fn get_authentication_connector_config(key: &str) -> JsResult {
let key = api_model_enums::AuthenticationConnectors::from_str(key)
.map_err(|_| "Invalid key received".to_string())?;
let res = connector::ConnectorConfig::get_authentication_connector_config(key)?;
Ok(serde_wasm_bindgen::to_value(&res)?)
}
#[wasm_bindgen(js_name = getTaxProcessorConfig)]
pub fn get_tax_processor_config(key: &str) -> JsResult {
let key = api_model_enums::TaxConnectors::from_str(key)
.map_err(|_| "Invalid key received".to_string())?;
let res = connector::ConnectorConfig::get_tax_processor_config(key)?;
Ok(serde_wasm_bindgen::to_value(&res)?)
}
#[wasm_bindgen(js_name = getPMAuthenticationProcessorConfig)]
pub fn get_pm_authentication_processor_config(key: &str) -> JsResult {
let key: api_model_enums::PmAuthConnectors = api_model_enums::PmAuthConnectors::from_str(key)
.map_err(|_| "Invalid key received".to_string())?;
let res = connector::ConnectorConfig::get_pm_authentication_processor_config(key)?;
Ok(serde_wasm_bindgen::to_value(&res)?)
}
#[wasm_bindgen(js_name = getRequestPayload)]
pub fn get_request_payload(input: JsValue, response: JsValue) -> JsResult {
let input: DashboardRequestPayload = serde_wasm_bindgen::from_value(input)?;
let api_response: ConnectorApiIntegrationPayload = serde_wasm_bindgen::from_value(response)?;
let result = DashboardRequestPayload::create_connector_request(input, api_response);
Ok(serde_wasm_bindgen::to_value(&result)?)
}
#[wasm_bindgen(js_name = getResponsePayload)]
pub fn get_response_payload(input: JsValue) -> JsResult {
let input: ConnectorApiIntegrationPayload = serde_wasm_bindgen::from_value(input)?;
let result = ConnectorApiIntegrationPayload::get_transformed_response_payload(input);
Ok(serde_wasm_bindgen::to_value(&result)?)
}
#[cfg(feature = "payouts")]
#[wasm_bindgen(js_name = getAllPayoutKeys)]
pub fn get_all_payout_keys() -> JsResult {
let keys: Vec<&'static str> = dir::PayoutDirKeyKind::VARIANTS.to_vec();
Ok(serde_wasm_bindgen::to_value(&keys)?)
}
#[cfg(feature = "payouts")]
#[wasm_bindgen(js_name = getPayoutVariantValues)]
pub fn get_payout_variant_values(key: &str) -> Result<JsValue, JsValue> {
let key =
dir::PayoutDirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?;
let variants: &[&str] = match key {
dir::PayoutDirKeyKind::BusinessCountry => dir_enums::BusinessCountry::VARIANTS,
dir::PayoutDirKeyKind::BillingCountry => dir_enums::BillingCountry::VARIANTS,
dir::PayoutDirKeyKind::PayoutCurrency => dir_enums::PaymentCurrency::VARIANTS,
dir::PayoutDirKeyKind::PayoutType => dir_enums::PayoutType::VARIANTS,
dir::PayoutDirKeyKind::WalletType => dir_enums::PayoutWalletType::VARIANTS,
dir::PayoutDirKeyKind::BankTransferType => dir_enums::PayoutBankTransferType::VARIANTS,
dir::PayoutDirKeyKind::PayoutAmount | dir::PayoutDirKeyKind::BusinessLabel => {
Err("Key does not have variants".to_string())?
}
};
Ok(serde_wasm_bindgen::to_value(variants)?)
}
#[cfg(feature = "payouts")]
#[wasm_bindgen(js_name = getPayoutDescriptionCategory)]
pub fn get_payout_description_category() -> JsResult {
let keys = dir::PayoutDirKeyKind::VARIANTS.to_vec();
let mut category: HashMap<Option<&str>, Vec<types::PayoutDetails<'_>>> = HashMap::new();
for key in keys {
let dir_key =
dir::PayoutDirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?;
let details = types::PayoutDetails {
description: dir_key.get_detailed_message(),
kind: dir_key.clone(),
};
category
.entry(dir_key.get_str("Category"))
.and_modify(|val| val.push(details.clone()))
.or_insert(vec![details]);
}
Ok(serde_wasm_bindgen::to_value(&category)?)
}
#[wasm_bindgen(js_name = getValidWebhookStatus)]
pub fn get_valid_webhook_status(key: &str) -> JsResult {
let event_class = EventClass::from_str(key)
.map_err(|_| "Invalid webhook event type received".to_string())
.err_to_js()?;
match event_class {
EventClass::Payments => {
let statuses: Vec<IntentStatus> = IntentStatus::iter()
.filter(|intent_status| Into::<Option<EventType>>::into(*intent_status).is_some())
.collect();
Ok(serde_wasm_bindgen::to_value(&statuses)?)
}
EventClass::Refunds => {
let statuses: Vec<RefundStatus> = RefundStatus::iter()
.filter(|status| Into::<Option<EventType>>::into(*status).is_some())
.collect();
Ok(serde_wasm_bindgen::to_value(&statuses)?)
}
EventClass::Disputes => {
let statuses: Vec<DisputeStatus> = DisputeStatus::iter().collect();
Ok(serde_wasm_bindgen::to_value(&statuses)?)
}
EventClass::Mandates => {
let statuses: Vec<MandateStatus> = MandateStatus::iter()
.filter(|status| Into::<Option<EventType>>::into(*status).is_some())
.collect();
Ok(serde_wasm_bindgen::to_value(&statuses)?)
}
#[cfg(feature = "payouts")]
EventClass::Payouts => {
let statuses: Vec<PayoutStatus> = PayoutStatus::iter()
.filter(|status| Into::<Option<EventType>>::into(*status).is_some())
.collect();
Ok(serde_wasm_bindgen::to_value(&statuses)?)
}
}
}
</file>
|
{
"crate": "euclid_wasm",
"file": "crates/euclid_wasm/src/lib.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5342
}
|
large_file_2187565825058928599
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_types
File: crates/common_types/src/payment_methods.rs
</path>
<file>
//! Common types to be used in payment methods
use diesel::{
backend::Backend,
deserialize,
deserialize::FromSql,
serialize::ToSql,
sql_types::{Json, Jsonb},
AsExpression, Queryable,
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
/// Details of all the payment methods enabled for the connector for the given merchant account
// sql_type for this can be json instead of jsonb. This is because validation at database is not required since it will always be written by the application.
// This is a performance optimization to avoid json validation at database level.
// jsonb enables faster querying on json columns, but it doesn't justify here since we are not querying on this column.
// https://docs.rs/diesel/latest/diesel/sql_types/struct.Jsonb.html
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, AsExpression)]
#[serde(deny_unknown_fields)]
#[diesel(sql_type = Json)]
pub struct PaymentMethodsEnabled {
/// Type of payment method.
#[schema(value_type = PaymentMethod,example = "card")]
pub payment_method_type: common_enums::PaymentMethod,
/// Payment method configuration, this includes all the filters associated with the payment method
pub payment_method_subtypes: Option<Vec<RequestPaymentMethodTypes>>,
}
// Custom FromSql implementation to handle deserialization of v1 data format
impl FromSql<Json, diesel::pg::Pg> for PaymentMethodsEnabled {
fn from_sql(bytes: <diesel::pg::Pg as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
let helper: PaymentMethodsEnabledHelper = serde_json::from_slice(bytes.as_bytes())
.map_err(|e| Box::new(diesel::result::Error::DeserializationError(Box::new(e))))?;
Ok(helper.into())
}
}
// In this ToSql implementation, we are directly serializing the PaymentMethodsEnabled struct to JSON
impl ToSql<Json, diesel::pg::Pg> for PaymentMethodsEnabled {
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
let value = serde_json::to_value(self)?;
// the function `reborrow` only works in case of `Pg` backend. But, in case of other backends
// please refer to the diesel migration blog:
// https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations
<serde_json::Value as ToSql<Json, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow())
}
}
// Intermediate type to handle deserialization of v1 data format of PaymentMethodsEnabled
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum PaymentMethodsEnabledHelper {
V2 {
payment_method_type: common_enums::PaymentMethod,
payment_method_subtypes: Option<Vec<RequestPaymentMethodTypes>>,
},
V1 {
payment_method: common_enums::PaymentMethod,
payment_method_types: Option<Vec<RequestPaymentMethodTypesV1>>,
},
}
impl From<PaymentMethodsEnabledHelper> for PaymentMethodsEnabled {
fn from(helper: PaymentMethodsEnabledHelper) -> Self {
match helper {
PaymentMethodsEnabledHelper::V2 {
payment_method_type,
payment_method_subtypes,
} => Self {
payment_method_type,
payment_method_subtypes,
},
PaymentMethodsEnabledHelper::V1 {
payment_method,
payment_method_types,
} => Self {
payment_method_type: payment_method,
payment_method_subtypes: payment_method_types.map(|subtypes| {
subtypes
.into_iter()
.map(RequestPaymentMethodTypes::from)
.collect()
}),
},
}
}
}
impl PaymentMethodsEnabled {
/// Get payment_method_type
#[cfg(feature = "v2")]
pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
Some(self.payment_method_type)
}
/// Get payment_method_subtypes
#[cfg(feature = "v2")]
pub fn get_payment_method_type(&self) -> Option<&Vec<RequestPaymentMethodTypes>> {
self.payment_method_subtypes.as_ref()
}
}
/// Details of a specific payment method subtype enabled for the connector for the given merchant account
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, Hash)]
pub struct RequestPaymentMethodTypes {
/// The payment method subtype
#[schema(value_type = PaymentMethodType)]
pub payment_method_subtype: common_enums::PaymentMethodType,
/// The payment experience for the payment method
#[schema(value_type = Option<PaymentExperience>)]
pub payment_experience: Option<common_enums::PaymentExperience>,
/// List of cards networks that are enabled for this payment method, applicable for credit and debit payment method subtypes only
#[schema(value_type = Option<Vec<CardNetwork>>)]
pub card_networks: Option<Vec<common_enums::CardNetwork>>,
/// List of currencies accepted or has the processing capabilities of the processor
#[schema(example = json!(
{
"type": "enable_only",
"list": ["USD", "INR"]
}
), value_type = Option<AcceptedCurrencies>)]
pub accepted_currencies: Option<AcceptedCurrencies>,
/// List of Countries accepted or has the processing capabilities of the processor
#[schema(example = json!(
{
"type": "enable_only",
"list": ["UK", "AU"]
}
), value_type = Option<AcceptedCountries>)]
pub accepted_countries: Option<AcceptedCountries>,
/// Minimum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents)
#[schema(example = 1)]
pub minimum_amount: Option<common_utils::types::MinorUnit>,
/// Maximum amount supported by the processor. To be represented in the lowest denomination of
/// the target currency (For example, for USD it should be in cents)
#[schema(example = 1313)]
pub maximum_amount: Option<common_utils::types::MinorUnit>,
/// Indicates whether the payment method supports recurring payments. Optional.
#[schema(example = true)]
pub recurring_enabled: Option<bool>,
/// Indicates whether the payment method is eligible for installment payments (e.g., EMI, BNPL). Optional.
#[schema(example = true)]
pub installment_payment_enabled: Option<bool>,
}
impl From<RequestPaymentMethodTypesV1> for RequestPaymentMethodTypes {
fn from(value: RequestPaymentMethodTypesV1) -> Self {
Self {
payment_method_subtype: value.payment_method_type,
payment_experience: value.payment_experience,
card_networks: value.card_networks,
accepted_currencies: value.accepted_currencies,
accepted_countries: value.accepted_countries,
minimum_amount: value.minimum_amount,
maximum_amount: value.maximum_amount,
recurring_enabled: value.recurring_enabled,
installment_payment_enabled: value.installment_payment_enabled,
}
}
}
#[derive(serde::Deserialize)]
struct RequestPaymentMethodTypesV1 {
pub payment_method_type: common_enums::PaymentMethodType,
pub payment_experience: Option<common_enums::PaymentExperience>,
pub card_networks: Option<Vec<common_enums::CardNetwork>>,
pub accepted_currencies: Option<AcceptedCurrencies>,
pub accepted_countries: Option<AcceptedCountries>,
pub minimum_amount: Option<common_utils::types::MinorUnit>,
pub maximum_amount: Option<common_utils::types::MinorUnit>,
pub recurring_enabled: Option<bool>,
pub installment_payment_enabled: Option<bool>,
}
impl RequestPaymentMethodTypes {
///Get payment_method_subtype
pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethodType> {
Some(self.payment_method_subtype)
}
}
#[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)]
#[serde(
deny_unknown_fields,
tag = "type",
content = "list",
rename_all = "snake_case"
)]
/// Object to filter the countries for which the payment method subtype is enabled
pub enum AcceptedCountries {
/// Only enable the payment method subtype for specific countries
#[schema(value_type = Vec<CountryAlpha2>)]
EnableOnly(Vec<common_enums::CountryAlpha2>),
/// Only disable the payment method subtype for specific countries
#[schema(value_type = Vec<CountryAlpha2>)]
DisableOnly(Vec<common_enums::CountryAlpha2>),
/// Enable the payment method subtype for all countries, in which the processor has the processing capabilities
AllAccepted,
}
#[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)]
#[serde(
deny_unknown_fields,
tag = "type",
content = "list",
rename_all = "snake_case"
)]
/// Object to filter the countries for which the payment method subtype is enabled
pub enum AcceptedCurrencies {
/// Only enable the payment method subtype for specific currencies
#[schema(value_type = Vec<Currency>)]
EnableOnly(Vec<common_enums::Currency>),
/// Only disable the payment method subtype for specific currencies
#[schema(value_type = Vec<Currency>)]
DisableOnly(Vec<common_enums::Currency>),
/// Enable the payment method subtype for all currencies, in which the processor has the processing capabilities
AllAccepted,
}
impl<DB> Queryable<Jsonb, DB> for PaymentMethodsEnabled
where
DB: Backend,
Self: FromSql<Jsonb, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
/// The network tokenization configuration for creating the payment method session
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct NetworkTokenization {
/// Enable the network tokenization for payment methods that are created using the payment method session
#[schema(value_type = NetworkTokenizationToggle)]
pub enable: common_enums::NetworkTokenizationToggle,
}
/// The Payment Service Provider Configuration for payment methods that are created using the payment method session
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PspTokenization {
/// The tokenization type to be applied for the payment method
#[schema(value_type = TokenizationType)]
pub tokenization_type: common_enums::TokenizationType,
/// The merchant connector id to be used for tokenization
#[schema(value_type = String)]
pub connector_id: common_utils::id_type::MerchantConnectorAccountId,
}
</file>
|
{
"crate": "common_types",
"file": "crates/common_types/src/payment_methods.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2320
}
|
large_file_3984291810268987834
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_types
File: crates/common_types/src/payments.rs
</path>
<file>
//! Payment related types
use std::collections::HashMap;
use common_enums::enums;
use common_utils::{
date_time, errors, events, ext_traits::OptionExt, impl_to_sql_from_sql_json, pii,
types::MinorUnit,
};
use diesel::{
sql_types::{Jsonb, Text},
AsExpression, FromSqlRow,
};
use error_stack::{Report, Result, ResultExt};
use euclid::frontend::{
ast::Program,
dir::{DirKeyKind, EuclidDirFilter},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::domain::{AdyenSplitData, XenditSplitSubMerchantData};
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
/// Fee information for Split Payments to be charged on the payment being collected
pub enum SplitPaymentsRequest {
/// StripeSplitPayment
StripeSplitPayment(StripeSplitPaymentRequest),
/// AdyenSplitPayment
AdyenSplitPayment(AdyenSplitData),
/// XenditSplitPayment
XenditSplitPayment(XenditSplitRequest),
}
impl_to_sql_from_sql_json!(SplitPaymentsRequest);
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
/// Fee information for Split Payments to be charged on the payment being collected for Stripe
pub struct StripeSplitPaymentRequest {
/// Stripe's charge type
#[schema(value_type = PaymentChargeType, example = "direct")]
pub charge_type: enums::PaymentChargeType,
/// Platform fees to be collected on the payment
#[schema(value_type = i64, example = 6540)]
pub application_fees: Option<MinorUnit>,
/// Identifier for the reseller's account where the funds were transferred
pub transfer_account_id: String,
}
impl_to_sql_from_sql_json!(StripeSplitPaymentRequest);
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
/// Hashmap to store mca_id's with product names
pub struct AuthenticationConnectorAccountMap(
HashMap<enums::AuthenticationProduct, common_utils::id_type::MerchantConnectorAccountId>,
);
impl_to_sql_from_sql_json!(AuthenticationConnectorAccountMap);
impl AuthenticationConnectorAccountMap {
/// fn to get click to pay connector_account_id
pub fn get_click_to_pay_connector_account_id(
&self,
) -> Result<common_utils::id_type::MerchantConnectorAccountId, errors::ValidationError> {
self.0
.get(&enums::AuthenticationProduct::ClickToPay)
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "authentication_product_id.click_to_pay".to_string(),
})
.map_err(Report::from)
.cloned()
}
}
/// A wrapper type for merchant country codes that provides validation and conversion functionality.
///
/// This type stores a country code as a string and provides methods to validate it
/// and convert it to a `Country` enum variant.
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Text)]
#[serde(deny_unknown_fields)]
pub struct MerchantCountryCode(String);
impl MerchantCountryCode {
/// Returns the country code as a string.
pub fn get_country_code(&self) -> String {
self.0.clone()
}
/// Validates the country code and returns a `Country` enum variant.
///
/// This method attempts to parse the country code as a u32 and convert it to a `Country` enum variant.
/// If the country code is invalid, it returns a `ValidationError` with the appropriate error message.
pub fn validate_and_get_country_from_merchant_country_code(
&self,
) -> errors::CustomResult<common_enums::Country, errors::ValidationError> {
let country_code = self.get_country_code();
let code = country_code
.parse::<u32>()
.map_err(Report::from)
.change_context(errors::ValidationError::IncorrectValueProvided {
field_name: "merchant_country_code",
})
.attach_printable_lazy(|| {
format!("Country code {country_code} is negative or too large")
})?;
common_enums::Country::from_numeric(code)
.map_err(|_| errors::ValidationError::IncorrectValueProvided {
field_name: "merchant_country_code",
})
.attach_printable_lazy(|| format!("Invalid country code {code}"))
}
/// Creates a new `MerchantCountryCode` instance from a string.
pub fn new(country_code: String) -> Self {
Self(country_code)
}
}
impl diesel::serialize::ToSql<Text, diesel::pg::Pg> for MerchantCountryCode {
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
<String as diesel::serialize::ToSql<Text, diesel::pg::Pg>>::to_sql(&self.0, out)
}
}
impl diesel::deserialize::FromSql<Text, diesel::pg::Pg> for MerchantCountryCode {
fn from_sql(bytes: diesel::pg::PgValue<'_>) -> diesel::deserialize::Result<Self> {
let s = <String as diesel::deserialize::FromSql<Text, diesel::pg::Pg>>::from_sql(bytes)?;
Ok(Self(s))
}
}
#[derive(
Serialize, Default, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
/// ConditionalConfigs
pub struct ConditionalConfigs {
/// Override 3DS
pub override_3ds: Option<common_enums::AuthenticationType>,
}
impl EuclidDirFilter for ConditionalConfigs {
const ALLOWED: &'static [DirKeyKind] = &[
DirKeyKind::PaymentMethod,
DirKeyKind::CardType,
DirKeyKind::CardNetwork,
DirKeyKind::MetaData,
DirKeyKind::PaymentAmount,
DirKeyKind::PaymentCurrency,
DirKeyKind::CaptureMethod,
DirKeyKind::BillingCountry,
DirKeyKind::BusinessCountry,
];
}
impl_to_sql_from_sql_json!(ConditionalConfigs);
/// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client.
#[derive(
Default,
Eq,
PartialEq,
Debug,
serde::Deserialize,
serde::Serialize,
Clone,
AsExpression,
ToSchema,
)]
#[serde(deny_unknown_fields)]
#[diesel(sql_type = Jsonb)]
pub struct CustomerAcceptance {
/// Type of acceptance provided by the
#[schema(example = "online")]
pub acceptance_type: AcceptanceType,
/// Specifying when the customer acceptance was provided
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub accepted_at: Option<PrimitiveDateTime>,
/// Information required for online mandate generation
pub online: Option<OnlineMandate>,
}
impl_to_sql_from_sql_json!(CustomerAcceptance);
impl CustomerAcceptance {
/// Get the IP address
pub fn get_ip_address(&self) -> Option<String> {
self.online
.as_ref()
.and_then(|data| data.ip_address.as_ref().map(|ip| ip.peek().to_owned()))
}
/// Get the User Agent
pub fn get_user_agent(&self) -> Option<String> {
self.online.as_ref().map(|data| data.user_agent.clone())
}
/// Get when the customer acceptance was provided
pub fn get_accepted_at(&self) -> PrimitiveDateTime {
self.accepted_at.unwrap_or_else(date_time::now)
}
}
impl masking::SerializableSecret for CustomerAcceptance {}
#[derive(
Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, Copy, ToSchema,
)]
#[serde(rename_all = "lowercase")]
/// This is used to indicate if the mandate was accepted online or offline
pub enum AcceptanceType {
/// Online
Online,
/// Offline
#[default]
Offline,
}
#[derive(
Default,
Eq,
PartialEq,
Debug,
serde::Deserialize,
serde::Serialize,
AsExpression,
Clone,
ToSchema,
)]
#[serde(deny_unknown_fields)]
/// Details of online mandate
#[diesel(sql_type = Jsonb)]
pub struct OnlineMandate {
/// Ip address of the customer machine from which the mandate was created
#[schema(value_type = String, example = "123.32.25.123")]
pub ip_address: Option<Secret<String, pii::IpAddress>>,
/// The user-agent of the customer's browser
pub user_agent: String,
}
impl_to_sql_from_sql_json!(OnlineMandate);
#[derive(Serialize, Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)]
#[diesel(sql_type = Jsonb)]
/// DecisionManagerRecord
pub struct DecisionManagerRecord {
/// Name of the Decision Manager
pub name: String,
/// Program to be executed
pub program: Program<ConditionalConfigs>,
/// Created at timestamp
pub created_at: i64,
}
impl events::ApiEventMetric for DecisionManagerRecord {
fn get_api_event_type(&self) -> Option<events::ApiEventsType> {
Some(events::ApiEventsType::Routing)
}
}
impl_to_sql_from_sql_json!(DecisionManagerRecord);
/// DecisionManagerResponse
pub type DecisionManagerResponse = DecisionManagerRecord;
/// Fee information to be charged on the payment being collected via Stripe
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
pub struct StripeChargeResponseData {
/// Identifier for charge created for the payment
pub charge_id: Option<String>,
/// Type of charge (connector specific)
#[schema(value_type = PaymentChargeType, example = "direct")]
pub charge_type: enums::PaymentChargeType,
/// Platform fees collected on the payment
#[schema(value_type = i64, example = 6540)]
pub application_fees: Option<MinorUnit>,
/// Identifier for the reseller's account where the funds were transferred
pub transfer_account_id: String,
}
impl_to_sql_from_sql_json!(StripeChargeResponseData);
/// Charge Information
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum ConnectorChargeResponseData {
/// StripeChargeResponseData
StripeSplitPayment(StripeChargeResponseData),
/// AdyenChargeResponseData
AdyenSplitPayment(AdyenSplitData),
/// XenditChargeResponseData
XenditSplitPayment(XenditChargeResponseData),
}
impl_to_sql_from_sql_json!(ConnectorChargeResponseData);
/// Fee information to be charged on the payment being collected via xendit
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
pub struct XenditSplitRoute {
/// Amount of payments to be split
pub flat_amount: Option<MinorUnit>,
/// Amount of payments to be split, using a percent rate as unit
pub percent_amount: Option<i64>,
/// Currency code
#[schema(value_type = Currency, example = "USD")]
pub currency: enums::Currency,
/// ID of the destination account where the amount will be routed to
pub destination_account_id: String,
/// Reference ID which acts as an identifier of the route itself
pub reference_id: String,
}
impl_to_sql_from_sql_json!(XenditSplitRoute);
/// Fee information to be charged on the payment being collected via xendit
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
pub struct XenditMultipleSplitRequest {
/// Name to identify split rule. Not required to be unique. Typically based on transaction and/or sub-merchant types.
pub name: String,
/// Description to identify fee rule
pub description: String,
/// The sub-account user-id that you want to make this transaction for.
pub for_user_id: Option<String>,
/// Array of objects that define how the platform wants to route the fees and to which accounts.
pub routes: Vec<XenditSplitRoute>,
}
impl_to_sql_from_sql_json!(XenditMultipleSplitRequest);
/// Xendit Charge Request
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum XenditSplitRequest {
/// Split Between Multiple Accounts
MultipleSplits(XenditMultipleSplitRequest),
/// Collect Fee for Single Account
SingleSplit(XenditSplitSubMerchantData),
}
impl_to_sql_from_sql_json!(XenditSplitRequest);
/// Charge Information
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum XenditChargeResponseData {
/// Split Between Multiple Accounts
MultipleSplits(XenditMultipleSplitResponse),
/// Collect Fee for Single Account
SingleSplit(XenditSplitSubMerchantData),
}
impl_to_sql_from_sql_json!(XenditChargeResponseData);
/// Fee information charged on the payment being collected via xendit
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(deny_unknown_fields)]
pub struct XenditMultipleSplitResponse {
/// Identifier for split rule created for the payment
pub split_rule_id: String,
/// The sub-account user-id that you want to make this transaction for.
pub for_user_id: Option<String>,
/// Name to identify split rule. Not required to be unique. Typically based on transaction and/or sub-merchant types.
pub name: String,
/// Description to identify fee rule
pub description: String,
/// Array of objects that define how the platform wants to route the fees and to which accounts.
pub routes: Vec<XenditSplitRoute>,
}
impl_to_sql_from_sql_json!(XenditMultipleSplitResponse);
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
/// This enum is used to represent the Gpay payment data, which can either be encrypted or decrypted.
pub enum GpayTokenizationData {
/// This variant contains the decrypted Gpay payment data as a structured object.
Decrypted(GPayPredecryptData),
/// This variant contains the encrypted Gpay payment data as a string.
Encrypted(GpayEcryptedTokenizationData),
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
/// This struct represents the encrypted Gpay payment data
pub struct GpayEcryptedTokenizationData {
/// The type of the token
#[serde(rename = "type")]
pub token_type: String,
/// Token generated for the wallet
pub token: String,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
/// This struct represents the decrypted Google Pay payment data
pub struct GPayPredecryptData {
/// The card's expiry month
#[schema(value_type = String)]
pub card_exp_month: Secret<String>,
/// The card's expiry year
#[schema(value_type = String)]
pub card_exp_year: Secret<String>,
/// The Primary Account Number (PAN) of the card
#[schema(value_type = String, example = "4242424242424242")]
pub application_primary_account_number: cards::CardNumber,
/// Cryptogram generated by the Network
#[schema(value_type = String, example = "AgAAAAAAAIR8CQrXcIhbQAAAAAA")]
pub cryptogram: Option<Secret<String>>,
/// Electronic Commerce Indicator
#[schema(value_type = String, example = "07")]
pub eci_indicator: Option<String>,
}
impl GpayTokenizationData {
/// Get the encrypted Google Pay payment data, returning an error if it does not exist
pub fn get_encrypted_google_pay_payment_data_mandatory(
&self,
) -> Result<&GpayEcryptedTokenizationData, errors::ValidationError> {
match self {
Self::Encrypted(encrypted_data) => Ok(encrypted_data),
Self::Decrypted(_) => Err(errors::ValidationError::InvalidValue {
message: "Encrypted Google Pay payment data is mandatory".to_string(),
}
.into()),
}
}
/// Get the token from Google Pay tokenization data
/// Returns the token string if encrypted data exists, otherwise returns an error
pub fn get_encrypted_google_pay_token(&self) -> Result<String, errors::ValidationError> {
Ok(self
.get_encrypted_google_pay_payment_data_mandatory()?
.token
.clone())
}
/// Get the token type from Google Pay tokenization data
/// Returns the token_type string if encrypted data exists, otherwise returns an error
pub fn get_encrypted_token_type(&self) -> Result<String, errors::ValidationError> {
Ok(self
.get_encrypted_google_pay_payment_data_mandatory()?
.token_type
.clone())
}
}
impl GPayPredecryptData {
/// Get the four-digit expiration year from the Google Pay pre-decrypt data
pub fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> {
let mut year = self.card_exp_year.peek().clone();
// If it's a 2-digit year, convert to 4-digit
if year.len() == 2 {
year = format!("20{year}");
} else if year.len() != 4 {
return Err(errors::ValidationError::InvalidValue {
message: format!(
"Invalid expiry year length: {}. Must be 2 or 4 digits",
year.len()
),
}
.into());
}
Ok(Secret::new(year))
}
/// Get the 2-digit expiration year from the Google Pay pre-decrypt data
pub fn get_two_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ValidationError::InvalidValue {
message: "Invalid two-digit year".to_string(),
})?
.to_string(),
))
}
/// Get the expiry date in MMYY format from the Google Pay pre-decrypt data
pub fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ValidationError> {
let year = self.get_two_digit_expiry_year()?.expose();
let month = self.get_expiry_month()?.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
/// Get the expiration month from the Google Pay pre-decrypt data
pub fn get_expiry_month(&self) -> Result<Secret<String>, errors::ValidationError> {
let month_str = self.card_exp_month.peek();
let month = month_str
.parse::<u8>()
.map_err(|_| errors::ValidationError::InvalidValue {
message: format!("Failed to parse expiry month: {month_str}"),
})?;
if !(1..=12).contains(&month) {
return Err(errors::ValidationError::InvalidValue {
message: format!("Invalid expiry month: {month}. Must be between 1 and 12"),
}
.into());
}
Ok(self.card_exp_month.clone())
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
/// This enum is used to represent the Apple Pay payment data, which can either be encrypted or decrypted.
pub enum ApplePayPaymentData {
/// This variant contains the decrypted Apple Pay payment data as a structured object.
Decrypted(ApplePayPredecryptData),
/// This variant contains the encrypted Apple Pay payment data as a string.
Encrypted(String),
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
/// This struct represents the decrypted Apple Pay payment data
pub struct ApplePayPredecryptData {
/// The primary account number
#[schema(value_type = String, example = "4242424242424242")]
pub application_primary_account_number: cards::CardNumber,
/// The application expiration date (PAN expiry month)
#[schema(value_type = String, example = "12")]
pub application_expiration_month: Secret<String>,
/// The application expiration date (PAN expiry year)
#[schema(value_type = String, example = "24")]
pub application_expiration_year: Secret<String>,
/// The payment data, which contains the cryptogram and ECI indicator
#[schema(value_type = ApplePayCryptogramData)]
pub payment_data: ApplePayCryptogramData,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
/// This struct represents the cryptogram data for Apple Pay transactions
pub struct ApplePayCryptogramData {
/// The online payment cryptogram
#[schema(value_type = String, example = "A1B2C3D4E5F6G7H8")]
pub online_payment_cryptogram: Secret<String>,
/// The ECI (Electronic Commerce Indicator) value
#[schema(value_type = String, example = "05")]
pub eci_indicator: Option<String>,
}
impl ApplePayPaymentData {
/// Get the encrypted Apple Pay payment data if it exists
pub fn get_encrypted_apple_pay_payment_data_optional(&self) -> Option<&String> {
match self {
Self::Encrypted(encrypted_data) => Some(encrypted_data),
Self::Decrypted(_) => None,
}
}
/// Get the decrypted Apple Pay payment data if it exists
pub fn get_decrypted_apple_pay_payment_data_optional(&self) -> Option<&ApplePayPredecryptData> {
match self {
Self::Encrypted(_) => None,
Self::Decrypted(decrypted_data) => Some(decrypted_data),
}
}
/// Get the encrypted Apple Pay payment data, returning an error if it does not exist
pub fn get_encrypted_apple_pay_payment_data_mandatory(
&self,
) -> Result<&String, errors::ValidationError> {
self.get_encrypted_apple_pay_payment_data_optional()
.get_required_value("Encrypted Apple Pay payment data")
.attach_printable("Encrypted Apple Pay payment data is mandatory")
}
/// Get the decrypted Apple Pay payment data, returning an error if it does not exist
pub fn get_decrypted_apple_pay_payment_data_mandatory(
&self,
) -> Result<&ApplePayPredecryptData, errors::ValidationError> {
self.get_decrypted_apple_pay_payment_data_optional()
.get_required_value("Decrypted Apple Pay payment data")
.attach_printable("Decrypted Apple Pay payment data is mandatory")
}
}
impl ApplePayPredecryptData {
/// Get the four-digit expiration year from the Apple Pay pre-decrypt data
pub fn get_two_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> {
let binding = self.application_expiration_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ValidationError::InvalidValue {
message: "Invalid two-digit year".to_string(),
})?
.to_string(),
))
}
/// Get the four-digit expiration year from the Apple Pay pre-decrypt data
pub fn get_four_digit_expiry_year(&self) -> Secret<String> {
let mut year = self.application_expiration_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
/// Get the expiration month from the Apple Pay pre-decrypt data
pub fn get_expiry_month(&self) -> Result<Secret<String>, errors::ValidationError> {
let month_str = self.application_expiration_month.peek();
let month = month_str
.parse::<u8>()
.map_err(|_| errors::ValidationError::InvalidValue {
message: format!("Failed to parse expiry month: {month_str}"),
})?;
if !(1..=12).contains(&month) {
return Err(errors::ValidationError::InvalidValue {
message: format!("Invalid expiry month: {month}. Must be between 1 and 12"),
}
.into());
}
Ok(self.application_expiration_month.clone())
}
/// Get the expiry date in MMYY format from the Apple Pay pre-decrypt data
pub fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ValidationError> {
let year = self.get_two_digit_expiry_year()?.expose();
let month = self.get_expiry_month()?.expose();
Ok(Secret::new(format!("{month}{year}")))
}
/// Get the expiry date in YYMM format from the Apple Pay pre-decrypt data
pub fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ValidationError> {
let year = self.get_two_digit_expiry_year()?.expose();
let month = self.get_expiry_month()?.expose();
Ok(Secret::new(format!("{year}{month}")))
}
}
/// type of action that needs to taken after consuming recovery payload
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecoveryAction {
/// Stops the process tracker and update the payment intent.
CancelInvoice,
/// Records the external transaction against payment intent.
ScheduleFailedPayment,
/// Records the external payment and stops the internal process tracker.
SuccessPaymentExternal,
/// Pending payments from billing processor.
PendingPayment,
/// No action required.
NoAction,
/// Invalid event has been received.
InvalidAction,
}
</file>
|
{
"crate": "common_types",
"file": "crates/common_types/src/payments.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5996
}
|
large_file_-4054883787832133074
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_types
File: crates/common_types/src/primitive_wrappers.rs
</path>
<file>
pub use bool_wrappers::*;
pub use safe_string::*;
pub use u32_wrappers::*;
mod bool_wrappers {
use std::ops::Deref;
use serde::{Deserialize, Serialize};
/// Bool that represents if Extended Authorization is Applied or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ExtendedAuthorizationAppliedBool(bool);
impl Deref for ExtendedAuthorizationAppliedBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for ExtendedAuthorizationAppliedBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct RequestExtendedAuthorizationBool(bool);
impl Deref for RequestExtendedAuthorizationBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for RequestExtendedAuthorizationBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl RequestExtendedAuthorizationBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Enable Partial Authorization is Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct EnablePartialAuthorizationBool(bool);
impl Deref for EnablePartialAuthorizationBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<bool> for EnablePartialAuthorizationBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl EnablePartialAuthorizationBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for EnablePartialAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for EnablePartialAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is always Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct AlwaysRequestExtendedAuthorization(bool);
impl Deref for AlwaysRequestExtendedAuthorization {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Cvv should be collected during payment or not. Default is true
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ShouldCollectCvvDuringPayment(bool);
impl Deref for ShouldCollectCvvDuringPayment {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for ShouldCollectCvvDuringPayment
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
impl Default for ShouldCollectCvvDuringPayment {
/// Default for `ShouldCollectCvvDuringPayment` is `true`
fn default() -> Self {
Self(true)
}
}
/// Bool that represents if overcapture should always be requested
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct AlwaysEnableOvercaptureBool(bool);
impl AlwaysEnableOvercaptureBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for AlwaysEnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for AlwaysEnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
impl Default for AlwaysEnableOvercaptureBool {
/// Default for `AlwaysEnableOvercaptureBool` is `false`
fn default() -> Self {
Self(false)
}
}
/// Bool that represents if overcapture is requested for this payment
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct EnableOvercaptureBool(bool);
impl From<bool> for EnableOvercaptureBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl From<AlwaysEnableOvercaptureBool> for EnableOvercaptureBool {
fn from(item: AlwaysEnableOvercaptureBool) -> Self {
Self(item.is_true())
}
}
impl Deref for EnableOvercaptureBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for EnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for EnableOvercaptureBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
impl Default for EnableOvercaptureBool {
/// Default for `EnableOvercaptureBool` is `false`
fn default() -> Self {
Self(false)
}
}
/// Bool that represents if overcapture is applied for a payment by the connector
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct OvercaptureEnabledBool(bool);
impl OvercaptureEnabledBool {
/// Creates a new instance of `OvercaptureEnabledBool`
pub fn new(value: bool) -> Self {
Self(value)
}
}
impl Default for OvercaptureEnabledBool {
/// Default for `OvercaptureEnabledBool` is `false`
fn default() -> Self {
Self(false)
}
}
impl Deref for OvercaptureEnabledBool {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for OvercaptureEnabledBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for OvercaptureEnabledBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
}
mod u32_wrappers {
use std::ops::Deref;
use serde::{de::Error, Deserialize, Serialize};
use crate::consts::{
DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS, MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS,
};
/// Time interval in hours for polling disputes
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, diesel::expression::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Integer)]
pub struct DisputePollingIntervalInHours(i32);
impl Deref for DisputePollingIntervalInHours {
type Target = i32;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'de> Deserialize<'de> for DisputePollingIntervalInHours {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let val = i32::deserialize(deserializer)?;
if val < 0 {
Err(D::Error::custom(
"DisputePollingIntervalInHours cannot be negative",
))
} else if val > MAX_DISPUTE_POLLING_INTERVAL_IN_HOURS {
Err(D::Error::custom(
"DisputePollingIntervalInHours exceeds the maximum allowed value of 24",
))
} else {
Ok(Self(val))
}
}
}
impl diesel::deserialize::FromSql<diesel::sql_types::Integer, diesel::pg::Pg>
for DisputePollingIntervalInHours
{
fn from_sql(value: diesel::pg::PgValue<'_>) -> diesel::deserialize::Result<Self> {
i32::from_sql(value).map(Self)
}
}
impl diesel::serialize::ToSql<diesel::sql_types::Integer, diesel::pg::Pg>
for DisputePollingIntervalInHours
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
<i32 as diesel::serialize::ToSql<diesel::sql_types::Integer, diesel::pg::Pg>>::to_sql(
&self.0, out,
)
}
}
impl Default for DisputePollingIntervalInHours {
/// Default for `DisputePollingIntervalInHours` is `24`
fn default() -> Self {
Self(DEFAULT_DISPUTE_POLLING_INTERVAL_IN_HOURS)
}
}
}
/// Safe string wrapper that validates input against XSS attacks
mod safe_string {
use std::ops::Deref;
use common_utils::validation::contains_potential_xss_or_sqli;
use masking::SerializableSecret;
use serde::{de::Error, Deserialize, Serialize};
/// String wrapper that prevents XSS and SQLi attacks
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct SafeString(String);
impl SafeString {
/// Creates a new SafeString after XSS and SQL injection validation
pub fn new(value: String) -> Result<Self, String> {
if contains_potential_xss_or_sqli(&value) {
return Err("Input contains potentially malicious content".into());
}
Ok(Self(value))
}
/// Creates a SafeString from a string slice
pub fn from_string_slice(value: &str) -> Result<Self, String> {
Self::new(value.to_string())
}
/// Returns the inner string as a string slice
pub fn as_str(&self) -> &str {
&self.0
}
/// Consumes self and returns the inner String
pub fn into_inner(self) -> String {
self.0
}
/// Returns true if the string is empty
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the length of the string
pub fn len(&self) -> usize {
self.0.len()
}
}
impl Deref for SafeString {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
// Custom serialization and deserialization
impl Serialize for SafeString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for SafeString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::new(value).map_err(D::Error::custom)
}
}
// Implement SerializableSecret for SafeString to work with Secret<SafeString>
impl SerializableSecret for SafeString {}
// Diesel implementations for database operations
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for SafeString
where
DB: diesel::backend::Backend,
String: diesel::serialize::ToSql<diesel::sql_types::Text, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for SafeString
where
DB: diesel::backend::Backend,
String: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
String::from_sql(value).map(Self)
}
}
}
</file>
|
{
"crate": "common_types",
"file": "crates/common_types/src/primitive_wrappers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4248
}
|
large_file_-5730606400166209520
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: smithy-core
File: crates/smithy-core/src/types.rs
</path>
<file>
// crates/smithy-core/types.rs
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SmithyModel {
pub namespace: String,
pub shapes: HashMap<String, SmithyShape>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum SmithyShape {
#[serde(rename = "structure")]
Structure {
members: HashMap<String, SmithyMember>,
#[serde(skip_serializing_if = "Option::is_none")]
documentation: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
traits: Vec<SmithyTrait>,
},
#[serde(rename = "string")]
String {
#[serde(skip_serializing_if = "Vec::is_empty")]
traits: Vec<SmithyTrait>,
},
#[serde(rename = "integer")]
Integer {
#[serde(skip_serializing_if = "Vec::is_empty")]
traits: Vec<SmithyTrait>,
},
#[serde(rename = "long")]
Long {
#[serde(skip_serializing_if = "Vec::is_empty")]
traits: Vec<SmithyTrait>,
},
#[serde(rename = "boolean")]
Boolean {
#[serde(skip_serializing_if = "Vec::is_empty")]
traits: Vec<SmithyTrait>,
},
#[serde(rename = "list")]
List {
member: Box<SmithyMember>,
#[serde(skip_serializing_if = "Vec::is_empty")]
traits: Vec<SmithyTrait>,
},
#[serde(rename = "union")]
Union {
members: HashMap<String, SmithyMember>,
#[serde(skip_serializing_if = "Option::is_none")]
documentation: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
traits: Vec<SmithyTrait>,
},
#[serde(rename = "enum")]
Enum {
values: HashMap<String, SmithyEnumValue>,
#[serde(skip_serializing_if = "Option::is_none")]
documentation: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
traits: Vec<SmithyTrait>,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SmithyMember {
pub target: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub documentation: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub traits: Vec<SmithyTrait>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SmithyEnumValue {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub documentation: Option<String>,
pub is_default: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "trait")]
pub enum SmithyTrait {
#[serde(rename = "smithy.api#pattern")]
Pattern { pattern: String },
#[serde(rename = "smithy.api#range")]
Range { min: Option<i64>, max: Option<i64> },
#[serde(rename = "smithy.api#required")]
Required,
#[serde(rename = "smithy.api#documentation")]
Documentation { documentation: String },
#[serde(rename = "smithy.api#length")]
Length { min: Option<u64>, max: Option<u64> },
#[serde(rename = "smithy.api#httpLabel")]
HttpLabel,
#[serde(rename = "smithy.api#httpQuery")]
HttpQuery { name: String },
#[serde(rename = "smithy.api#mixin")]
Mixin,
}
#[derive(Debug, Clone)]
pub struct SmithyField {
pub name: String,
pub value_type: String,
pub constraints: Vec<SmithyConstraint>,
pub documentation: Option<String>,
pub optional: bool,
pub flatten: bool,
}
#[derive(Debug, Clone)]
pub struct SmithyEnumVariant {
pub name: String,
pub fields: Vec<SmithyField>,
pub constraints: Vec<SmithyConstraint>,
pub documentation: Option<String>,
}
#[derive(Debug, Clone)]
pub enum SmithyConstraint {
Pattern(String),
Range(Option<i64>, Option<i64>),
Length(Option<u64>, Option<u64>),
Required,
HttpLabel,
HttpQuery(String),
}
pub trait SmithyModelGenerator {
fn generate_smithy_model() -> SmithyModel;
}
// Helper functions moved from the proc-macro crate to be accessible by it.
pub fn resolve_type_and_generate_shapes(
value_type: &str,
shapes: &mut HashMap<String, SmithyShape>,
) -> Result<(String, HashMap<String, SmithyShape>), syn::Error> {
let value_type = value_type.trim();
let value_type_span = proc_macro2::Span::call_site();
let mut generated_shapes = HashMap::new();
let target_type = match value_type {
"String" | "str" => "smithy.api#String".to_string(),
"i8" | "i16" | "i32" | "u8" | "u16" | "u32" => "smithy.api#Integer".to_string(),
"i64" | "u64" | "isize" | "usize" => "smithy.api#Long".to_string(),
"f32" => "smithy.api#Float".to_string(),
"f64" => "smithy.api#Double".to_string(),
"bool" => "smithy.api#Boolean".to_string(),
"PrimitiveDateTime" | "time::PrimitiveDateTime" => "smithy.api#Timestamp".to_string(),
"Amount" | "MinorUnit" => "smithy.api#Long".to_string(),
"serde_json::Value" | "Value" | "Object" => "smithy.api#Document".to_string(),
"Url" | "url::Url" => "smithy.api#String".to_string(),
vt if vt.starts_with("Option<") && vt.ends_with('>') => {
let inner_type = extract_generic_inner_type(vt, "Option")
.map_err(|e| syn::Error::new(value_type_span, e))?;
let (resolved_type, new_shapes) = resolve_type_and_generate_shapes(inner_type, shapes)?;
generated_shapes.extend(new_shapes);
resolved_type
}
vt if vt.starts_with("Vec<") && vt.ends_with('>') => {
let inner_type = extract_generic_inner_type(vt, "Vec")
.map_err(|e| syn::Error::new(value_type_span, e))?;
let (inner_smithy_type, new_shapes) =
resolve_type_and_generate_shapes(inner_type, shapes)?;
generated_shapes.extend(new_shapes);
let list_shape_name = format!(
"{}List",
inner_smithy_type
.split("::")
.last()
.unwrap_or(&inner_smithy_type)
.split('#')
.next_back()
.unwrap_or(&inner_smithy_type)
);
if !shapes.contains_key(&list_shape_name)
&& !generated_shapes.contains_key(&list_shape_name)
{
let list_shape = SmithyShape::List {
member: Box::new(SmithyMember {
target: inner_smithy_type,
documentation: None,
traits: vec![],
}),
traits: vec![],
};
generated_shapes.insert(list_shape_name.clone(), list_shape);
}
list_shape_name
}
vt if vt.starts_with("Box<") && vt.ends_with('>') => {
let inner_type = extract_generic_inner_type(vt, "Box")
.map_err(|e| syn::Error::new(value_type_span, e))?;
let (resolved_type, new_shapes) = resolve_type_and_generate_shapes(inner_type, shapes)?;
generated_shapes.extend(new_shapes);
resolved_type
}
vt if vt.starts_with("Secret<") && vt.ends_with('>') => {
let inner_type = extract_generic_inner_type(vt, "Secret")
.map_err(|e| syn::Error::new(value_type_span, e))?;
let (resolved_type, new_shapes) = resolve_type_and_generate_shapes(inner_type, shapes)?;
generated_shapes.extend(new_shapes);
resolved_type
}
vt if vt.starts_with("HashMap<") && vt.ends_with('>') => {
let inner_types = extract_generic_inner_type(vt, "HashMap")
.map_err(|e| syn::Error::new(value_type_span, e))?;
let (key_type, value_type) =
parse_map_types(inner_types).map_err(|e| syn::Error::new(value_type_span, e))?;
let (key_smithy_type, key_shapes) = resolve_type_and_generate_shapes(key_type, shapes)?;
generated_shapes.extend(key_shapes);
let (value_smithy_type, value_shapes) =
resolve_type_and_generate_shapes(value_type, shapes)?;
generated_shapes.extend(value_shapes);
format!(
"smithy.api#Map<key: {}, value: {}>",
key_smithy_type, value_smithy_type
)
}
vt if vt.starts_with("BTreeMap<") && vt.ends_with('>') => {
let inner_types = extract_generic_inner_type(vt, "BTreeMap")
.map_err(|e| syn::Error::new(value_type_span, e))?;
let (key_type, value_type) =
parse_map_types(inner_types).map_err(|e| syn::Error::new(value_type_span, e))?;
let (key_smithy_type, key_shapes) = resolve_type_and_generate_shapes(key_type, shapes)?;
generated_shapes.extend(key_shapes);
let (value_smithy_type, value_shapes) =
resolve_type_and_generate_shapes(value_type, shapes)?;
generated_shapes.extend(value_shapes);
format!(
"smithy.api#Map<key: {}, value: {}>",
key_smithy_type, value_smithy_type
)
}
_ => {
if value_type.contains("::") {
value_type.replace("::", ".")
} else {
value_type.to_string()
}
}
};
Ok((target_type, generated_shapes))
}
fn extract_generic_inner_type<'a>(full_type: &'a str, wrapper: &str) -> Result<&'a str, String> {
let expected_start = format!("{}<", wrapper);
if !full_type.starts_with(&expected_start) || !full_type.ends_with('>') {
return Err(format!("Invalid {} type format: {}", wrapper, full_type));
}
let start_idx = expected_start.len();
let end_idx = full_type.len() - 1;
if start_idx >= end_idx {
return Err(format!("Empty {} type: {}", wrapper, full_type));
}
if start_idx >= full_type.len() || end_idx > full_type.len() {
return Err(format!(
"Invalid index bounds for {} type: {}",
wrapper, full_type
));
}
Ok(full_type
.get(start_idx..end_idx)
.ok_or_else(|| {
format!(
"Failed to extract inner type from {}: {}",
wrapper, full_type
)
})?
.trim())
}
fn parse_map_types(inner_types: &str) -> Result<(&str, &str), String> {
// Handle nested generics by counting angle brackets
let mut bracket_count = 0;
let mut comma_pos = None;
for (i, ch) in inner_types.char_indices() {
match ch {
'<' => bracket_count += 1,
'>' => bracket_count -= 1,
',' if bracket_count == 0 => {
comma_pos = Some(i);
break;
}
_ => {}
}
}
if let Some(pos) = comma_pos {
let key_type = inner_types
.get(..pos)
.ok_or_else(|| format!("Invalid key type bounds in map: {}", inner_types))?
.trim();
let value_type = inner_types
.get(pos + 1..)
.ok_or_else(|| format!("Invalid value type bounds in map: {}", inner_types))?
.trim();
if key_type.is_empty() || value_type.is_empty() {
return Err(format!("Invalid map type format: {}", inner_types));
}
Ok((key_type, value_type))
} else {
Err(format!(
"Invalid map type format, missing comma: {}",
inner_types
))
}
}
</file>
|
{
"crate": "smithy-core",
"file": "crates/smithy-core/src/types.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2718
}
|
large_file_3984578187734090948
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: smithy-core
File: crates/smithy-core/src/generator.rs
</path>
<file>
// crates/smithy-core/generator.rs
use std::{collections::HashMap, fs, path::Path};
use crate::types::{self as types, SmithyModel};
/// Generator for creating Smithy IDL files from models
pub struct SmithyGenerator {
models: Vec<SmithyModel>,
}
impl SmithyGenerator {
pub fn new() -> Self {
Self { models: Vec::new() }
}
pub fn add_model(&mut self, model: SmithyModel) {
self.models.push(model);
}
pub fn generate_idl(&self, output_dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
fs::create_dir_all(output_dir)?;
let mut namespace_models: HashMap<String, Vec<&SmithyModel>> = HashMap::new();
let mut shape_to_namespace: HashMap<String, String> = HashMap::new();
// First, build a map of all shape names to their namespaces
for model in &self.models {
for shape_name in model.shapes.keys() {
shape_to_namespace.insert(shape_name.clone(), model.namespace.clone());
}
}
// Group models by namespace for file generation
for model in &self.models {
namespace_models
.entry(model.namespace.clone())
.or_default()
.push(model);
}
for (namespace, models) in namespace_models {
let filename = format!("{}.smithy", namespace.replace('.', "_"));
let filepath = output_dir.join(filename);
let mut content = String::new();
content.push_str("$version: \"2\"\n\n");
content.push_str(&format!("namespace {}\n\n", namespace));
// Collect all unique shape definitions for the current namespace
let mut shapes_in_namespace = HashMap::new();
for model in models {
for (shape_name, shape) in &model.shapes {
shapes_in_namespace.insert(shape_name.clone(), shape.clone());
}
}
// Generate definitions for each shape in the namespace
for (shape_name, shape) in &shapes_in_namespace {
content.push_str(&self.generate_shape_definition(
shape_name,
shape,
&namespace,
&shape_to_namespace,
));
content.push_str("\n\n");
}
fs::write(filepath, content)?;
}
Ok(())
}
fn generate_shape_definition(
&self,
name: &str,
shape: &types::SmithyShape,
current_namespace: &str,
shape_to_namespace: &HashMap<String, String>,
) -> String {
let resolve_target =
|target: &str| self.resolve_type(target, current_namespace, shape_to_namespace);
match shape {
types::SmithyShape::Structure {
members,
documentation,
traits,
} => {
let mut def = String::new();
if let Some(doc) = documentation {
def.push_str(&format!("/// {}\n", doc));
}
for smithy_trait in traits {
def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait)));
}
def.push_str(&format!("structure {} {{\n", name));
for (member_name, member) in members {
if let Some(doc) = &member.documentation {
def.push_str(&format!(" /// {}\n", doc));
}
for smithy_trait in &member.traits {
def.push_str(&format!(" @{}\n", self.trait_to_string(smithy_trait)));
}
let resolved_target = resolve_target(&member.target);
def.push_str(&format!(" {}: {}\n", member_name, resolved_target));
}
def.push('}');
def
}
types::SmithyShape::Union {
members,
documentation,
traits,
} => {
let mut def = String::new();
if let Some(doc) = documentation {
def.push_str(&format!("/// {}\n", doc));
}
for smithy_trait in traits {
def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait)));
}
def.push_str(&format!("union {} {{\n", name));
for (member_name, member) in members {
if let Some(doc) = &member.documentation {
def.push_str(&format!(" /// {}\n", doc));
}
for smithy_trait in &member.traits {
def.push_str(&format!(" @{}\n", self.trait_to_string(smithy_trait)));
}
let resolved_target = resolve_target(&member.target);
def.push_str(&format!(" {}: {}\n", member_name, resolved_target));
}
def.push('}');
def
}
types::SmithyShape::Enum {
values,
documentation,
traits,
} => {
let mut def = String::new();
if let Some(doc) = documentation {
def.push_str(&format!("/// {}\n", doc));
}
for smithy_trait in traits {
def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait)));
}
def.push_str(&format!("enum {} {{\n", name));
for (value_name, enum_value) in values {
if let Some(doc) = &enum_value.documentation {
def.push_str(&format!(" /// {}\n", doc));
}
def.push_str(&format!(" {}\n", value_name));
}
def.push('}');
def
}
types::SmithyShape::String { traits } => {
let mut def = String::new();
for smithy_trait in traits {
def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait)));
}
def.push_str(&format!("string {}", name));
def
}
types::SmithyShape::Integer { traits } => {
let mut def = String::new();
for smithy_trait in traits {
def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait)));
}
def.push_str(&format!("integer {}", name));
def
}
types::SmithyShape::Long { traits } => {
let mut def = String::new();
for smithy_trait in traits {
def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait)));
}
def.push_str(&format!("long {}", name));
def
}
types::SmithyShape::Boolean { traits } => {
let mut def = String::new();
for smithy_trait in traits {
def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait)));
}
def.push_str(&format!("boolean {}", name));
def
}
types::SmithyShape::List { member, traits } => {
let mut def = String::new();
for smithy_trait in traits {
def.push_str(&format!("@{}\n", self.trait_to_string(smithy_trait)));
}
def.push_str(&format!("list {} {{\n", name));
let resolved_target = resolve_target(&member.target);
def.push_str(&format!(" member: {}\n", resolved_target));
def.push('}');
def
}
}
}
fn resolve_type(
&self,
target: &str,
current_namespace: &str,
shape_to_namespace: &HashMap<String, String>,
) -> String {
// If the target is a primitive or a fully qualified Smithy type, return it as is
if target.starts_with("smithy.api#") {
return target.to_string();
}
// If the target is a custom type, resolve its namespace
if let Some(target_namespace) = shape_to_namespace.get(target) {
if target_namespace == current_namespace {
// The type is in the same namespace, so no qualification is needed
target.to_string()
} else {
// The type is in a different namespace, so it needs to be fully qualified
format!("{}#{}", target_namespace, target)
}
} else {
// If the type is not found in the shape map, it might be a primitive
// or an unresolved type. For now, return it as is.
target.to_string()
}
}
fn trait_to_string(&self, smithy_trait: &types::SmithyTrait) -> String {
match smithy_trait {
types::SmithyTrait::Pattern { pattern } => {
format!("pattern(\"{}\")", pattern)
}
types::SmithyTrait::Range { min, max } => match (min, max) {
(Some(min), Some(max)) => format!("range(min: {}, max: {})", min, max),
(Some(min), None) => format!("range(min: {})", min),
(None, Some(max)) => format!("range(max: {})", max),
(None, None) => "range".to_string(),
},
types::SmithyTrait::Required => "required".to_string(),
types::SmithyTrait::Documentation { documentation } => {
format!("documentation(\"{}\")", documentation)
}
types::SmithyTrait::Length { min, max } => match (min, max) {
(Some(min), Some(max)) => format!("length(min: {}, max: {})", min, max),
(Some(min), None) => format!("length(min: {})", min),
(None, Some(max)) => format!("length(max: {})", max),
(None, None) => "length".to_string(),
},
types::SmithyTrait::HttpLabel => "httpLabel".to_string(),
types::SmithyTrait::HttpQuery { name } => {
format!("httpQuery(\"{}\")", name)
}
types::SmithyTrait::Mixin => "mixin".to_string(),
}
}
}
impl Default for SmithyGenerator {
fn default() -> Self {
Self::new()
}
}
</file>
|
{
"crate": "smithy-core",
"file": "crates/smithy-core/src/generator.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2132
}
|
large_file_7041257242485611342
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: cards
File: crates/cards/src/validate.rs
</path>
<file>
use std::{collections::HashMap, fmt, ops::Deref, str::FromStr, sync::LazyLock};
use common_utils::errors::ValidationError;
use error_stack::report;
use masking::{PeekInterface, Strategy, StrongSecret, WithType};
use regex::Regex;
#[cfg(not(target_arch = "wasm32"))]
use router_env::{logger, which as router_env_which, Env};
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;
/// Minimum limit of a card number will not be less than 8 by ISO standards
pub const MIN_CARD_NUMBER_LENGTH: usize = 8;
/// Maximum limit of a card number will not exceed 19 by ISO standards
pub const MAX_CARD_NUMBER_LENGTH: usize = 19;
#[derive(Debug, Deserialize, Serialize, Error)]
#[error("{0}")]
pub struct CardNumberValidationErr(&'static str);
/// Card number
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
pub struct CardNumber(StrongSecret<String, CardNumberStrategy>);
//Network Token
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
pub struct NetworkToken(StrongSecret<String, CardNumberStrategy>);
impl CardNumber {
pub fn get_card_isin(&self) -> String {
self.0.peek().chars().take(6).collect::<String>()
}
pub fn get_extended_card_bin(&self) -> String {
self.0.peek().chars().take(8).collect::<String>()
}
pub fn get_card_no(&self) -> String {
self.0.peek().chars().collect::<String>()
}
pub fn get_last4(&self) -> String {
self.0
.peek()
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>()
}
pub fn is_cobadged_card(&self) -> Result<bool, error_stack::Report<ValidationError>> {
/// Regex to identify card networks
static CARD_NETWORK_REGEX: LazyLock<HashMap<&str, Result<Regex, regex::Error>>> =
LazyLock::new(|| {
let mut map = HashMap::new();
map.insert(
"Mastercard",
Regex::new(r"^(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[0-1][0-9]|2720|5[1-5])"),
);
map.insert("American Express", Regex::new(r"^3[47]"));
map.insert("Visa", Regex::new(r"^4"));
map.insert(
"Discover",
Regex::new(
r"^(6011|64[4-9]|65|622126|622[1-9][0-9][0-9]|6229[0-1][0-9]|622925)",
),
);
map.insert(
"Maestro",
Regex::new(r"^(5018|5081|5044|504681|504993|5020|502260|5038|5893|603845|603123|6304|6759|676[1-3]|6220|504834|504817|504645|504775|600206|627741)"),
);
map.insert(
"RuPay",
Regex::new(r"^(508227|508[5-9]|603741|60698[5-9]|60699|607[0-8]|6079[0-7]|60798[0-4]|60800[1-9]|6080[1-9]|608[1-4]|608500|6521[5-9]|652[2-9]|6530|6531[0-4]|817290|817368|817378|353800|82)"),
);
map.insert("Diners Club", Regex::new(r"^(36|38|39|30[0-5])"));
map.insert("JCB", Regex::new(r"^35(2[89]|[3-8][0-9])"));
map.insert("CarteBlanche", Regex::new(r"^389[0-9]{11}$"));
map.insert("Sodex", Regex::new(r"^(637513)"));
map.insert("BAJAJ", Regex::new(r"^(203040)"));
map.insert("CartesBancaires", Regex::new(r"^(401(005|006|581)|4021(01|02)|403550|405936|406572|41(3849|4819|50(56|59|62|71|74)|6286|65(37|79)|71[7])|420110|423460|43(47(21|22)|50(48|49|50|51|52)|7875|95(09|11|15|39|98)|96(03|18|19|20|22|72))|4424(48|49|50|51|52|57)|448412|4505(19|60)|45(33|56[6-8]|61|62[^3]|6955|7452|7717|93[02379])|46(099|54(76|77)|6258|6575|98[023])|47(4107|71(73|74|86)|72(65|93)|9619)|48(1091|3622|6519)|49(7|83[5-9]|90(0[1-6]|1[0-6]|2[0-3]|3[0-3]|4[0-3]|5[0-2]|68|9[256789]))|5075(89|90|93|94|97)|51(0726|3([0-7]|8[56]|9(00|38))|5214|62(07|36)|72(22|43)|73(65|66)|7502|7647|8101|9920)|52(0993|1662|3718|7429|9227|93(13|14|31)|94(14|21|30|40|47|55|56|[6-9])|9542)|53(0901|10(28|30)|1195|23(4[4-7])|2459|25(09|34|54|56)|3801|41(02|05|11)|50(29|66)|5324|61(07|15)|71(06|12)|8011)|54(2848|5157|9538|98(5[89]))|55(39(79|93)|42(05|60)|4965|7008|88(67|82)|89(29|4[23])|9618|98(09|10))|56(0408|12(0[2-6]|4[134]|5[04678]))|58(17(0[0-7]|15|2[14]|3[16789]|4[0-9]|5[016]|6[269]|7[3789]|8[0-7]|9[017])|55(0[2-5]|7[7-9]|8[0-2])))"));
map
});
let mut no_of_supported_card_networks = 0;
let card_number_str = self.get_card_no();
for (_, regex) in CARD_NETWORK_REGEX.iter() {
let card_regex = match regex.as_ref() {
Ok(regex) => Ok(regex),
Err(_) => Err(report!(ValidationError::InvalidValue {
message: "Invalid regex expression".into(),
})),
}?;
if card_regex.is_match(&card_number_str) {
no_of_supported_card_networks += 1;
if no_of_supported_card_networks > 1 {
break;
}
}
}
Ok(no_of_supported_card_networks > 1)
}
}
impl NetworkToken {
pub fn get_card_isin(&self) -> String {
self.0.peek().chars().take(6).collect::<String>()
}
pub fn get_extended_card_bin(&self) -> String {
self.0.peek().chars().take(8).collect::<String>()
}
pub fn get_card_no(&self) -> String {
self.0.peek().chars().collect::<String>()
}
pub fn get_last4(&self) -> String {
self.0
.peek()
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>()
}
}
impl FromStr for CardNumber {
type Err = CardNumberValidationErr;
fn from_str(card_number: &str) -> Result<Self, Self::Err> {
// Valid test cards for threedsecureio
let valid_test_cards = vec![
"4000100511112003",
"6000100611111203",
"3000100811111072",
"9000100111111111",
];
#[cfg(not(target_arch = "wasm32"))]
let valid_test_cards = match router_env_which() {
Env::Development | Env::Sandbox => valid_test_cards,
Env::Production => vec![],
};
let card_number = card_number.split_whitespace().collect::<String>();
let is_card_valid = sanitize_card_number(&card_number)?;
if valid_test_cards.contains(&card_number.as_str()) || is_card_valid {
Ok(Self(StrongSecret::new(card_number)))
} else {
Err(CardNumberValidationErr("card number invalid"))
}
}
}
impl FromStr for NetworkToken {
type Err = CardNumberValidationErr;
fn from_str(network_token: &str) -> Result<Self, Self::Err> {
// Valid test cards for threedsecureio
let valid_test_network_tokens = vec![
"4000100511112003",
"6000100611111203",
"3000100811111072",
"9000100111111111",
];
#[cfg(not(target_arch = "wasm32"))]
let valid_test_network_tokens = match router_env_which() {
Env::Development | Env::Sandbox => valid_test_network_tokens,
Env::Production => vec![],
};
let network_token = network_token.split_whitespace().collect::<String>();
let is_network_token_valid = sanitize_card_number(&network_token)?;
if valid_test_network_tokens.contains(&network_token.as_str()) || is_network_token_valid {
Ok(Self(StrongSecret::new(network_token)))
} else {
Err(CardNumberValidationErr("network token invalid"))
}
}
}
pub fn sanitize_card_number(card_number: &str) -> Result<bool, CardNumberValidationErr> {
let is_card_number_valid = Ok(card_number)
.and_then(validate_card_number_chars)
.and_then(validate_card_number_length)
.map(|number| luhn(&number))?;
Ok(is_card_number_valid)
}
/// # Panics
///
/// Never, as a single character will never be greater than 10, or `u8`
pub fn validate_card_number_chars(number: &str) -> Result<Vec<u8>, CardNumberValidationErr> {
let data = number.chars().try_fold(
Vec::with_capacity(MAX_CARD_NUMBER_LENGTH),
|mut data, character| {
data.push(
#[allow(clippy::expect_used)]
character
.to_digit(10)
.ok_or(CardNumberValidationErr(
"invalid character found in card number",
))?
.try_into()
.expect("error while converting a single character to u8"), // safety, a single character will never be greater `u8`
);
Ok::<Vec<u8>, CardNumberValidationErr>(data)
},
)?;
Ok(data)
}
pub fn validate_card_number_length(number: Vec<u8>) -> Result<Vec<u8>, CardNumberValidationErr> {
if number.len() >= MIN_CARD_NUMBER_LENGTH && number.len() <= MAX_CARD_NUMBER_LENGTH {
Ok(number)
} else {
Err(CardNumberValidationErr("invalid card number length"))
}
}
#[allow(clippy::as_conversions)]
pub fn luhn(number: &[u8]) -> bool {
number
.iter()
.rev()
.enumerate()
.map(|(idx, element)| {
((*element * 2) / 10 + (*element * 2) % 10) * ((idx as u8) % 2)
+ (*element) * (((idx + 1) as u8) % 2)
})
.sum::<u8>()
% 10
== 0
}
impl TryFrom<String> for CardNumber {
type Error = CardNumberValidationErr;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_str(&value)
}
}
impl TryFrom<String> for NetworkToken {
type Error = CardNumberValidationErr;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_str(&value)
}
}
impl Deref for CardNumber {
type Target = StrongSecret<String, CardNumberStrategy>;
fn deref(&self) -> &StrongSecret<String, CardNumberStrategy> {
&self.0
}
}
impl Deref for NetworkToken {
type Target = StrongSecret<String, CardNumberStrategy>;
fn deref(&self) -> &StrongSecret<String, CardNumberStrategy> {
&self.0
}
}
impl<'de> Deserialize<'de> for CardNumber {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
impl<'de> Deserialize<'de> for NetworkToken {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
pub enum CardNumberStrategy {}
impl<T> Strategy<T> for CardNumberStrategy
where
T: AsRef<str>,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
if val_str.len() < 15 || val_str.len() > 19 {
return WithType::fmt(val, f);
}
if let Some(value) = val_str.get(..6) {
write!(f, "{}{}", value, "*".repeat(val_str.len() - 6))
} else {
#[cfg(not(target_arch = "wasm32"))]
logger::error!("Invalid card number {val_str}");
WithType::fmt(val, f)
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use masking::Secret;
use super::*;
#[test]
fn valid_card_number() {
let s = "371449635398431";
assert_eq!(
CardNumber::from_str(s).unwrap(),
CardNumber(StrongSecret::from_str(s).unwrap())
);
}
#[test]
fn invalid_card_number_length() {
let s = "371446";
assert_eq!(
CardNumber::from_str(s).unwrap_err().to_string(),
"invalid card number length".to_string()
);
}
#[test]
fn card_number_with_non_digit_character() {
let s = "371446431 A";
assert_eq!(
CardNumber::from_str(s).unwrap_err().to_string(),
"invalid character found in card number".to_string()
);
}
#[test]
fn invalid_card_number() {
let s = "371446431";
assert_eq!(
CardNumber::from_str(s).unwrap_err().to_string(),
"card number invalid".to_string()
);
}
#[test]
fn card_number_no_whitespace() {
let s = "3714 4963 5398 431";
assert_eq!(
CardNumber::from_str(s).unwrap().to_string(),
"371449*********"
);
}
#[test]
fn test_valid_card_number_masking() {
let secret: Secret<String, CardNumberStrategy> =
Secret::new("1234567890987654".to_string());
assert_eq!("123456**********", format!("{secret:?}"));
}
#[test]
fn test_invalid_card_number_masking() {
let secret: Secret<String, CardNumberStrategy> = Secret::new("9123456789".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
#[test]
fn test_valid_card_number_strong_secret_masking() {
let card_number = CardNumber::from_str("3714 4963 5398 431").unwrap();
let secret = &(*card_number);
assert_eq!("371449*********", format!("{secret:?}"));
}
#[test]
fn test_valid_card_number_deserialization() {
let card_number = serde_json::from_str::<CardNumber>(r#""3714 4963 5398 431""#).unwrap();
let secret = card_number.to_string();
assert_eq!(r#""371449*********""#, format!("{secret:?}"));
}
#[test]
fn test_invalid_card_number_deserialization() {
let card_number = serde_json::from_str::<CardNumber>(r#""1234 5678""#);
let error_msg = card_number.unwrap_err().to_string();
assert_eq!(error_msg, "card number invalid".to_string());
}
}
</file>
|
{
"crate": "cards",
"file": "crates/cards/src/validate.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4508
}
|
large_file_-4304266706455125811
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: currency_conversion
File: crates/currency_conversion/src/types.rs
</path>
<file>
use std::collections::HashMap;
use common_enums::Currency;
use rust_decimal::Decimal;
use rusty_money::iso;
use crate::error::CurrencyConversionError;
/// Cached currency store of base currency
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExchangeRates {
pub base_currency: Currency,
pub conversion: HashMap<Currency, CurrencyFactors>,
}
/// Stores the multiplicative factor for conversion between currency to base and vice versa
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CurrencyFactors {
/// The factor that will be multiplied to provide Currency output
pub to_factor: Decimal,
/// The factor that will be multiplied to provide for the base output
pub from_factor: Decimal,
}
impl CurrencyFactors {
pub fn new(to_factor: Decimal, from_factor: Decimal) -> Self {
Self {
to_factor,
from_factor,
}
}
}
impl ExchangeRates {
pub fn new(base_currency: Currency, conversion: HashMap<Currency, CurrencyFactors>) -> Self {
Self {
base_currency,
conversion,
}
}
/// The flow here is from_currency -> base_currency -> to_currency
/// from to_currency -> base currency
pub fn forward_conversion(
&self,
amt: Decimal,
from_currency: Currency,
) -> Result<Decimal, CurrencyConversionError> {
let from_factor = self
.conversion
.get(&from_currency)
.ok_or_else(|| {
CurrencyConversionError::ConversionNotSupported(from_currency.to_string())
})?
.from_factor;
amt.checked_mul(from_factor)
.ok_or(CurrencyConversionError::DecimalMultiplicationFailed)
}
/// from base_currency -> to_currency
pub fn backward_conversion(
&self,
amt: Decimal,
to_currency: Currency,
) -> Result<Decimal, CurrencyConversionError> {
let to_factor = self
.conversion
.get(&to_currency)
.ok_or_else(|| {
CurrencyConversionError::ConversionNotSupported(to_currency.to_string())
})?
.to_factor;
amt.checked_mul(to_factor)
.ok_or(CurrencyConversionError::DecimalMultiplicationFailed)
}
}
pub fn currency_match(currency: Currency) -> &'static iso::Currency {
match currency {
Currency::AED => iso::AED,
Currency::AFN => iso::AFN,
Currency::ALL => iso::ALL,
Currency::AMD => iso::AMD,
Currency::ANG => iso::ANG,
Currency::AOA => iso::AOA,
Currency::ARS => iso::ARS,
Currency::AUD => iso::AUD,
Currency::AWG => iso::AWG,
Currency::AZN => iso::AZN,
Currency::BAM => iso::BAM,
Currency::BBD => iso::BBD,
Currency::BDT => iso::BDT,
Currency::BGN => iso::BGN,
Currency::BHD => iso::BHD,
Currency::BIF => iso::BIF,
Currency::BMD => iso::BMD,
Currency::BND => iso::BND,
Currency::BOB => iso::BOB,
Currency::BRL => iso::BRL,
Currency::BSD => iso::BSD,
Currency::BTN => iso::BTN,
Currency::BWP => iso::BWP,
Currency::BYN => iso::BYN,
Currency::BZD => iso::BZD,
Currency::CAD => iso::CAD,
Currency::CDF => iso::CDF,
Currency::CHF => iso::CHF,
Currency::CLF => iso::CLF,
Currency::CLP => iso::CLP,
Currency::CNY => iso::CNY,
Currency::COP => iso::COP,
Currency::CRC => iso::CRC,
Currency::CUC => iso::CUC,
Currency::CUP => iso::CUP,
Currency::CVE => iso::CVE,
Currency::CZK => iso::CZK,
Currency::DJF => iso::DJF,
Currency::DKK => iso::DKK,
Currency::DOP => iso::DOP,
Currency::DZD => iso::DZD,
Currency::EGP => iso::EGP,
Currency::ERN => iso::ERN,
Currency::ETB => iso::ETB,
Currency::EUR => iso::EUR,
Currency::FJD => iso::FJD,
Currency::FKP => iso::FKP,
Currency::GBP => iso::GBP,
Currency::GEL => iso::GEL,
Currency::GHS => iso::GHS,
Currency::GIP => iso::GIP,
Currency::GMD => iso::GMD,
Currency::GNF => iso::GNF,
Currency::GTQ => iso::GTQ,
Currency::GYD => iso::GYD,
Currency::HKD => iso::HKD,
Currency::HNL => iso::HNL,
Currency::HRK => iso::HRK,
Currency::HTG => iso::HTG,
Currency::HUF => iso::HUF,
Currency::IDR => iso::IDR,
Currency::ILS => iso::ILS,
Currency::INR => iso::INR,
Currency::IQD => iso::IQD,
Currency::IRR => iso::IRR,
Currency::ISK => iso::ISK,
Currency::JMD => iso::JMD,
Currency::JOD => iso::JOD,
Currency::JPY => iso::JPY,
Currency::KES => iso::KES,
Currency::KGS => iso::KGS,
Currency::KHR => iso::KHR,
Currency::KMF => iso::KMF,
Currency::KPW => iso::KPW,
Currency::KRW => iso::KRW,
Currency::KWD => iso::KWD,
Currency::KYD => iso::KYD,
Currency::KZT => iso::KZT,
Currency::LAK => iso::LAK,
Currency::LBP => iso::LBP,
Currency::LKR => iso::LKR,
Currency::LRD => iso::LRD,
Currency::LSL => iso::LSL,
Currency::LYD => iso::LYD,
Currency::MAD => iso::MAD,
Currency::MDL => iso::MDL,
Currency::MGA => iso::MGA,
Currency::MKD => iso::MKD,
Currency::MMK => iso::MMK,
Currency::MNT => iso::MNT,
Currency::MOP => iso::MOP,
Currency::MRU => iso::MRU,
Currency::MUR => iso::MUR,
Currency::MVR => iso::MVR,
Currency::MWK => iso::MWK,
Currency::MXN => iso::MXN,
Currency::MYR => iso::MYR,
Currency::MZN => iso::MZN,
Currency::NAD => iso::NAD,
Currency::NGN => iso::NGN,
Currency::NIO => iso::NIO,
Currency::NOK => iso::NOK,
Currency::NPR => iso::NPR,
Currency::NZD => iso::NZD,
Currency::OMR => iso::OMR,
Currency::PAB => iso::PAB,
Currency::PEN => iso::PEN,
Currency::PGK => iso::PGK,
Currency::PHP => iso::PHP,
Currency::PKR => iso::PKR,
Currency::PLN => iso::PLN,
Currency::PYG => iso::PYG,
Currency::QAR => iso::QAR,
Currency::RON => iso::RON,
Currency::RSD => iso::RSD,
Currency::RUB => iso::RUB,
Currency::RWF => iso::RWF,
Currency::SAR => iso::SAR,
Currency::SBD => iso::SBD,
Currency::SCR => iso::SCR,
Currency::SDG => iso::SDG,
Currency::SEK => iso::SEK,
Currency::SGD => iso::SGD,
Currency::SHP => iso::SHP,
Currency::SLE => iso::SLE,
Currency::SLL => iso::SLL,
Currency::SOS => iso::SOS,
Currency::SRD => iso::SRD,
Currency::SSP => iso::SSP,
Currency::STD => iso::STD,
Currency::STN => iso::STN,
Currency::SVC => iso::SVC,
Currency::SYP => iso::SYP,
Currency::SZL => iso::SZL,
Currency::THB => iso::THB,
Currency::TJS => iso::TJS,
Currency::TND => iso::TND,
Currency::TMT => iso::TMT,
Currency::TOP => iso::TOP,
Currency::TTD => iso::TTD,
Currency::TRY => iso::TRY,
Currency::TWD => iso::TWD,
Currency::TZS => iso::TZS,
Currency::UAH => iso::UAH,
Currency::UGX => iso::UGX,
Currency::USD => iso::USD,
Currency::UYU => iso::UYU,
Currency::UZS => iso::UZS,
Currency::VES => iso::VES,
Currency::VND => iso::VND,
Currency::VUV => iso::VUV,
Currency::WST => iso::WST,
Currency::XAF => iso::XAF,
Currency::XCD => iso::XCD,
Currency::XOF => iso::XOF,
Currency::XPF => iso::XPF,
Currency::YER => iso::YER,
Currency::ZAR => iso::ZAR,
Currency::ZMW => iso::ZMW,
Currency::ZWL => iso::ZWL,
}
}
</file>
|
{
"crate": "currency_conversion",
"file": "crates/currency_conversion/src/types.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2216
}
|
large_file_-4001597350976964296
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/schema_v2.rs
</path>
<file>
// @generated automatically by Diesel CLI.
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
address (address_id) {
#[max_length = 64]
address_id -> Varchar,
#[max_length = 128]
city -> Nullable<Varchar>,
country -> Nullable<CountryAlpha2>,
line1 -> Nullable<Bytea>,
line2 -> Nullable<Bytea>,
line3 -> Nullable<Bytea>,
state -> Nullable<Bytea>,
zip -> Nullable<Bytea>,
first_name -> Nullable<Bytea>,
last_name -> Nullable<Bytea>,
phone_number -> Nullable<Bytea>,
#[max_length = 8]
country_code -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
email -> Nullable<Bytea>,
origin_zip -> Nullable<Bytea>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
api_keys (key_id) {
#[max_length = 64]
key_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
name -> Varchar,
#[max_length = 256]
description -> Nullable<Varchar>,
#[max_length = 128]
hashed_api_key -> Varchar,
#[max_length = 16]
prefix -> Varchar,
created_at -> Timestamp,
expires_at -> Nullable<Timestamp>,
last_used -> Nullable<Timestamp>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
authentication (authentication_id) {
#[max_length = 64]
authentication_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
authentication_connector -> Nullable<Varchar>,
#[max_length = 64]
connector_authentication_id -> Nullable<Varchar>,
authentication_data -> Nullable<Jsonb>,
#[max_length = 64]
payment_method_id -> Varchar,
#[max_length = 64]
authentication_type -> Nullable<Varchar>,
#[max_length = 64]
authentication_status -> Varchar,
#[max_length = 64]
authentication_lifecycle_status -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
error_message -> Nullable<Text>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
connector_metadata -> Nullable<Jsonb>,
maximum_supported_version -> Nullable<Jsonb>,
#[max_length = 64]
threeds_server_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
cavv -> Nullable<Varchar>,
#[max_length = 64]
authentication_flow_type -> Nullable<Varchar>,
message_version -> Nullable<Jsonb>,
#[max_length = 64]
eci -> Nullable<Varchar>,
#[max_length = 64]
trans_status -> Nullable<Varchar>,
#[max_length = 64]
acquirer_bin -> Nullable<Varchar>,
#[max_length = 64]
acquirer_merchant_id -> Nullable<Varchar>,
three_ds_method_data -> Nullable<Varchar>,
three_ds_method_url -> Nullable<Varchar>,
acs_url -> Nullable<Varchar>,
challenge_request -> Nullable<Varchar>,
acs_reference_number -> Nullable<Varchar>,
acs_trans_id -> Nullable<Varchar>,
acs_signed_content -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 255]
payment_id -> Nullable<Varchar>,
#[max_length = 128]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
ds_trans_id -> Nullable<Varchar>,
#[max_length = 128]
directory_server_id -> Nullable<Varchar>,
#[max_length = 64]
acquirer_country_code -> Nullable<Varchar>,
service_details -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 128]
authentication_client_secret -> Nullable<Varchar>,
force_3ds_challenge -> Nullable<Bool>,
psd2_sca_exemption_type -> Nullable<ScaExemptionType>,
#[max_length = 2048]
return_url -> Nullable<Varchar>,
amount -> Nullable<Int8>,
currency -> Nullable<Currency>,
billing_address -> Nullable<Bytea>,
shipping_address -> Nullable<Bytea>,
browser_info -> Nullable<Jsonb>,
email -> Nullable<Bytea>,
#[max_length = 128]
profile_acquirer_id -> Nullable<Varchar>,
challenge_code -> Nullable<Varchar>,
challenge_cancel -> Nullable<Varchar>,
challenge_code_reason -> Nullable<Varchar>,
message_extension -> Nullable<Jsonb>,
#[max_length = 255]
challenge_request_key -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist (merchant_id, fingerprint_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_fingerprint (id) {
id -> Int4,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
encrypted_fingerprint -> Text,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_lookup (id) {
id -> Int4,
#[max_length = 64]
merchant_id -> Varchar,
fingerprint -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
business_profile (id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_name -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
return_url -> Nullable<Text>,
enable_payment_response_hash -> Bool,
#[max_length = 255]
payment_response_hash_key -> Nullable<Varchar>,
redirect_to_merchant_with_http_post -> Bool,
webhook_details -> Nullable<Json>,
metadata -> Nullable<Json>,
is_recon_enabled -> Bool,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
payment_link_config -> Nullable<Jsonb>,
session_expiry -> Nullable<Int8>,
authentication_connector_details -> Nullable<Jsonb>,
payout_link_config -> Nullable<Jsonb>,
is_extended_card_info_enabled -> Nullable<Bool>,
extended_card_info_config -> Nullable<Jsonb>,
is_connector_agnostic_mit_enabled -> Nullable<Bool>,
use_billing_as_payment_method_billing -> Nullable<Bool>,
collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
collect_billing_details_from_wallet_connector -> Nullable<Bool>,
outgoing_webhook_custom_http_headers -> Nullable<Bytea>,
always_collect_billing_details_from_wallet_connector -> Nullable<Bool>,
always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
#[max_length = 64]
tax_connector_id -> Nullable<Varchar>,
is_tax_connector_enabled -> Nullable<Bool>,
version -> ApiVersion,
dynamic_routing_algorithm -> Nullable<Json>,
is_network_tokenization_enabled -> Bool,
is_auto_retries_enabled -> Nullable<Bool>,
max_auto_retries_enabled -> Nullable<Int2>,
always_request_extended_authorization -> Nullable<Bool>,
is_click_to_pay_enabled -> Bool,
authentication_product_ids -> Nullable<Jsonb>,
card_testing_guard_config -> Nullable<Jsonb>,
card_testing_secret_key -> Nullable<Bytea>,
is_clear_pan_retries_enabled -> Bool,
force_3ds_challenge -> Nullable<Bool>,
is_debit_routing_enabled -> Bool,
merchant_business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
id -> Varchar,
is_iframe_redirection_enabled -> Nullable<Bool>,
three_ds_decision_rule_algorithm -> Nullable<Jsonb>,
acquirer_config_map -> Nullable<Jsonb>,
#[max_length = 16]
merchant_category_code -> Nullable<Varchar>,
#[max_length = 32]
merchant_country_code -> Nullable<Varchar>,
dispute_polling_interval -> Nullable<Int4>,
is_manual_retry_enabled -> Nullable<Bool>,
always_enable_overcapture -> Nullable<Bool>,
#[max_length = 64]
billing_processor_id -> Nullable<Varchar>,
is_external_vault_enabled -> Nullable<Bool>,
external_vault_connector_details -> Nullable<Jsonb>,
is_l2_l3_enabled -> Nullable<Bool>,
#[max_length = 64]
routing_algorithm_id -> Nullable<Varchar>,
order_fulfillment_time -> Nullable<Int8>,
order_fulfillment_time_origin -> Nullable<OrderFulfillmentTimeOrigin>,
#[max_length = 64]
frm_routing_algorithm_id -> Nullable<Varchar>,
#[max_length = 64]
payout_routing_algorithm_id -> Nullable<Varchar>,
default_fallback_routing -> Nullable<Jsonb>,
three_ds_decision_manager_config -> Nullable<Jsonb>,
should_collect_cvv_during_payment -> Nullable<Bool>,
revenue_recovery_retry_algorithm_type -> Nullable<RevenueRecoveryAlgorithmType>,
revenue_recovery_retry_algorithm_data -> Nullable<Jsonb>,
#[max_length = 16]
split_txns_enabled -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
callback_mapper (id, type_) {
#[max_length = 128]
id -> Varchar,
#[sql_name = "type"]
#[max_length = 64]
type_ -> Varchar,
data -> Jsonb,
created_at -> Timestamp,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
captures (capture_id) {
#[max_length = 64]
capture_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
status -> CaptureStatus,
amount -> Int8,
currency -> Nullable<Currency>,
#[max_length = 255]
connector -> Varchar,
#[max_length = 255]
error_message -> Nullable<Varchar>,
#[max_length = 255]
error_code -> Nullable<Varchar>,
#[max_length = 255]
error_reason -> Nullable<Varchar>,
tax_amount -> Nullable<Int8>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
authorized_attempt_id -> Varchar,
#[max_length = 128]
connector_capture_id -> Nullable<Varchar>,
capture_sequence -> Int2,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
processor_capture_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
cards_info (card_iin) {
#[max_length = 16]
card_iin -> Varchar,
card_issuer -> Nullable<Text>,
card_network -> Nullable<Text>,
card_type -> Nullable<Text>,
card_subtype -> Nullable<Text>,
card_issuing_country -> Nullable<Text>,
#[max_length = 32]
bank_code_id -> Nullable<Varchar>,
#[max_length = 32]
bank_code -> Nullable<Varchar>,
#[max_length = 32]
country_code -> Nullable<Varchar>,
date_created -> Timestamp,
last_updated -> Nullable<Timestamp>,
last_updated_provider -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
configs (key) {
id -> Int4,
#[max_length = 255]
key -> Varchar,
config -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
customers (id) {
#[max_length = 64]
merchant_id -> Varchar,
name -> Nullable<Bytea>,
email -> Nullable<Bytea>,
phone -> Nullable<Bytea>,
#[max_length = 8]
phone_country_code -> Nullable<Varchar>,
#[max_length = 255]
description -> Nullable<Varchar>,
created_at -> Timestamp,
metadata -> Nullable<Json>,
connector_customer -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
default_payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
version -> ApiVersion,
tax_registration_id -> Nullable<Bytea>,
#[max_length = 64]
merchant_reference_id -> Nullable<Varchar>,
default_billing_address -> Nullable<Bytea>,
default_shipping_address -> Nullable<Bytea>,
status -> Nullable<DeleteStatus>,
#[max_length = 64]
id -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dashboard_metadata (id) {
id -> Int4,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
org_id -> Varchar,
data_key -> DashboardMetadata,
data_value -> Json,
#[max_length = 64]
created_by -> Varchar,
created_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dispute (dispute_id) {
#[max_length = 64]
dispute_id -> Varchar,
#[max_length = 255]
amount -> Varchar,
#[max_length = 255]
currency -> Varchar,
dispute_stage -> DisputeStage,
dispute_status -> DisputeStatus,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
connector_status -> Varchar,
#[max_length = 255]
connector_dispute_id -> Varchar,
#[max_length = 255]
connector_reason -> Nullable<Varchar>,
#[max_length = 255]
connector_reason_code -> Nullable<Varchar>,
challenge_required_by -> Nullable<Timestamp>,
connector_created_at -> Nullable<Timestamp>,
connector_updated_at -> Nullable<Timestamp>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 255]
connector -> Varchar,
evidence -> Jsonb,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
dispute_amount -> Int8,
#[max_length = 32]
organization_id -> Varchar,
dispute_currency -> Nullable<Currency>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dynamic_routing_stats (attempt_id, merchant_id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
amount -> Int8,
#[max_length = 64]
success_based_routing_connector -> Varchar,
#[max_length = 64]
payment_connector -> Varchar,
currency -> Nullable<Currency>,
#[max_length = 64]
payment_method -> Nullable<Varchar>,
capture_method -> Nullable<CaptureMethod>,
authentication_type -> Nullable<AuthenticationType>,
payment_status -> AttemptStatus,
conclusive_classification -> SuccessBasedRoutingConclusiveState,
created_at -> Timestamp,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
#[max_length = 64]
global_success_based_connector -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
events (event_id) {
#[max_length = 64]
event_id -> Varchar,
event_type -> EventType,
event_class -> EventClass,
is_webhook_notified -> Bool,
#[max_length = 64]
primary_object_id -> Varchar,
primary_object_type -> EventObjectType,
created_at -> Timestamp,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
business_profile_id -> Nullable<Varchar>,
primary_object_created_at -> Nullable<Timestamp>,
#[max_length = 64]
idempotent_event_id -> Nullable<Varchar>,
#[max_length = 64]
initial_attempt_id -> Nullable<Varchar>,
request -> Nullable<Bytea>,
response -> Nullable<Bytea>,
delivery_attempt -> Nullable<WebhookDeliveryAttempt>,
metadata -> Nullable<Jsonb>,
is_overall_delivery_successful -> Nullable<Bool>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
file_metadata (file_id, merchant_id) {
#[max_length = 64]
file_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
file_name -> Nullable<Varchar>,
file_size -> Int4,
#[max_length = 255]
file_type -> Varchar,
#[max_length = 255]
provider_file_id -> Nullable<Varchar>,
#[max_length = 255]
file_upload_provider -> Nullable<Varchar>,
available -> Bool,
created_at -> Timestamp,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
fraud_check (frm_id, attempt_id, payment_id, merchant_id) {
#[max_length = 64]
frm_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
created_at -> Timestamp,
#[max_length = 255]
frm_name -> Varchar,
#[max_length = 255]
frm_transaction_id -> Nullable<Varchar>,
frm_transaction_type -> FraudCheckType,
frm_status -> FraudCheckStatus,
frm_score -> Nullable<Int4>,
frm_reason -> Nullable<Jsonb>,
#[max_length = 255]
frm_error -> Nullable<Varchar>,
payment_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
last_step -> Varchar,
payment_capture_method -> Nullable<CaptureMethod>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
gateway_status_map (connector, flow, sub_flow, code, message) {
#[max_length = 64]
connector -> Varchar,
#[max_length = 64]
flow -> Varchar,
#[max_length = 64]
sub_flow -> Varchar,
#[max_length = 255]
code -> Varchar,
#[max_length = 1024]
message -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 64]
router_error -> Nullable<Varchar>,
#[max_length = 64]
decision -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
step_up_possible -> Bool,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
#[max_length = 64]
error_category -> Nullable<Varchar>,
clear_pan_possible -> Bool,
feature_data -> Nullable<Jsonb>,
#[max_length = 64]
feature -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
generic_link (link_id) {
#[max_length = 64]
link_id -> Varchar,
#[max_length = 64]
primary_reference -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
created_at -> Timestamp,
last_modified_at -> Timestamp,
expiry -> Timestamp,
link_data -> Jsonb,
link_status -> Jsonb,
link_type -> GenericLinkType,
url -> Text,
return_url -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction_default (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
incremental_authorization (authorization_id, merchant_id) {
#[max_length = 64]
authorization_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
amount -> Int8,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
status -> Varchar,
#[max_length = 255]
error_code -> Nullable<Varchar>,
error_message -> Nullable<Text>,
#[max_length = 64]
connector_authorization_id -> Nullable<Varchar>,
previously_authorized_amount -> Int8,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
invoice (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 128]
subscription_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 128]
merchant_connector_id -> Varchar,
#[max_length = 64]
payment_intent_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
customer_id -> Varchar,
amount -> Int8,
#[max_length = 3]
currency -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 128]
provider_name -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
connector_invoice_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
locker_mock_up (id) {
id -> Int4,
#[max_length = 255]
card_id -> Varchar,
#[max_length = 255]
external_id -> Varchar,
#[max_length = 255]
card_fingerprint -> Varchar,
#[max_length = 255]
card_global_fingerprint -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
card_number -> Varchar,
#[max_length = 255]
card_exp_year -> Varchar,
#[max_length = 255]
card_exp_month -> Varchar,
#[max_length = 255]
name_on_card -> Nullable<Varchar>,
#[max_length = 255]
nickname -> Nullable<Varchar>,
#[max_length = 255]
customer_id -> Nullable<Varchar>,
duplicate -> Nullable<Bool>,
#[max_length = 8]
card_cvc -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
enc_card_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
mandate (mandate_id) {
#[max_length = 64]
mandate_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_method_id -> Varchar,
mandate_status -> MandateStatus,
mandate_type -> MandateType,
customer_accepted_at -> Nullable<Timestamp>,
#[max_length = 64]
customer_ip_address -> Nullable<Varchar>,
#[max_length = 255]
customer_user_agent -> Nullable<Varchar>,
#[max_length = 128]
network_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
previous_attempt_id -> Nullable<Varchar>,
created_at -> Timestamp,
mandate_amount -> Nullable<Int8>,
mandate_currency -> Nullable<Currency>,
amount_captured -> Nullable<Int8>,
#[max_length = 64]
connector -> Varchar,
#[max_length = 128]
connector_mandate_id -> Nullable<Varchar>,
start_date -> Nullable<Timestamp>,
end_date -> Nullable<Timestamp>,
metadata -> Nullable<Jsonb>,
connector_mandate_ids -> Nullable<Jsonb>,
#[max_length = 64]
original_payment_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
#[max_length = 2048]
customer_user_agent_extended -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_account (id) {
merchant_name -> Nullable<Bytea>,
merchant_details -> Nullable<Bytea>,
#[max_length = 128]
publishable_key -> Nullable<Varchar>,
storage_scheme -> MerchantStorageScheme,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 32]
organization_id -> Varchar,
recon_status -> ReconStatus,
version -> ApiVersion,
is_platform_account -> Bool,
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
product_type -> Nullable<Varchar>,
#[max_length = 64]
merchant_account_type -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_connector_account (id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
connector_name -> Varchar,
connector_account_details -> Bytea,
disabled -> Nullable<Bool>,
payment_methods_enabled -> Nullable<Array<Nullable<Json>>>,
connector_type -> ConnectorType,
metadata -> Nullable<Jsonb>,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
connector_webhook_details -> Nullable<Jsonb>,
frm_config -> Nullable<Array<Nullable<Jsonb>>>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
pm_auth_config -> Nullable<Jsonb>,
status -> ConnectorStatus,
additional_merchant_data -> Nullable<Bytea>,
connector_wallets_details -> Nullable<Bytea>,
version -> ApiVersion,
#[max_length = 64]
id -> Varchar,
feature_metadata -> Nullable<Jsonb>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_key_store (merchant_id) {
#[max_length = 64]
merchant_id -> Varchar,
key -> Bytea,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
organization (id) {
organization_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 32]
id -> Varchar,
organization_name -> Nullable<Text>,
version -> ApiVersion,
#[max_length = 64]
organization_type -> Nullable<Varchar>,
#[max_length = 64]
platform_merchant_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_attempt (id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
status -> AttemptStatus,
#[max_length = 64]
connector -> Nullable<Varchar>,
error_message -> Nullable<Text>,
surcharge_amount -> Nullable<Int8>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
authentication_type -> Nullable<AuthenticationType>,
created_at -> Timestamp,
modified_at -> Timestamp,
last_synced -> Nullable<Timestamp>,
#[max_length = 255]
cancellation_reason -> Nullable<Varchar>,
amount_to_capture -> Nullable<Int8>,
browser_info -> Nullable<Jsonb>,
#[max_length = 255]
error_code -> Nullable<Varchar>,
#[max_length = 128]
payment_token -> Nullable<Varchar>,
connector_metadata -> Nullable<Jsonb>,
#[max_length = 50]
payment_experience -> Nullable<Varchar>,
payment_method_data -> Nullable<Jsonb>,
preprocessing_step_id -> Nullable<Varchar>,
error_reason -> Nullable<Text>,
multiple_capture_count -> Nullable<Int2>,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
amount_capturable -> Int8,
#[max_length = 32]
updated_by -> Varchar,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
encoded_data -> Nullable<Text>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
net_amount -> Nullable<Int8>,
external_three_ds_authentication_attempted -> Nullable<Bool>,
#[max_length = 64]
authentication_connector -> Nullable<Varchar>,
#[max_length = 64]
authentication_id -> Nullable<Varchar>,
#[max_length = 64]
fingerprint_id -> Nullable<Varchar>,
#[max_length = 64]
client_source -> Nullable<Varchar>,
#[max_length = 64]
client_version -> Nullable<Varchar>,
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 32]
card_network -> Nullable<Varchar>,
shipping_cost -> Nullable<Int8>,
order_tax_amount -> Nullable<Int8>,
request_extended_authorization -> Nullable<Bool>,
extended_authorization_applied -> Nullable<Bool>,
capture_before -> Nullable<Timestamp>,
card_discovery -> Nullable<CardDiscovery>,
charges -> Nullable<Jsonb>,
#[max_length = 64]
processor_merchant_id -> Nullable<Varchar>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
#[max_length = 255]
connector_request_reference_id -> Nullable<Varchar>,
#[max_length = 255]
network_transaction_id -> Nullable<Varchar>,
is_overcapture_enabled -> Nullable<Bool>,
network_details -> Nullable<Jsonb>,
is_stored_credential -> Nullable<Bool>,
authorized_amount -> Nullable<Int8>,
payment_method_type_v2 -> Nullable<Varchar>,
#[max_length = 128]
connector_payment_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_subtype -> Varchar,
routing_result -> Nullable<Jsonb>,
authentication_applied -> Nullable<AuthenticationType>,
#[max_length = 128]
external_reference_id -> Nullable<Varchar>,
tax_on_surcharge -> Nullable<Int8>,
payment_method_billing_address -> Nullable<Bytea>,
redirection_data -> Nullable<Jsonb>,
connector_payment_data -> Nullable<Text>,
connector_token_details -> Nullable<Jsonb>,
#[max_length = 64]
id -> Varchar,
feature_metadata -> Nullable<Jsonb>,
#[max_length = 32]
network_advice_code -> Nullable<Varchar>,
#[max_length = 32]
network_decline_code -> Nullable<Varchar>,
network_error_message -> Nullable<Text>,
#[max_length = 64]
attempts_group_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_intent (id) {
#[max_length = 64]
merchant_id -> Varchar,
status -> IntentStatus,
amount -> Int8,
currency -> Nullable<Currency>,
amount_captured -> Nullable<Int8>,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 255]
return_url -> Nullable<Varchar>,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
last_synced -> Nullable<Timestamp>,
setup_future_usage -> Nullable<FutureUsage>,
#[max_length = 64]
active_attempt_id -> Nullable<Varchar>,
order_details -> Nullable<Array<Nullable<Jsonb>>>,
allowed_payment_method_types -> Nullable<Json>,
connector_metadata -> Nullable<Json>,
feature_metadata -> Nullable<Json>,
attempt_count -> Int2,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 255]
payment_link_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
surcharge_applicable -> Nullable<Bool>,
request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>,
authorization_count -> Nullable<Int4>,
session_expiry -> Nullable<Timestamp>,
request_external_three_ds_authentication -> Nullable<Bool>,
frm_metadata -> Nullable<Jsonb>,
customer_details -> Nullable<Bytea>,
shipping_cost -> Nullable<Int8>,
#[max_length = 32]
organization_id -> Varchar,
tax_details -> Nullable<Jsonb>,
skip_external_tax_calculation -> Nullable<Bool>,
request_extended_authorization -> Nullable<Bool>,
psd2_sca_exemption_type -> Nullable<ScaExemptionType>,
split_payments -> Nullable<Jsonb>,
#[max_length = 64]
platform_merchant_id -> Nullable<Varchar>,
force_3ds_challenge -> Nullable<Bool>,
force_3ds_challenge_trigger -> Nullable<Bool>,
#[max_length = 64]
processor_merchant_id -> Nullable<Varchar>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
is_iframe_redirection_enabled -> Nullable<Bool>,
is_payment_id_from_merchant -> Nullable<Bool>,
#[max_length = 64]
payment_channel -> Nullable<Varchar>,
tax_status -> Nullable<Varchar>,
discount_amount -> Nullable<Int8>,
shipping_amount_tax -> Nullable<Int8>,
duty_amount -> Nullable<Int8>,
order_date -> Nullable<Timestamp>,
enable_partial_authorization -> Nullable<Bool>,
enable_overcapture -> Nullable<Bool>,
#[max_length = 64]
mit_category -> Nullable<Varchar>,
#[max_length = 64]
merchant_reference_id -> Nullable<Varchar>,
billing_address -> Nullable<Bytea>,
shipping_address -> Nullable<Bytea>,
capture_method -> Nullable<CaptureMethod>,
authentication_type -> Nullable<AuthenticationType>,
prerouting_algorithm -> Nullable<Jsonb>,
surcharge_amount -> Nullable<Int8>,
tax_on_surcharge -> Nullable<Int8>,
#[max_length = 64]
frm_merchant_decision -> Nullable<Varchar>,
#[max_length = 255]
statement_descriptor -> Nullable<Varchar>,
enable_payment_link -> Nullable<Bool>,
apply_mit_exemption -> Nullable<Bool>,
customer_present -> Nullable<Bool>,
#[max_length = 64]
routing_algorithm_id -> Nullable<Varchar>,
payment_link_config -> Nullable<Jsonb>,
#[max_length = 64]
id -> Varchar,
#[max_length = 16]
split_txns_enabled -> Nullable<Varchar>,
#[max_length = 64]
active_attempts_group_id -> Nullable<Varchar>,
#[max_length = 16]
active_attempt_id_type -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_link (payment_link_id) {
#[max_length = 255]
payment_link_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 255]
link_to_pay -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
amount -> Int8,
currency -> Nullable<Currency>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
fulfilment_time -> Nullable<Timestamp>,
#[max_length = 64]
custom_merchant_name -> Nullable<Varchar>,
payment_link_config -> Nullable<Jsonb>,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 255]
secure_link -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_methods (id) {
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
locker_id -> Nullable<Varchar>,
last_used_at -> Timestamp,
connector_mandate_details -> Nullable<Jsonb>,
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
status -> Varchar,
#[max_length = 255]
network_transaction_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
payment_method_billing_address -> Nullable<Bytea>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
version -> ApiVersion,
#[max_length = 128]
network_token_requestor_reference_id -> Nullable<Varchar>,
#[max_length = 64]
network_token_locker_id -> Nullable<Varchar>,
network_token_payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
external_vault_source -> Nullable<Varchar>,
#[max_length = 64]
vault_type -> Nullable<Varchar>,
#[max_length = 64]
locker_fingerprint_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_type_v2 -> Nullable<Varchar>,
#[max_length = 64]
payment_method_subtype -> Nullable<Varchar>,
#[max_length = 64]
id -> Varchar,
external_vault_token_data -> Nullable<Bytea>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payout_attempt (merchant_id, payout_attempt_id) {
#[max_length = 64]
payout_attempt_id -> Varchar,
#[max_length = 64]
payout_id -> Varchar,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
address_id -> Nullable<Varchar>,
#[max_length = 64]
connector -> Nullable<Varchar>,
#[max_length = 128]
connector_payout_id -> Nullable<Varchar>,
#[max_length = 64]
payout_token -> Nullable<Varchar>,
status -> PayoutStatus,
is_eligible -> Nullable<Bool>,
error_message -> Nullable<Text>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
business_label -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
routing_info -> Nullable<Jsonb>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
additional_payout_method_data -> Nullable<Jsonb>,
#[max_length = 255]
merchant_order_reference_id -> Nullable<Varchar>,
payout_connector_metadata -> Nullable<Jsonb>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payouts (merchant_id, payout_id) {
#[max_length = 64]
payout_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
address_id -> Nullable<Varchar>,
payout_type -> Nullable<PayoutType>,
#[max_length = 64]
payout_method_id -> Nullable<Varchar>,
amount -> Int8,
destination_currency -> Currency,
source_currency -> Currency,
#[max_length = 255]
description -> Nullable<Varchar>,
recurring -> Bool,
auto_fulfill -> Bool,
#[max_length = 255]
return_url -> Nullable<Varchar>,
#[max_length = 64]
entity_type -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
attempt_count -> Int2,
#[max_length = 64]
profile_id -> Varchar,
status -> PayoutStatus,
confirm -> Nullable<Bool>,
#[max_length = 255]
payout_link_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
#[max_length = 32]
priority -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
process_tracker (id) {
#[max_length = 127]
id -> Varchar,
#[max_length = 64]
name -> Nullable<Varchar>,
tag -> Array<Nullable<Text>>,
#[max_length = 64]
runner -> Nullable<Varchar>,
retry_count -> Int4,
schedule_time -> Nullable<Timestamp>,
#[max_length = 255]
rule -> Varchar,
tracking_data -> Json,
#[max_length = 255]
business_status -> Varchar,
status -> ProcessTrackerStatus,
event -> Array<Nullable<Text>>,
created_at -> Timestamp,
updated_at -> Timestamp,
version -> ApiVersion,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
refund (id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 128]
connector_transaction_id -> Varchar,
#[max_length = 64]
connector -> Varchar,
#[max_length = 128]
connector_refund_id -> Nullable<Varchar>,
#[max_length = 64]
external_reference_id -> Nullable<Varchar>,
refund_type -> RefundType,
total_amount -> Int8,
currency -> Currency,
refund_amount -> Int8,
refund_status -> RefundStatus,
sent_to_gateway -> Bool,
refund_error_message -> Nullable<Text>,
metadata -> Nullable<Json>,
#[max_length = 128]
refund_arn -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 255]
refund_reason -> Nullable<Varchar>,
refund_error_code -> Nullable<Text>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
charges -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
split_refunds -> Nullable<Jsonb>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
processor_refund_data -> Nullable<Text>,
processor_transaction_data -> Nullable<Text>,
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
merchant_reference_id -> Nullable<Varchar>,
#[max_length = 64]
connector_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
relay (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 128]
connector_resource_id -> Varchar,
#[max_length = 64]
connector_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
relay_type -> RelayType,
request_data -> Nullable<Jsonb>,
status -> RelayStatus,
#[max_length = 128]
connector_reference_id -> Nullable<Varchar>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
error_message -> Nullable<Text>,
created_at -> Timestamp,
modified_at -> Timestamp,
response_data -> Nullable<Jsonb>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
reverse_lookup (lookup_id) {
#[max_length = 128]
lookup_id -> Varchar,
#[max_length = 128]
sk_id -> Varchar,
#[max_length = 128]
pk_id -> Varchar,
#[max_length = 128]
source -> Varchar,
#[max_length = 32]
updated_by -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
roles (role_id) {
#[max_length = 64]
role_name -> Varchar,
#[max_length = 64]
role_id -> Varchar,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Varchar,
groups -> Array<Nullable<Text>>,
scope -> RoleScope,
created_at -> Timestamp,
#[max_length = 64]
created_by -> Varchar,
last_modified_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
#[max_length = 64]
entity_type -> Varchar,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
tenant_id -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
routing_algorithm (algorithm_id) {
#[max_length = 64]
algorithm_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
name -> Varchar,
#[max_length = 256]
description -> Nullable<Varchar>,
kind -> RoutingAlgorithmKind,
algorithm_data -> Jsonb,
created_at -> Timestamp,
modified_at -> Timestamp,
algorithm_for -> TransactionType,
#[max_length = 64]
decision_engine_routing_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
subscription (id) {
#[max_length = 128]
id -> Varchar,
#[max_length = 128]
status -> Varchar,
#[max_length = 128]
billing_processor -> Nullable<Varchar>,
#[max_length = 128]
payment_method_id -> Nullable<Varchar>,
#[max_length = 128]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
#[max_length = 128]
connector_subscription_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 128]
merchant_reference_id -> Nullable<Varchar>,
#[max_length = 128]
plan_id -> Nullable<Varchar>,
#[max_length = 128]
item_price_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
themes (theme_id) {
#[max_length = 64]
theme_id -> Varchar,
#[max_length = 64]
tenant_id -> Varchar,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
entity_type -> Varchar,
#[max_length = 64]
theme_name -> Varchar,
#[max_length = 64]
email_primary_color -> Varchar,
#[max_length = 64]
email_foreground_color -> Varchar,
#[max_length = 64]
email_background_color -> Varchar,
#[max_length = 64]
email_entity_name -> Varchar,
email_entity_logo_url -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
tokenization (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
created_at -> Timestamp,
updated_at -> Timestamp,
#[max_length = 255]
locker_id -> Varchar,
flag -> TokenizationFlag,
version -> ApiVersion,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
unified_translations (unified_code, unified_message, locale) {
#[max_length = 255]
unified_code -> Varchar,
#[max_length = 1024]
unified_message -> Varchar,
#[max_length = 255]
locale -> Varchar,
#[max_length = 1024]
translation -> Varchar,
created_at -> Timestamp,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_authentication_methods (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
auth_id -> Varchar,
#[max_length = 64]
owner_id -> Varchar,
#[max_length = 64]
owner_type -> Varchar,
#[max_length = 64]
auth_type -> Varchar,
private_config -> Nullable<Bytea>,
public_config -> Nullable<Jsonb>,
allow_signup -> Bool,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
email_domain -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_key_store (user_id) {
#[max_length = 64]
user_id -> Varchar,
key -> Bytea,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_roles (id) {
id -> Int4,
#[max_length = 64]
user_id -> Varchar,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Varchar,
#[max_length = 64]
org_id -> Nullable<Varchar>,
status -> UserStatus,
#[max_length = 64]
created_by -> Varchar,
#[max_length = 64]
last_modified_by -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
entity_id -> Nullable<Varchar>,
#[max_length = 64]
entity_type -> Nullable<Varchar>,
version -> UserRoleVersion,
#[max_length = 64]
tenant_id -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
users (user_id) {
#[max_length = 64]
user_id -> Varchar,
#[max_length = 255]
email -> Varchar,
#[max_length = 255]
name -> Varchar,
#[max_length = 255]
password -> Nullable<Varchar>,
is_verified -> Bool,
created_at -> Timestamp,
last_modified_at -> Timestamp,
totp_status -> TotpStatus,
totp_secret -> Nullable<Bytea>,
totp_recovery_codes -> Nullable<Array<Nullable<Text>>>,
last_password_modified_at -> Nullable<Timestamp>,
lineage_context -> Nullable<Jsonb>,
}
}
diesel::allow_tables_to_appear_in_same_query!(
address,
api_keys,
authentication,
blocklist,
blocklist_fingerprint,
blocklist_lookup,
business_profile,
callback_mapper,
captures,
cards_info,
configs,
customers,
dashboard_metadata,
dispute,
dynamic_routing_stats,
events,
file_metadata,
fraud_check,
gateway_status_map,
generic_link,
hyperswitch_ai_interaction,
hyperswitch_ai_interaction_default,
incremental_authorization,
invoice,
locker_mock_up,
mandate,
merchant_account,
merchant_connector_account,
merchant_key_store,
organization,
payment_attempt,
payment_intent,
payment_link,
payment_methods,
payout_attempt,
payouts,
process_tracker,
refund,
relay,
reverse_lookup,
roles,
routing_algorithm,
subscription,
themes,
tokenization,
unified_translations,
user_authentication_methods,
user_key_store,
user_roles,
users,
);
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/schema_v2.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 13529
}
|
large_file_-716921824394648573
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/kv.rs
</path>
<file>
use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
#[cfg(feature = "v2")]
use crate::payment_attempt::PaymentAttemptUpdateInternal;
#[cfg(feature = "v1")]
use crate::payment_intent::PaymentIntentUpdate;
#[cfg(feature = "v2")]
use crate::payment_intent::PaymentIntentUpdateInternal;
use crate::{
address::{Address, AddressNew, AddressUpdateInternal},
customers::{Customer, CustomerNew, CustomerUpdateInternal},
errors,
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
payment_intent::PaymentIntentNew,
payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate},
payouts::{Payouts, PayoutsNew, PayoutsUpdate},
refund::{Refund, RefundNew, RefundUpdate},
reverse_lookup::{ReverseLookup, ReverseLookupNew},
Mandate, MandateNew, MandateUpdateInternal, PaymentIntent, PaymentMethod, PaymentMethodNew,
PaymentMethodUpdateInternal, PgPooledConn,
};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "db_op", content = "data")]
pub enum DBOperation {
Insert { insertable: Box<Insertable> },
Update { updatable: Box<Updateable> },
}
impl DBOperation {
pub fn operation<'a>(&self) -> &'a str {
match self {
Self::Insert { .. } => "insert",
Self::Update { .. } => "update",
}
}
pub fn table<'a>(&self) -> &'a str {
match self {
Self::Insert { insertable } => match **insertable {
Insertable::PaymentIntent(_) => "payment_intent",
Insertable::PaymentAttempt(_) => "payment_attempt",
Insertable::Refund(_) => "refund",
Insertable::Address(_) => "address",
Insertable::Payouts(_) => "payouts",
Insertable::PayoutAttempt(_) => "payout_attempt",
Insertable::Customer(_) => "customer",
Insertable::ReverseLookUp(_) => "reverse_lookup",
Insertable::PaymentMethod(_) => "payment_method",
Insertable::Mandate(_) => "mandate",
},
Self::Update { updatable } => match **updatable {
Updateable::PaymentIntentUpdate(_) => "payment_intent",
Updateable::PaymentAttemptUpdate(_) => "payment_attempt",
Updateable::RefundUpdate(_) => "refund",
Updateable::CustomerUpdate(_) => "customer",
Updateable::AddressUpdate(_) => "address",
Updateable::PayoutsUpdate(_) => "payouts",
Updateable::PayoutAttemptUpdate(_) => "payout_attempt",
Updateable::PaymentMethodUpdate(_) => "payment_method",
Updateable::MandateUpdate(_) => " mandate",
},
}
}
}
#[derive(Debug)]
pub enum DBResult {
PaymentIntent(Box<PaymentIntent>),
PaymentAttempt(Box<PaymentAttempt>),
Refund(Box<Refund>),
Address(Box<Address>),
Customer(Box<Customer>),
ReverseLookUp(Box<ReverseLookup>),
Payouts(Box<Payouts>),
PayoutAttempt(Box<PayoutAttempt>),
PaymentMethod(Box<PaymentMethod>),
Mandate(Box<Mandate>),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TypedSql {
#[serde(flatten)]
pub op: DBOperation,
}
impl DBOperation {
pub async fn execute(self, conn: &PgPooledConn) -> crate::StorageResult<DBResult> {
Ok(match self {
Self::Insert { insertable } => match *insertable {
Insertable::PaymentIntent(a) => {
DBResult::PaymentIntent(Box::new(a.insert(conn).await?))
}
Insertable::PaymentAttempt(a) => {
DBResult::PaymentAttempt(Box::new(a.insert(conn).await?))
}
Insertable::Refund(a) => DBResult::Refund(Box::new(a.insert(conn).await?)),
Insertable::Address(addr) => DBResult::Address(Box::new(addr.insert(conn).await?)),
Insertable::Customer(cust) => {
DBResult::Customer(Box::new(cust.insert(conn).await?))
}
Insertable::ReverseLookUp(rev) => {
DBResult::ReverseLookUp(Box::new(rev.insert(conn).await?))
}
Insertable::Payouts(rev) => DBResult::Payouts(Box::new(rev.insert(conn).await?)),
Insertable::PayoutAttempt(rev) => {
DBResult::PayoutAttempt(Box::new(rev.insert(conn).await?))
}
Insertable::PaymentMethod(rev) => {
DBResult::PaymentMethod(Box::new(rev.insert(conn).await?))
}
Insertable::Mandate(m) => DBResult::Mandate(Box::new(m.insert(conn).await?)),
},
Self::Update { updatable } => match *updatable {
#[cfg(feature = "v1")]
Updateable::PaymentIntentUpdate(a) => {
DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?))
}
#[cfg(feature = "v2")]
Updateable::PaymentIntentUpdate(a) => {
DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?))
}
#[cfg(feature = "v1")]
Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new(
a.orig.update_with_attempt_id(conn, a.update_data).await?,
)),
#[cfg(feature = "v2")]
Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new(
a.orig.update_with_attempt_id(conn, a.update_data).await?,
)),
#[cfg(feature = "v1")]
Updateable::RefundUpdate(a) => {
DBResult::Refund(Box::new(a.orig.update(conn, a.update_data).await?))
}
#[cfg(feature = "v2")]
Updateable::RefundUpdate(a) => {
DBResult::Refund(Box::new(a.orig.update_with_id(conn, a.update_data).await?))
}
Updateable::AddressUpdate(a) => {
DBResult::Address(Box::new(a.orig.update(conn, a.update_data).await?))
}
Updateable::PayoutsUpdate(a) => {
DBResult::Payouts(Box::new(a.orig.update(conn, a.update_data).await?))
}
Updateable::PayoutAttemptUpdate(a) => DBResult::PayoutAttempt(Box::new(
a.orig.update_with_attempt_id(conn, a.update_data).await?,
)),
#[cfg(feature = "v1")]
Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new(
v.orig
.update_with_payment_method_id(conn, v.update_data)
.await?,
)),
#[cfg(feature = "v2")]
Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new(
v.orig.update_with_id(conn, v.update_data).await?,
)),
Updateable::MandateUpdate(m) => DBResult::Mandate(Box::new(
Mandate::update_by_merchant_id_mandate_id(
conn,
&m.orig.merchant_id,
&m.orig.mandate_id,
m.update_data,
)
.await?,
)),
#[cfg(feature = "v1")]
Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new(
Customer::update_by_customer_id_merchant_id(
conn,
cust.orig.customer_id.clone(),
cust.orig.merchant_id.clone(),
cust.update_data,
)
.await?,
)),
#[cfg(feature = "v2")]
Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new(
Customer::update_by_id(conn, cust.orig.id, cust.update_data).await?,
)),
},
})
}
}
impl TypedSql {
pub fn to_field_value_pairs(
&self,
request_id: String,
global_id: String,
) -> crate::StorageResult<Vec<(&str, String)>> {
let pushed_at = common_utils::date_time::now_unix_timestamp();
Ok(vec![
(
"typed_sql",
serde_json::to_string(self)
.change_context(errors::DatabaseError::QueryGenerationFailed)?,
),
("global_id", global_id),
("request_id", request_id),
("pushed_at", pushed_at.to_string()),
])
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "table", content = "data")]
pub enum Insertable {
PaymentIntent(Box<PaymentIntentNew>),
PaymentAttempt(Box<PaymentAttemptNew>),
Refund(RefundNew),
Address(Box<AddressNew>),
Customer(CustomerNew),
ReverseLookUp(ReverseLookupNew),
Payouts(PayoutsNew),
PayoutAttempt(PayoutAttemptNew),
PaymentMethod(PaymentMethodNew),
Mandate(MandateNew),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "table", content = "data")]
pub enum Updateable {
PaymentIntentUpdate(Box<PaymentIntentUpdateMems>),
PaymentAttemptUpdate(Box<PaymentAttemptUpdateMems>),
RefundUpdate(Box<RefundUpdateMems>),
CustomerUpdate(CustomerUpdateMems),
AddressUpdate(Box<AddressUpdateMems>),
PayoutsUpdate(PayoutsUpdateMems),
PayoutAttemptUpdate(PayoutAttemptUpdateMems),
PaymentMethodUpdate(Box<PaymentMethodUpdateMems>),
MandateUpdate(MandateUpdateMems),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CustomerUpdateMems {
pub orig: Customer,
pub update_data: CustomerUpdateInternal,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AddressUpdateMems {
pub orig: Address,
pub update_data: AddressUpdateInternal,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentIntentUpdateMems {
pub orig: PaymentIntent,
pub update_data: PaymentIntentUpdate,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentIntentUpdateMems {
pub orig: PaymentIntent,
pub update_data: PaymentIntentUpdateInternal,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentAttemptUpdateMems {
pub orig: PaymentAttempt,
pub update_data: PaymentAttemptUpdate,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentAttemptUpdateMems {
pub orig: PaymentAttempt,
pub update_data: PaymentAttemptUpdateInternal,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RefundUpdateMems {
pub orig: Refund,
pub update_data: RefundUpdate,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PayoutsUpdateMems {
pub orig: Payouts,
pub update_data: PayoutsUpdate,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PayoutAttemptUpdateMems {
pub orig: PayoutAttempt,
pub update_data: PayoutAttemptUpdate,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentMethodUpdateMems {
pub orig: PaymentMethod,
pub update_data: PaymentMethodUpdateInternal,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MandateUpdateMems {
pub orig: Mandate,
pub update_data: MandateUpdateInternal,
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/kv.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2522
}
|
large_file_-3537722962697841686
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/types.rs
</path>
<file>
#[cfg(feature = "v2")]
use common_enums::enums::PaymentConnectorTransmission;
#[cfg(feature = "v2")]
use common_utils::id_type;
use common_utils::{hashing::HashedString, pii, types::MinorUnit};
use diesel::{
sql_types::{Json, Jsonb},
AsExpression, FromSqlRow,
};
use masking::{Secret, WithType};
use serde::{self, Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Jsonb)]
pub struct OrderDetailsWithAmount {
/// Name of the product that is being purchased
pub product_name: String,
/// The quantity of the product to be purchased
pub quantity: u16,
/// the amount per quantity of product
pub amount: MinorUnit,
// Does the order includes shipping
pub requires_shipping: Option<bool>,
/// The image URL of the product
pub product_img_link: Option<String>,
/// ID of the product that is being purchased
pub product_id: Option<String>,
/// Category of the product that is being purchased
pub category: Option<String>,
/// Sub category of the product that is being purchased
pub sub_category: Option<String>,
/// Brand of the product that is being purchased
pub brand: Option<String>,
/// Type of the product that is being purchased
pub product_type: Option<common_enums::ProductType>,
/// The tax code for the product
pub product_tax_code: Option<String>,
/// tax rate applicable to the product
pub tax_rate: Option<f64>,
/// total tax amount applicable to the product
pub total_tax_amount: Option<MinorUnit>,
/// description of the product
pub description: Option<String>,
/// stock keeping unit of the product
pub sku: Option<String>,
/// universal product code of the product
pub upc: Option<String>,
/// commodity code of the product
pub commodity_code: Option<String>,
/// unit of measure of the product
pub unit_of_measure: Option<String>,
/// total amount of the product
pub total_amount: Option<MinorUnit>,
/// discount amount on the unit
pub unit_discount_amount: Option<MinorUnit>,
}
impl masking::SerializableSecret for OrderDetailsWithAmount {}
common_utils::impl_to_sql_from_sql_json!(OrderDetailsWithAmount);
#[cfg(feature = "v2")]
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Json)]
pub struct FeatureMetadata {
/// Redirection response coming in request as metadata field only for redirection scenarios
pub redirect_response: Option<RedirectResponse>,
/// Additional tags to be used for global search
pub search_tags: Option<Vec<HashedString<WithType>>>,
/// Recurring payment details required for apple pay Merchant Token
pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>,
/// revenue recovery data for payment intent
pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>,
}
#[cfg(feature = "v2")]
impl FeatureMetadata {
pub fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> {
self.payment_revenue_recovery_metadata
.as_ref()
.map(|rrm| rrm.payment_method_subtype)
}
pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> {
self.payment_revenue_recovery_metadata
.as_ref()
.map(|recovery_metadata| recovery_metadata.payment_method_type)
}
pub fn get_billing_merchant_connector_account_id(
&self,
) -> Option<id_type::MerchantConnectorAccountId> {
self.payment_revenue_recovery_metadata
.as_ref()
.map(|recovery_metadata| recovery_metadata.billing_connector_id.clone())
}
// TODO: Check search_tags for relevant payment method type
// TODO: Check redirect_response metadata if applicable
// TODO: Check apple_pay_recurring_details metadata if applicable
}
#[cfg(feature = "v1")]
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Json)]
pub struct FeatureMetadata {
/// Redirection response coming in request as metadata field only for redirection scenarios
pub redirect_response: Option<RedirectResponse>,
/// Additional tags to be used for global search
pub search_tags: Option<Vec<HashedString<WithType>>>,
/// Recurring payment details required for apple pay Merchant Token
pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>,
/// The system that the gateway is integrated with, e.g., `Direct`(through hyperswitch), `UnifiedConnectorService`(through ucs), etc.
pub gateway_system: Option<common_enums::GatewaySystem>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Json)]
pub struct ApplePayRecurringDetails {
/// A description of the recurring payment that Apple Pay displays to the user in the payment sheet
pub payment_description: String,
/// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count
pub regular_billing: ApplePayRegularBillingDetails,
/// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment
pub billing_agreement: Option<String>,
/// A URL to a web page where the user can update or delete the payment method for the recurring payment
pub management_url: common_utils::types::Url,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Json)]
pub struct ApplePayRegularBillingDetails {
/// The label that Apple Pay displays to the user in the payment sheet with the recurring details
pub label: String,
/// The date of the first payment
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub recurring_payment_start_date: Option<time::PrimitiveDateTime>,
/// The date of the final payment
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub recurring_payment_end_date: Option<time::PrimitiveDateTime>,
/// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval
pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>,
/// The number of interval units that make up the total payment interval
pub recurring_payment_interval_count: Option<i32>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)]
#[diesel(sql_type = Json)]
#[serde(rename_all = "snake_case")]
pub enum RecurringPaymentIntervalUnit {
Year,
Month,
Day,
Hour,
Minute,
}
common_utils::impl_to_sql_from_sql_json!(ApplePayRecurringDetails);
common_utils::impl_to_sql_from_sql_json!(ApplePayRegularBillingDetails);
common_utils::impl_to_sql_from_sql_json!(RecurringPaymentIntervalUnit);
common_utils::impl_to_sql_from_sql_json!(FeatureMetadata);
#[derive(Default, Debug, Eq, PartialEq, Deserialize, Serialize, Clone)]
pub struct RedirectResponse {
pub param: Option<Secret<String>>,
pub json_payload: Option<pii::SecretSerdeValue>,
}
impl masking::SerializableSecret for RedirectResponse {}
common_utils::impl_to_sql_from_sql_json!(RedirectResponse);
#[cfg(feature = "v2")]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct PaymentRevenueRecoveryMetadata {
/// Total number of billing connector + recovery retries for a payment intent.
pub total_retry_count: u16,
/// Flag for the payment connector's call
pub payment_connector_transmission: PaymentConnectorTransmission,
/// Billing Connector Id to update the invoices
pub billing_connector_id: id_type::MerchantConnectorAccountId,
/// Payment Connector Id to retry the payments
pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId,
/// Billing Connector Payment Details
pub billing_connector_payment_details: BillingConnectorPaymentDetails,
///Payment Method Type
pub payment_method_type: common_enums::enums::PaymentMethod,
/// PaymentMethod Subtype
pub payment_method_subtype: common_enums::enums::PaymentMethodType,
/// The name of the payment connector through which the payment attempt was made.
pub connector: common_enums::connector_enums::Connector,
/// Time at which next invoice will be created
pub invoice_next_billing_time: Option<time::PrimitiveDateTime>,
/// Time at which invoice started
pub invoice_billing_started_at_time: Option<time::PrimitiveDateTime>,
/// Extra Payment Method Details that are needed to be stored
pub billing_connector_payment_method_details: Option<BillingConnectorPaymentMethodDetails>,
/// First Payment Attempt Payment Gateway Error Code
pub first_payment_attempt_pg_error_code: Option<String>,
/// First Payment Attempt Network Error Code
pub first_payment_attempt_network_decline_code: Option<String>,
/// First Payment Attempt Network Advice Code
pub first_payment_attempt_network_advice_code: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[cfg(feature = "v2")]
pub struct BillingConnectorPaymentDetails {
/// Payment Processor Token to process the Revenue Recovery Payment
pub payment_processor_token: String,
/// Billing Connector's Customer Id
pub connector_customer_id: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
pub enum BillingConnectorPaymentMethodDetails {
Card(BillingConnectorAdditionalCardInfo),
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct BillingConnectorAdditionalCardInfo {
/// Card Network
pub card_network: Option<common_enums::enums::CardNetwork>,
/// Card Issuer
pub card_issuer: Option<String>,
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/types.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2165
}
|
large_file_2290599859805237523
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/organization.rs
</path>
<file>
use common_utils::{id_type, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
#[cfg(feature = "v1")]
use crate::schema::organization;
#[cfg(feature = "v2")]
use crate::schema_v2::organization;
pub trait OrganizationBridge {
fn get_organization_id(&self) -> id_type::OrganizationId;
fn get_organization_name(&self) -> Option<String>;
fn set_organization_name(&mut self, organization_name: String);
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(
table_name = organization,
primary_key(org_id),
check_for_backend(diesel::pg::Pg)
)]
pub struct Organization {
org_id: id_type::OrganizationId,
org_name: Option<String>,
pub organization_details: Option<pii::SecretSerdeValue>,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
#[allow(dead_code)]
id: Option<id_type::OrganizationId>,
#[allow(dead_code)]
organization_name: Option<String>,
pub version: common_enums::ApiVersion,
pub organization_type: Option<common_enums::OrganizationType>,
pub platform_merchant_id: Option<id_type::MerchantId>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(
table_name = organization,
primary_key(id),
check_for_backend(diesel::pg::Pg)
)]
pub struct Organization {
pub organization_details: Option<pii::SecretSerdeValue>,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
id: id_type::OrganizationId,
organization_name: Option<String>,
pub version: common_enums::ApiVersion,
pub organization_type: Option<common_enums::OrganizationType>,
pub platform_merchant_id: Option<id_type::MerchantId>,
}
#[cfg(feature = "v1")]
impl Organization {
pub fn new(org_new: OrganizationNew) -> Self {
let OrganizationNew {
org_id,
org_name,
organization_details,
metadata,
created_at,
modified_at,
id: _,
organization_name: _,
version,
organization_type,
platform_merchant_id,
} = org_new;
Self {
id: Some(org_id.clone()),
organization_name: org_name.clone(),
org_id,
org_name,
organization_details,
metadata,
created_at,
modified_at,
version,
organization_type: Some(organization_type),
platform_merchant_id,
}
}
pub fn get_organization_type(&self) -> common_enums::OrganizationType {
self.organization_type.unwrap_or_default()
}
}
#[cfg(feature = "v2")]
impl Organization {
pub fn new(org_new: OrganizationNew) -> Self {
let OrganizationNew {
id,
organization_name,
organization_details,
metadata,
created_at,
modified_at,
version,
organization_type,
platform_merchant_id,
} = org_new;
Self {
id,
organization_name,
organization_details,
metadata,
created_at,
modified_at,
version,
organization_type: Some(organization_type),
platform_merchant_id,
}
}
pub fn get_organization_type(&self) -> common_enums::OrganizationType {
self.organization_type.unwrap_or_default()
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Insertable)]
#[diesel(table_name = organization, primary_key(org_id))]
pub struct OrganizationNew {
org_id: id_type::OrganizationId,
org_name: Option<String>,
id: id_type::OrganizationId,
organization_name: Option<String>,
pub organization_details: Option<pii::SecretSerdeValue>,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub version: common_enums::ApiVersion,
pub organization_type: common_enums::OrganizationType,
pub platform_merchant_id: Option<id_type::MerchantId>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable)]
#[diesel(table_name = organization, primary_key(id))]
pub struct OrganizationNew {
id: id_type::OrganizationId,
organization_name: Option<String>,
pub organization_details: Option<pii::SecretSerdeValue>,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub version: common_enums::ApiVersion,
pub organization_type: common_enums::OrganizationType,
pub platform_merchant_id: Option<id_type::MerchantId>,
}
#[cfg(feature = "v1")]
impl OrganizationNew {
pub fn new(
id: id_type::OrganizationId,
organization_type: common_enums::OrganizationType,
organization_name: Option<String>,
) -> Self {
Self {
org_id: id.clone(),
org_name: organization_name.clone(),
id,
organization_name,
organization_details: None,
metadata: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
version: common_types::consts::API_VERSION,
organization_type,
platform_merchant_id: None,
}
}
}
#[cfg(feature = "v2")]
impl OrganizationNew {
pub fn new(
id: id_type::OrganizationId,
organization_type: common_enums::OrganizationType,
organization_name: Option<String>,
) -> Self {
Self {
id,
organization_name,
organization_details: None,
metadata: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
version: common_types::consts::API_VERSION,
organization_type,
platform_merchant_id: None,
}
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset)]
#[diesel(table_name = organization)]
pub struct OrganizationUpdateInternal {
org_name: Option<String>,
organization_name: Option<String>,
organization_details: Option<pii::SecretSerdeValue>,
metadata: Option<pii::SecretSerdeValue>,
modified_at: time::PrimitiveDateTime,
platform_merchant_id: Option<id_type::MerchantId>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset)]
#[diesel(table_name = organization)]
pub struct OrganizationUpdateInternal {
organization_name: Option<String>,
organization_details: Option<pii::SecretSerdeValue>,
metadata: Option<pii::SecretSerdeValue>,
modified_at: time::PrimitiveDateTime,
platform_merchant_id: Option<id_type::MerchantId>,
}
pub enum OrganizationUpdate {
Update {
organization_name: Option<String>,
organization_details: Option<pii::SecretSerdeValue>,
metadata: Option<pii::SecretSerdeValue>,
platform_merchant_id: Option<id_type::MerchantId>,
},
}
#[cfg(feature = "v1")]
impl From<OrganizationUpdate> for OrganizationUpdateInternal {
fn from(value: OrganizationUpdate) -> Self {
match value {
OrganizationUpdate::Update {
organization_name,
organization_details,
metadata,
platform_merchant_id,
} => Self {
org_name: organization_name.clone(),
organization_name,
organization_details,
metadata,
modified_at: common_utils::date_time::now(),
platform_merchant_id,
},
}
}
}
#[cfg(feature = "v2")]
impl From<OrganizationUpdate> for OrganizationUpdateInternal {
fn from(value: OrganizationUpdate) -> Self {
match value {
OrganizationUpdate::Update {
organization_name,
organization_details,
metadata,
platform_merchant_id,
} => Self {
organization_name,
organization_details,
metadata,
modified_at: common_utils::date_time::now(),
platform_merchant_id,
},
}
}
}
#[cfg(feature = "v1")]
impl OrganizationBridge for Organization {
fn get_organization_id(&self) -> id_type::OrganizationId {
self.org_id.clone()
}
fn get_organization_name(&self) -> Option<String> {
self.org_name.clone()
}
fn set_organization_name(&mut self, organization_name: String) {
self.org_name = Some(organization_name);
}
}
#[cfg(feature = "v1")]
impl OrganizationBridge for OrganizationNew {
fn get_organization_id(&self) -> id_type::OrganizationId {
self.org_id.clone()
}
fn get_organization_name(&self) -> Option<String> {
self.org_name.clone()
}
fn set_organization_name(&mut self, organization_name: String) {
self.org_name = Some(organization_name);
}
}
#[cfg(feature = "v2")]
impl OrganizationBridge for Organization {
fn get_organization_id(&self) -> id_type::OrganizationId {
self.id.clone()
}
fn get_organization_name(&self) -> Option<String> {
self.organization_name.clone()
}
fn set_organization_name(&mut self, organization_name: String) {
self.organization_name = Some(organization_name);
}
}
#[cfg(feature = "v2")]
impl OrganizationBridge for OrganizationNew {
fn get_organization_id(&self) -> id_type::OrganizationId {
self.id.clone()
}
fn get_organization_name(&self) -> Option<String> {
self.organization_name.clone()
}
fn set_organization_name(&mut self, organization_name: String) {
self.organization_name = Some(organization_name);
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/organization.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2111
}
|
large_file_54087289845818366
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/merchant_account.rs
</path>
<file>
use common_utils::{encryption::Encryption, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use crate::enums as storage_enums;
#[cfg(feature = "v1")]
use crate::schema::merchant_account;
#[cfg(feature = "v2")]
use crate::schema_v2::merchant_account;
/// Note: The order of fields in the struct is important.
/// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile
/// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged
#[cfg(feature = "v1")]
#[derive(
Clone,
Debug,
serde::Deserialize,
Identifiable,
serde::Serialize,
Queryable,
Selectable,
router_derive::DebugAsDisplay,
)]
#[diesel(table_name = merchant_account, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct MerchantAccount {
merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub webhook_details: Option<crate::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: Option<String>,
pub storage_scheme: storage_enums::MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub intent_fulfillment_time: Option<i64>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: storage_enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub id: Option<common_utils::id_type::MerchantId>,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: Option<common_enums::MerchantAccountType>,
}
#[cfg(feature = "v1")]
pub struct MerchantAccountSetter {
pub merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub webhook_details: Option<crate::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: Option<String>,
pub storage_scheme: storage_enums::MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub intent_fulfillment_time: Option<i64>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: storage_enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v1")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
Self {
id: Some(item.merchant_id.clone()),
merchant_id: item.merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item.merchant_name,
merchant_details: item.merchant_details,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key: item.publishable_key,
storage_scheme: item.storage_scheme,
locker_id: item.locker_id,
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
primary_business_details: item.primary_business_details,
intent_fulfillment_time: item.intent_fulfillment_time,
created_at: item.created_at,
modified_at: item.modified_at,
frm_routing_algorithm: item.frm_routing_algorithm,
payout_routing_algorithm: item.payout_routing_algorithm,
organization_id: item.organization_id,
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
payment_link_config: item.payment_link_config,
pm_collect_link_config: item.pm_collect_link_config,
version: item.version,
is_platform_account: item.is_platform_account,
product_type: item.product_type,
merchant_account_type: Some(item.merchant_account_type),
}
}
}
/// Note: The order of fields in the struct is important.
/// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile
/// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged
#[cfg(feature = "v2")]
#[derive(
Clone,
Debug,
serde::Deserialize,
Identifiable,
serde::Serialize,
Queryable,
router_derive::DebugAsDisplay,
Selectable,
)]
#[diesel(table_name = merchant_account, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct MerchantAccount {
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub publishable_key: Option<String>,
pub storage_scheme: storage_enums::MerchantStorageScheme,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: storage_enums::ReconStatus,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub id: common_utils::id_type::MerchantId,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: Option<common_enums::MerchantAccountType>,
}
#[cfg(feature = "v2")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
Self {
id: item.id,
merchant_name: item.merchant_name,
merchant_details: item.merchant_details,
publishable_key: item.publishable_key,
storage_scheme: item.storage_scheme,
metadata: item.metadata,
created_at: item.created_at,
modified_at: item.modified_at,
organization_id: item.organization_id,
recon_status: item.recon_status,
version: item.version,
is_platform_account: item.is_platform_account,
product_type: item.product_type,
merchant_account_type: Some(item.merchant_account_type),
}
}
}
#[cfg(feature = "v2")]
pub struct MerchantAccountSetter {
pub id: common_utils::id_type::MerchantId,
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub publishable_key: Option<String>,
pub storage_scheme: storage_enums::MerchantStorageScheme,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: storage_enums::ReconStatus,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
impl MerchantAccount {
#[cfg(feature = "v1")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.merchant_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.id
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_account)]
pub struct MerchantAccountNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub return_url: Option<String>,
pub webhook_details: Option<crate::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
pub publishable_key: Option<String>,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub intent_fulfillment_time: Option<i64>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: storage_enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub id: Option<common_utils::id_type::MerchantId>,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_account)]
pub struct MerchantAccountNew {
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub publishable_key: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: storage_enums::ReconStatus,
pub id: common_utils::id_type::MerchantId,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_account)]
pub struct MerchantAccountUpdateInternal {
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub publishable_key: Option<String>,
pub storage_scheme: Option<storage_enums::MerchantStorageScheme>,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: Option<common_utils::id_type::OrganizationId>,
pub recon_status: Option<storage_enums::ReconStatus>,
pub is_platform_account: Option<bool>,
pub product_type: Option<common_enums::MerchantProductType>,
}
#[cfg(feature = "v2")]
impl MerchantAccountUpdateInternal {
pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount {
let Self {
merchant_name,
merchant_details,
publishable_key,
storage_scheme,
metadata,
modified_at,
organization_id,
recon_status,
is_platform_account,
product_type,
} = self;
MerchantAccount {
merchant_name: merchant_name.or(source.merchant_name),
merchant_details: merchant_details.or(source.merchant_details),
publishable_key: publishable_key.or(source.publishable_key),
storage_scheme: storage_scheme.unwrap_or(source.storage_scheme),
metadata: metadata.or(source.metadata),
created_at: source.created_at,
modified_at,
organization_id: organization_id.unwrap_or(source.organization_id),
recon_status: recon_status.unwrap_or(source.recon_status),
version: source.version,
id: source.id,
is_platform_account: is_platform_account.unwrap_or(source.is_platform_account),
product_type: product_type.or(source.product_type),
merchant_account_type: source.merchant_account_type,
}
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_account)]
pub struct MerchantAccountUpdateInternal {
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub return_url: Option<String>,
pub webhook_details: Option<crate::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
pub publishable_key: Option<String>,
pub storage_scheme: Option<storage_enums::MerchantStorageScheme>,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: Option<serde_json::Value>,
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: Option<common_utils::id_type::OrganizationId>,
pub is_recon_enabled: Option<bool>,
pub default_profile: Option<Option<common_utils::id_type::ProfileId>>,
pub recon_status: Option<storage_enums::ReconStatus>,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub is_platform_account: Option<bool>,
pub product_type: Option<common_enums::MerchantProductType>,
}
#[cfg(feature = "v1")]
impl MerchantAccountUpdateInternal {
pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount {
let Self {
merchant_name,
merchant_details,
return_url,
webhook_details,
sub_merchants_enabled,
parent_merchant_id,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
publishable_key,
storage_scheme,
locker_id,
metadata,
routing_algorithm,
primary_business_details,
modified_at,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
organization_id,
is_recon_enabled,
default_profile,
recon_status,
payment_link_config,
pm_collect_link_config,
is_platform_account,
product_type,
} = self;
MerchantAccount {
merchant_id: source.merchant_id,
return_url: return_url.or(source.return_url),
enable_payment_response_hash: enable_payment_response_hash
.unwrap_or(source.enable_payment_response_hash),
payment_response_hash_key: payment_response_hash_key
.or(source.payment_response_hash_key),
redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post
.unwrap_or(source.redirect_to_merchant_with_http_post),
merchant_name: merchant_name.or(source.merchant_name),
merchant_details: merchant_details.or(source.merchant_details),
webhook_details: webhook_details.or(source.webhook_details),
sub_merchants_enabled: sub_merchants_enabled.or(source.sub_merchants_enabled),
parent_merchant_id: parent_merchant_id.or(source.parent_merchant_id),
publishable_key: publishable_key.or(source.publishable_key),
storage_scheme: storage_scheme.unwrap_or(source.storage_scheme),
locker_id: locker_id.or(source.locker_id),
metadata: metadata.or(source.metadata),
routing_algorithm: routing_algorithm.or(source.routing_algorithm),
primary_business_details: primary_business_details
.unwrap_or(source.primary_business_details),
intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time),
created_at: source.created_at,
modified_at,
frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm),
payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm),
organization_id: organization_id.unwrap_or(source.organization_id),
is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled),
default_profile: default_profile.unwrap_or(source.default_profile),
recon_status: recon_status.unwrap_or(source.recon_status),
payment_link_config: payment_link_config.or(source.payment_link_config),
pm_collect_link_config: pm_collect_link_config.or(source.pm_collect_link_config),
version: source.version,
is_platform_account: is_platform_account.unwrap_or(source.is_platform_account),
id: source.id,
product_type: product_type.or(source.product_type),
merchant_account_type: source.merchant_account_type,
}
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/merchant_account.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4065
}
|
large_file_4794403518702074157
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/payment_method.rs
</path>
<file>
use std::collections::HashMap;
use common_enums::MerchantStorageScheme;
use common_utils::{
encryption::Encryption,
errors::{CustomResult, ParsingError},
pii,
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
#[cfg(feature = "v1")]
use crate::{enums as storage_enums, schema::payment_methods};
#[cfg(feature = "v2")]
use crate::{enums as storage_enums, schema_v2::payment_methods};
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = payment_methods, primary_key(payment_method_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentMethod {
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
#[diesel(deserialize_as = super::OptionalDieselArray<storage_enums::Currency>)]
pub accepted_currency: Option<Vec<storage_enums::Currency>>,
pub scheme: Option<String>,
pub token: Option<String>,
pub cardholder_name: Option<Secret<String>>,
pub issuer_name: Option<String>,
pub issuer_country: Option<String>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub payer_country: Option<Vec<String>>,
pub is_stored: Option<bool>,
pub swift_code: Option<String>,
pub direct_debit_token: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub vault_type: Option<storage_enums::VaultType>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)]
#[diesel(table_name = payment_methods, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentMethod {
pub customer_id: common_utils::id_type::GlobalCustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<CommonMandateReference>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub vault_type: Option<storage_enums::VaultType>,
pub locker_fingerprint_id: Option<String>,
pub payment_method_type_v2: Option<storage_enums::PaymentMethod>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
pub id: common_utils::id_type::GlobalPaymentMethodId,
pub external_vault_token_data: Option<Encryption>,
}
impl PaymentMethod {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &String {
&self.payment_method_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodNew {
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub accepted_currency: Option<Vec<storage_enums::Currency>>,
pub scheme: Option<String>,
pub token: Option<String>,
pub cardholder_name: Option<Secret<String>>,
pub issuer_name: Option<String>,
pub issuer_country: Option<String>,
pub payer_country: Option<Vec<String>>,
pub is_stored: Option<bool>,
pub swift_code: Option<String>,
pub direct_debit_token: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub vault_type: Option<storage_enums::VaultType>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodNew {
pub customer_id: common_utils::id_type::GlobalCustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method_data: Option<Encryption>,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<CommonMandateReference>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: Option<Encryption>,
pub external_vault_token_data: Option<Encryption>,
pub locker_fingerprint_id: Option<String>,
pub payment_method_type_v2: Option<storage_enums::PaymentMethod>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
pub id: common_utils::id_type::GlobalPaymentMethodId,
pub vault_type: Option<storage_enums::VaultType>,
}
impl PaymentMethodNew {
pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) {
self.updated_by = Some(storage_scheme.to_string());
}
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &String {
&self.payment_method_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct TokenizeCoreWorkflow {
pub lookup_key: String,
pub pm: storage_enums::PaymentMethod,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub enum PaymentMethodUpdate {
MetadataUpdateAndLastUsed {
metadata: Option<serde_json::Value>,
last_used_at: PrimitiveDateTime,
},
UpdatePaymentMethodDataAndLastUsed {
payment_method_data: Option<Encryption>,
scheme: Option<String>,
last_used_at: PrimitiveDateTime,
},
PaymentMethodDataUpdate {
payment_method_data: Option<Encryption>,
},
LastUsedUpdate {
last_used_at: PrimitiveDateTime,
},
NetworkTransactionIdAndStatusUpdate {
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
},
StatusUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
},
AdditionalDataUpdate {
payment_method_data: Option<Encryption>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
payment_method: Option<storage_enums::PaymentMethod>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_method_issuer: Option<String>,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
},
ConnectorMandateDetailsUpdate {
connector_mandate_details: Option<serde_json::Value>,
},
NetworkTokenDataUpdate {
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
},
ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details: Option<pii::SecretSerdeValue>,
network_transaction_id: Option<Secret<String>>,
},
PaymentMethodBatchUpdate {
connector_mandate_details: Option<pii::SecretSerdeValue>,
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
payment_method_data: Option<Encryption>,
},
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub enum PaymentMethodUpdate {
UpdatePaymentMethodDataAndLastUsed {
payment_method_data: Option<Encryption>,
scheme: Option<String>,
last_used_at: PrimitiveDateTime,
},
PaymentMethodDataUpdate {
payment_method_data: Option<Encryption>,
},
LastUsedUpdate {
last_used_at: PrimitiveDateTime,
},
NetworkTransactionIdAndStatusUpdate {
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
},
StatusUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
},
GenericUpdate {
payment_method_data: Option<Encryption>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
payment_method_type_v2: Option<storage_enums::PaymentMethod>,
payment_method_subtype: Option<storage_enums::PaymentMethodType>,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
locker_fingerprint_id: Option<String>,
connector_mandate_details: Option<CommonMandateReference>,
external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
},
ConnectorMandateDetailsUpdate {
connector_mandate_details: Option<CommonMandateReference>,
},
}
impl PaymentMethodUpdate {
pub fn convert_to_payment_method_update(
self,
storage_scheme: MerchantStorageScheme,
) -> PaymentMethodUpdateInternal {
let mut update_internal: PaymentMethodUpdateInternal = self.into();
update_internal.updated_by = Some(storage_scheme.to_string());
update_internal
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodUpdateInternal {
payment_method_data: Option<Encryption>,
last_used_at: Option<PrimitiveDateTime>,
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
payment_method_type_v2: Option<storage_enums::PaymentMethod>,
connector_mandate_details: Option<CommonMandateReference>,
updated_by: Option<String>,
payment_method_subtype: Option<storage_enums::PaymentMethodType>,
last_modified: PrimitiveDateTime,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
locker_fingerprint_id: Option<String>,
external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v2")]
impl PaymentMethodUpdateInternal {
pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod {
let Self {
payment_method_data,
last_used_at,
network_transaction_id,
status,
locker_id,
payment_method_type_v2,
connector_mandate_details,
updated_by,
payment_method_subtype,
last_modified,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
locker_fingerprint_id,
external_vault_source,
} = self;
PaymentMethod {
customer_id: source.customer_id,
merchant_id: source.merchant_id,
created_at: source.created_at,
last_modified,
payment_method_data: payment_method_data.or(source.payment_method_data),
locker_id: locker_id.or(source.locker_id),
last_used_at: last_used_at.unwrap_or(source.last_used_at),
connector_mandate_details: connector_mandate_details
.or(source.connector_mandate_details),
customer_acceptance: source.customer_acceptance,
status: status.unwrap_or(source.status),
network_transaction_id: network_transaction_id.or(source.network_transaction_id),
client_secret: source.client_secret,
payment_method_billing_address: source.payment_method_billing_address,
updated_by: updated_by.or(source.updated_by),
locker_fingerprint_id: locker_fingerprint_id.or(source.locker_fingerprint_id),
payment_method_type_v2: payment_method_type_v2.or(source.payment_method_type_v2),
payment_method_subtype: payment_method_subtype.or(source.payment_method_subtype),
id: source.id,
version: source.version,
network_token_requestor_reference_id: network_token_requestor_reference_id
.or(source.network_token_requestor_reference_id),
network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id),
network_token_payment_method_data: network_token_payment_method_data
.or(source.network_token_payment_method_data),
external_vault_source: external_vault_source.or(source.external_vault_source),
external_vault_token_data: source.external_vault_token_data,
vault_type: source.vault_type,
}
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodUpdateInternal {
metadata: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
last_used_at: Option<PrimitiveDateTime>,
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
network_token_requestor_reference_id: Option<String>,
payment_method: Option<storage_enums::PaymentMethod>,
connector_mandate_details: Option<serde_json::Value>,
updated_by: Option<String>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_method_issuer: Option<String>,
last_modified: PrimitiveDateTime,
network_token_locker_id: Option<String>,
network_token_payment_method_data: Option<Encryption>,
scheme: Option<String>,
}
#[cfg(feature = "v1")]
impl PaymentMethodUpdateInternal {
pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod {
let Self {
metadata,
payment_method_data,
last_used_at,
network_transaction_id,
status,
locker_id,
network_token_requestor_reference_id,
payment_method,
connector_mandate_details,
updated_by,
payment_method_type,
payment_method_issuer,
last_modified,
network_token_locker_id,
network_token_payment_method_data,
scheme,
} = self;
PaymentMethod {
customer_id: source.customer_id,
merchant_id: source.merchant_id,
payment_method_id: source.payment_method_id,
accepted_currency: source.accepted_currency,
scheme: scheme.or(source.scheme),
token: source.token,
cardholder_name: source.cardholder_name,
issuer_name: source.issuer_name,
issuer_country: source.issuer_country,
payer_country: source.payer_country,
is_stored: source.is_stored,
swift_code: source.swift_code,
direct_debit_token: source.direct_debit_token,
created_at: source.created_at,
last_modified,
payment_method: payment_method.or(source.payment_method),
payment_method_type: payment_method_type.or(source.payment_method_type),
payment_method_issuer: payment_method_issuer.or(source.payment_method_issuer),
payment_method_issuer_code: source.payment_method_issuer_code,
metadata: metadata.map_or(source.metadata, |v| Some(v.into())),
payment_method_data: payment_method_data.or(source.payment_method_data),
locker_id: locker_id.or(source.locker_id),
last_used_at: last_used_at.unwrap_or(source.last_used_at),
connector_mandate_details: connector_mandate_details
.or(source.connector_mandate_details),
customer_acceptance: source.customer_acceptance,
status: status.unwrap_or(source.status),
network_transaction_id: network_transaction_id.or(source.network_transaction_id),
client_secret: source.client_secret,
payment_method_billing_address: source.payment_method_billing_address,
updated_by: updated_by.or(source.updated_by),
version: source.version,
network_token_requestor_reference_id: network_token_requestor_reference_id
.or(source.network_token_requestor_reference_id),
network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id),
network_token_payment_method_data: network_token_payment_method_data
.or(source.network_token_payment_method_data),
external_vault_source: source.external_vault_source,
vault_type: source.vault_type,
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
fn from(payment_method_update: PaymentMethodUpdate) -> Self {
match payment_method_update {
PaymentMethodUpdate::MetadataUpdateAndLastUsed {
metadata,
last_used_at,
} => Self {
metadata,
payment_method_data: None,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
} => Self {
metadata: None,
payment_method_data,
last_used_at: None,
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
metadata: None,
payment_method_data: None,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
},
PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data,
scheme,
last_used_at,
} => Self {
metadata: None,
payment_method_data,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status,
} => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
network_transaction_id,
status,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
},
PaymentMethodUpdate::StatusUpdate { status } => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
network_transaction_id: None,
status,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
},
PaymentMethodUpdate::AdditionalDataUpdate {
payment_method_data,
status,
locker_id,
network_token_requestor_reference_id,
payment_method,
payment_method_type,
payment_method_issuer,
network_token_locker_id,
network_token_payment_method_data,
} => Self {
metadata: None,
payment_method_data,
last_used_at: None,
network_transaction_id: None,
status,
locker_id,
network_token_requestor_reference_id,
payment_method,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer,
payment_method_type,
last_modified: common_utils::date_time::now(),
network_token_locker_id,
network_token_payment_method_data,
scheme: None,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details,
} => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
status: None,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details,
network_transaction_id: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
},
PaymentMethodUpdate::NetworkTokenDataUpdate {
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
} => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
status: None,
locker_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_transaction_id: None,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
scheme: None,
},
PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details,
network_transaction_id,
} => Self {
connector_mandate_details: connector_mandate_details
.map(|mandate_details| mandate_details.expose()),
network_transaction_id: network_transaction_id.map(|txn_id| txn_id.expose()),
last_modified: common_utils::date_time::now(),
status: None,
metadata: None,
payment_method_data: None,
last_used_at: None,
locker_id: None,
payment_method: None,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
network_token_requestor_reference_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
},
PaymentMethodUpdate::PaymentMethodBatchUpdate {
connector_mandate_details,
network_transaction_id,
status,
payment_method_data,
} => Self {
metadata: None,
last_used_at: None,
status,
locker_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: connector_mandate_details
.map(|mandate_details| mandate_details.expose()),
network_transaction_id,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_payment_method_data: None,
scheme: None,
payment_method_data,
},
}
}
}
#[cfg(feature = "v2")]
impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
fn from(payment_method_update: PaymentMethodUpdate) -> Self {
match payment_method_update {
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
} => Self {
payment_method_data,
last_used_at: None,
network_transaction_id: None,
status: None,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
payment_method_data: None,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
},
PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data,
last_used_at,
..
} => Self {
payment_method_data,
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status,
} => Self {
payment_method_data: None,
last_used_at: None,
network_transaction_id,
status,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
},
PaymentMethodUpdate::StatusUpdate { status } => Self {
payment_method_data: None,
last_used_at: None,
network_transaction_id: None,
status,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
},
PaymentMethodUpdate::GenericUpdate {
payment_method_data,
status,
locker_id,
payment_method_type_v2,
payment_method_subtype,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
locker_fingerprint_id,
connector_mandate_details,
external_vault_source,
} => Self {
payment_method_data,
last_used_at: None,
network_transaction_id: None,
status,
locker_id,
payment_method_type_v2,
connector_mandate_details,
updated_by: None,
payment_method_subtype,
last_modified: common_utils::date_time::now(),
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
locker_fingerprint_id,
external_vault_source,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details,
} => Self {
payment_method_data: None,
last_used_at: None,
status: None,
locker_id: None,
payment_method_type_v2: None,
connector_mandate_details,
network_transaction_id: None,
updated_by: None,
payment_method_subtype: None,
last_modified: common_utils::date_time::now(),
network_token_locker_id: None,
network_token_requestor_reference_id: None,
network_token_payment_method_data: None,
locker_fingerprint_id: None,
external_vault_source: None,
},
}
}
}
#[cfg(feature = "v1")]
impl From<&PaymentMethodNew> for PaymentMethod {
fn from(payment_method_new: &PaymentMethodNew) -> Self {
Self {
customer_id: payment_method_new.customer_id.clone(),
merchant_id: payment_method_new.merchant_id.clone(),
payment_method_id: payment_method_new.payment_method_id.clone(),
locker_id: payment_method_new.locker_id.clone(),
network_token_requestor_reference_id: payment_method_new
.network_token_requestor_reference_id
.clone(),
accepted_currency: payment_method_new.accepted_currency.clone(),
scheme: payment_method_new.scheme.clone(),
token: payment_method_new.token.clone(),
cardholder_name: payment_method_new.cardholder_name.clone(),
issuer_name: payment_method_new.issuer_name.clone(),
issuer_country: payment_method_new.issuer_country.clone(),
payer_country: payment_method_new.payer_country.clone(),
is_stored: payment_method_new.is_stored,
swift_code: payment_method_new.swift_code.clone(),
direct_debit_token: payment_method_new.direct_debit_token.clone(),
created_at: payment_method_new.created_at,
last_modified: payment_method_new.last_modified,
payment_method: payment_method_new.payment_method,
payment_method_type: payment_method_new.payment_method_type,
payment_method_issuer: payment_method_new.payment_method_issuer.clone(),
payment_method_issuer_code: payment_method_new.payment_method_issuer_code,
metadata: payment_method_new.metadata.clone(),
payment_method_data: payment_method_new.payment_method_data.clone(),
last_used_at: payment_method_new.last_used_at,
connector_mandate_details: payment_method_new.connector_mandate_details.clone(),
customer_acceptance: payment_method_new.customer_acceptance.clone(),
status: payment_method_new.status,
network_transaction_id: payment_method_new.network_transaction_id.clone(),
client_secret: payment_method_new.client_secret.clone(),
updated_by: payment_method_new.updated_by.clone(),
payment_method_billing_address: payment_method_new
.payment_method_billing_address
.clone(),
version: payment_method_new.version,
network_token_locker_id: payment_method_new.network_token_locker_id.clone(),
network_token_payment_method_data: payment_method_new
.network_token_payment_method_data
.clone(),
external_vault_source: payment_method_new.external_vault_source.clone(),
vault_type: payment_method_new.vault_type,
}
}
}
#[cfg(feature = "v2")]
impl From<&PaymentMethodNew> for PaymentMethod {
fn from(payment_method_new: &PaymentMethodNew) -> Self {
Self {
customer_id: payment_method_new.customer_id.clone(),
merchant_id: payment_method_new.merchant_id.clone(),
locker_id: payment_method_new.locker_id.clone(),
created_at: payment_method_new.created_at,
last_modified: payment_method_new.last_modified,
payment_method_data: payment_method_new.payment_method_data.clone(),
last_used_at: payment_method_new.last_used_at,
connector_mandate_details: payment_method_new.connector_mandate_details.clone(),
customer_acceptance: payment_method_new.customer_acceptance.clone(),
status: payment_method_new.status,
network_transaction_id: payment_method_new.network_transaction_id.clone(),
client_secret: payment_method_new.client_secret.clone(),
updated_by: payment_method_new.updated_by.clone(),
payment_method_billing_address: payment_method_new
.payment_method_billing_address
.clone(),
locker_fingerprint_id: payment_method_new.locker_fingerprint_id.clone(),
payment_method_type_v2: payment_method_new.payment_method_type_v2,
payment_method_subtype: payment_method_new.payment_method_subtype,
id: payment_method_new.id.clone(),
version: payment_method_new.version,
network_token_requestor_reference_id: payment_method_new
.network_token_requestor_reference_id
.clone(),
network_token_locker_id: payment_method_new.network_token_locker_id.clone(),
network_token_payment_method_data: payment_method_new
.network_token_payment_method_data
.clone(),
external_vault_source: None,
external_vault_token_data: payment_method_new.external_vault_token_data.clone(),
vault_type: payment_method_new.vault_type,
}
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsMandateReferenceRecord {
pub connector_mandate_id: String,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<common_enums::Currency>,
pub mandate_metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>,
pub connector_mandate_request_reference_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorTokenReferenceRecord {
pub connector_token: String,
pub payment_method_subtype: Option<common_enums::PaymentMethodType>,
pub original_payment_authorized_amount: Option<common_utils::types::MinorUnit>,
pub original_payment_authorized_currency: Option<common_enums::Currency>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_token_status: common_enums::ConnectorTokenStatus,
pub connector_token_request_reference_id: Option<String>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PaymentsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>,
);
#[cfg(feature = "v1")]
impl std::ops::Deref for PaymentsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v1")]
impl std::ops::DerefMut for PaymentsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PaymentsTokenReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>,
);
#[cfg(feature = "v2")]
impl std::ops::Deref for PaymentsTokenReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v2")]
impl std::ops::DerefMut for PaymentsTokenReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v1")]
common_utils::impl_to_sql_from_sql_json!(PaymentsMandateReference);
#[cfg(feature = "v2")]
common_utils::impl_to_sql_from_sql_json!(PaymentsTokenReference);
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PayoutsMandateReferenceRecord {
pub transfer_method_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PayoutsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>,
);
impl std::ops::Deref for PayoutsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for PayoutsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsMandateReference>,
pub payouts: Option<PayoutsMandateReference>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsTokenReference>,
pub payouts: Option<PayoutsMandateReference>,
}
impl CommonMandateReference {
pub fn get_mandate_details_value(&self) -> CustomResult<serde_json::Value, ParsingError> {
let mut payments = self
.payments
.as_ref()
.map_or_else(|| Ok(serde_json::json!({})), serde_json::to_value)
.change_context(ParsingError::StructParseFailure("payment mandate details"))?;
self.payouts
.as_ref()
.map(|payouts_mandate| {
serde_json::to_value(payouts_mandate).map(|payouts_mandate_value| {
payments.as_object_mut().map(|payments_object| {
payments_object.insert("payouts".to_string(), payouts_mandate_value);
})
})
})
.transpose()
.change_context(ParsingError::StructParseFailure("payout mandate details"))?;
Ok(payments)
}
#[cfg(feature = "v2")]
/// Insert a new payment token reference for the given connector_id
pub fn insert_payment_token_reference_record(
&mut self,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
record: ConnectorTokenReferenceRecord,
) {
match self.payments {
Some(ref mut payments_reference) => {
payments_reference.insert(connector_id.clone(), record);
}
None => {
let mut payments_reference = HashMap::new();
payments_reference.insert(connector_id.clone(), record);
self.payments = Some(PaymentsTokenReference(payments_reference));
}
}
}
}
impl diesel::serialize::ToSql<diesel::sql_types::Jsonb, diesel::pg::Pg> for CommonMandateReference {
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
let payments = self.get_mandate_details_value()?;
<serde_json::Value as diesel::serialize::ToSql<
diesel::sql_types::Jsonb,
diesel::pg::Pg,
>>::to_sql(&payments, &mut out.reborrow())
}
}
#[cfg(feature = "v1")]
impl<DB: diesel::backend::Backend> diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>
for CommonMandateReference
where
serde_json::Value: diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let value = <serde_json::Value as diesel::deserialize::FromSql<
diesel::sql_types::Jsonb,
DB,
>>::from_sql(bytes)?;
let payments_data = value
.clone()
.as_object_mut()
.map(|obj| {
obj.remove("payouts");
serde_json::from_value::<PaymentsMandateReference>(serde_json::Value::Object(
obj.clone(),
))
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payments data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payments data",
))
})
.transpose()?;
let payouts_data = serde_json::from_value::<Option<Self>>(value)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payouts data",
))
.map(|optional_common_mandate_details| {
optional_common_mandate_details
.and_then(|common_mandate_details| common_mandate_details.payouts)
})?;
Ok(Self {
payments: payments_data,
payouts: payouts_data,
})
}
}
#[cfg(feature = "v2")]
impl<DB: diesel::backend::Backend> diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>
for CommonMandateReference
where
serde_json::Value: diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let value = <serde_json::Value as diesel::deserialize::FromSql<
diesel::sql_types::Jsonb,
DB,
>>::from_sql(bytes)?;
let payments_data = value
.clone()
.as_object_mut()
.map(|obj| {
obj.remove("payouts");
serde_json::from_value::<PaymentsTokenReference>(serde_json::Value::Object(
obj.clone(),
))
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payments data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payments data",
))
})
.transpose()?;
let payouts_data = serde_json::from_value::<Option<Self>>(value)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payouts data",
))
.map(|optional_common_mandate_details| {
optional_common_mandate_details
.and_then(|common_mandate_details| common_mandate_details.payouts)
})?;
Ok(Self {
payments: payments_data,
payouts: payouts_data,
})
}
}
#[cfg(feature = "v1")]
impl From<PaymentsMandateReference> for CommonMandateReference {
fn from(payment_reference: PaymentsMandateReference) -> Self {
Self {
payments: Some(payment_reference),
payouts: None,
}
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/payment_method.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10170
}
|
large_file_4873129553658352469
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/merchant_connector_account.rs
</path>
<file>
#[cfg(feature = "v2")]
use std::collections::HashMap;
use std::fmt::Debug;
use common_utils::{encryption::Encryption, id_type, pii};
#[cfg(feature = "v2")]
use diesel::{sql_types::Jsonb, AsExpression};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use crate::enums as storage_enums;
#[cfg(feature = "v1")]
use crate::schema::merchant_connector_account;
#[cfg(feature = "v2")]
use crate::schema_v2::merchant_connector_account;
#[cfg(feature = "v1")]
#[derive(
Clone,
Debug,
serde::Serialize,
serde::Deserialize,
Identifiable,
Queryable,
Selectable,
router_derive::DebugAsDisplay,
)]
#[diesel(table_name = merchant_connector_account, primary_key(merchant_connector_id), check_for_backend(diesel::pg::Pg))]
pub struct MerchantConnectorAccount {
pub merchant_id: id_type::MerchantId,
pub connector_name: String,
pub connector_account_details: Encryption,
pub test_mode: Option<bool>,
pub disabled: Option<bool>,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
pub connector_type: storage_enums::ConnectorType,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_label: Option<String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub business_sub_label: Option<String>,
pub frm_configs: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
pub profile_id: Option<id_type::ProfileId>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: storage_enums::ConnectorStatus,
pub additional_merchant_data: Option<Encryption>,
pub connector_wallets_details: Option<Encryption>,
pub version: common_enums::ApiVersion,
pub id: Option<id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v1")]
impl MerchantConnectorAccount {
pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {
self.merchant_connector_id.clone()
}
}
#[cfg(feature = "v2")]
use crate::RequiredFromNullable;
#[cfg(feature = "v2")]
#[derive(
Clone,
Debug,
serde::Serialize,
serde::Deserialize,
Identifiable,
Queryable,
Selectable,
router_derive::DebugAsDisplay,
)]
#[diesel(table_name = merchant_connector_account, check_for_backend(diesel::pg::Pg))]
pub struct MerchantConnectorAccount {
pub merchant_id: id_type::MerchantId,
pub connector_name: common_enums::connector_enums::Connector,
pub connector_account_details: Encryption,
pub disabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)]
pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,
pub connector_type: storage_enums::ConnectorType,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_label: Option<String>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
#[diesel(deserialize_as = RequiredFromNullable<id_type::ProfileId>)]
pub profile_id: id_type::ProfileId,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: storage_enums::ConnectorStatus,
pub additional_merchant_data: Option<Encryption>,
pub connector_wallets_details: Option<Encryption>,
pub version: common_enums::ApiVersion,
pub id: id_type::MerchantConnectorAccountId,
pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,
}
#[cfg(feature = "v2")]
impl MerchantConnectorAccount {
pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {
self.id.clone()
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_connector_account)]
pub struct MerchantConnectorAccountNew {
pub merchant_id: Option<id_type::MerchantId>,
pub connector_type: Option<storage_enums::ConnectorType>,
pub connector_name: Option<String>,
pub connector_account_details: Option<Encryption>,
pub test_mode: Option<bool>,
pub disabled: Option<bool>,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_label: Option<String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub business_sub_label: Option<String>,
pub frm_configs: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
pub profile_id: Option<id_type::ProfileId>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: storage_enums::ConnectorStatus,
pub additional_merchant_data: Option<Encryption>,
pub connector_wallets_details: Option<Encryption>,
pub version: common_enums::ApiVersion,
pub id: Option<id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_connector_account)]
pub struct MerchantConnectorAccountNew {
pub merchant_id: Option<id_type::MerchantId>,
pub connector_type: Option<storage_enums::ConnectorType>,
pub connector_name: Option<common_enums::connector_enums::Connector>,
pub connector_account_details: Option<Encryption>,
pub disabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)]
pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_label: Option<String>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
pub profile_id: id_type::ProfileId,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: storage_enums::ConnectorStatus,
pub additional_merchant_data: Option<Encryption>,
pub connector_wallets_details: Option<Encryption>,
pub version: common_enums::ApiVersion,
pub id: id_type::MerchantConnectorAccountId,
pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_connector_account)]
pub struct MerchantConnectorAccountUpdateInternal {
pub connector_type: Option<storage_enums::ConnectorType>,
pub connector_name: Option<String>,
pub connector_account_details: Option<Encryption>,
pub connector_label: Option<String>,
pub test_mode: Option<bool>,
pub disabled: Option<bool>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
pub frm_configs: Option<pii::SecretSerdeValue>,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: Option<time::PrimitiveDateTime>,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: Option<storage_enums::ConnectorStatus>,
pub connector_wallets_details: Option<Encryption>,
pub additional_merchant_data: Option<Encryption>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_connector_account)]
pub struct MerchantConnectorAccountUpdateInternal {
pub connector_type: Option<storage_enums::ConnectorType>,
pub connector_account_details: Option<Encryption>,
pub connector_label: Option<String>,
pub disabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)]
pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: Option<time::PrimitiveDateTime>,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub frm_config: Option<Vec<pii::SecretSerdeValue>>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: Option<storage_enums::ConnectorStatus>,
pub connector_wallets_details: Option<Encryption>,
pub additional_merchant_data: Option<Encryption>,
pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,
}
#[cfg(feature = "v1")]
impl MerchantConnectorAccountUpdateInternal {
pub fn create_merchant_connector_account(
self,
source: MerchantConnectorAccount,
) -> MerchantConnectorAccount {
MerchantConnectorAccount {
merchant_id: source.merchant_id,
connector_type: self.connector_type.unwrap_or(source.connector_type),
connector_account_details: self
.connector_account_details
.unwrap_or(source.connector_account_details),
test_mode: self.test_mode,
disabled: self.disabled,
merchant_connector_id: self
.merchant_connector_id
.unwrap_or(source.merchant_connector_id),
payment_methods_enabled: self.payment_methods_enabled,
frm_config: self.frm_config,
modified_at: self.modified_at.unwrap_or(source.modified_at),
pm_auth_config: self.pm_auth_config,
status: self.status.unwrap_or(source.status),
..source
}
}
}
#[cfg(feature = "v2")]
impl MerchantConnectorAccountUpdateInternal {
pub fn create_merchant_connector_account(
self,
source: MerchantConnectorAccount,
) -> MerchantConnectorAccount {
MerchantConnectorAccount {
connector_type: self.connector_type.unwrap_or(source.connector_type),
connector_account_details: self
.connector_account_details
.unwrap_or(source.connector_account_details),
disabled: self.disabled,
payment_methods_enabled: self.payment_methods_enabled,
frm_config: self.frm_config,
modified_at: self.modified_at.unwrap_or(source.modified_at),
pm_auth_config: self.pm_auth_config,
status: self.status.unwrap_or(source.status),
feature_metadata: self.feature_metadata,
..source
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, AsExpression)]
#[diesel(sql_type = Jsonb)]
pub struct MerchantConnectorAccountFeatureMetadata {
pub revenue_recovery: Option<RevenueRecoveryMetadata>,
}
#[cfg(feature = "v2")]
common_utils::impl_to_sql_from_sql_json!(MerchantConnectorAccountFeatureMetadata);
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct RevenueRecoveryMetadata {
/// The maximum number of retries allowed for an invoice. This limit is set by the merchant for each `billing connector`.Once this limit is reached, no further retries will be attempted.
pub max_retry_count: u16,
/// Maximum number of `billing connector` retries before revenue recovery can start executing retries.
pub billing_connector_retry_threshold: u16,
/// Billing account reference id is payment gateway id at billing connector end.
/// Merchants need to provide a mapping between these merchant connector account and the corresponding
/// account reference IDs for each `billing connector`.
pub billing_account_reference: BillingAccountReference,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BillingAccountReference(pub HashMap<id_type::MerchantConnectorAccountId, String>);
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/merchant_connector_account.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3039
}
|
large_file_1644779699913969844
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/lib.rs
</path>
<file>
pub mod address;
pub mod api_keys;
pub mod blocklist_lookup;
pub mod business_profile;
pub mod capture;
pub mod cards_info;
pub mod configs;
pub mod authentication;
pub mod authorization;
pub mod blocklist;
pub mod blocklist_fingerprint;
pub mod callback_mapper;
pub mod customers;
pub mod dispute;
pub mod dynamic_routing_stats;
pub mod enums;
pub mod ephemeral_key;
pub mod errors;
pub mod events;
pub mod file;
#[allow(unused)]
pub mod fraud_check;
pub mod generic_link;
pub mod gsm;
pub mod hyperswitch_ai_interaction;
pub mod invoice;
#[cfg(feature = "kv_store")]
pub mod kv;
pub mod locker_mock_up;
pub mod mandate;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_key_store;
pub mod organization;
pub mod payment_attempt;
pub mod payment_intent;
pub mod payment_link;
pub mod payment_method;
pub mod payout_attempt;
pub mod payouts;
pub mod process_tracker;
pub mod query;
pub mod refund;
pub mod relay;
pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod subscription;
pub mod types;
pub mod unified_translations;
#[cfg(feature = "v2")]
pub mod payment_methods_session;
#[allow(unused_qualifications)]
pub mod schema;
#[allow(unused_qualifications)]
pub mod schema_v2;
pub mod user;
pub mod user_authentication_method;
pub mod user_key_store;
pub mod user_role;
use diesel_impl::{DieselArray, OptionalDieselArray};
#[cfg(feature = "v2")]
use diesel_impl::{RequiredFromNullable, RequiredFromNullableWithDefault};
pub type StorageResult<T> = error_stack::Result<T, errors::DatabaseError>;
pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>;
pub use self::{
address::*, api_keys::*, callback_mapper::*, cards_info::*, configs::*, customers::*,
dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*,
hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*, merchant_account::*,
merchant_connector_account::*, payment_attempt::*, payment_intent::*, payment_method::*,
payout_attempt::*, payouts::*, process_tracker::*, refund::*, reverse_lookup::*,
user_authentication_method::*,
};
/// The types and implementations provided by this module are required for the schema generated by
/// `diesel_cli` 2.0 to work with the types defined in Rust code. This is because
/// [`diesel`][diesel] 2.0 [changed the nullability of array elements][diesel-2.0-array-nullability],
/// which causes [`diesel`][diesel] to deserialize arrays as `Vec<Option<T>>`. To prevent declaring
/// array elements as `Option<T>`, this module provides types and implementations to deserialize
/// arrays as `Vec<T>`, considering only non-null values (`Some(T)`) among the deserialized
/// `Option<T>` values.
///
/// [diesel-2.0-array-nullability]: https://diesel.rs/guides/migration_guide.html#2-0-0-nullability-of-array-elements
#[doc(hidden)]
pub(crate) mod diesel_impl {
#[cfg(feature = "v2")]
use common_utils::{id_type, types};
use diesel::{
deserialize::FromSql,
pg::Pg,
sql_types::{Array, Nullable},
Queryable,
};
#[cfg(feature = "v2")]
use crate::enums;
pub struct DieselArray<T>(Vec<Option<T>>);
impl<T> From<DieselArray<T>> for Vec<T> {
fn from(array: DieselArray<T>) -> Self {
array.0.into_iter().flatten().collect()
}
}
impl<T, U> Queryable<Array<Nullable<U>>, Pg> for DieselArray<T>
where
T: FromSql<U, Pg>,
Vec<Option<T>>: FromSql<Array<Nullable<U>>, Pg>,
{
type Row = Vec<Option<T>>;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(Self(row))
}
}
pub struct OptionalDieselArray<T>(Option<Vec<Option<T>>>);
impl<T> From<OptionalDieselArray<T>> for Option<Vec<T>> {
fn from(option_array: OptionalDieselArray<T>) -> Self {
option_array
.0
.map(|array| array.into_iter().flatten().collect())
}
}
impl<T, U> Queryable<Nullable<Array<Nullable<U>>>, Pg> for OptionalDieselArray<T>
where
Option<Vec<Option<T>>>: FromSql<Nullable<Array<Nullable<U>>>, Pg>,
{
type Row = Option<Vec<Option<T>>>;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(Self(row))
}
}
#[cfg(feature = "v2")]
/// If the DB value is null, this wrapper will return an error when deserializing.
///
/// This is useful when you want to ensure that a field is always present, even if the database
/// value is NULL. If the database column contains a NULL value, an error will be returned.
pub struct RequiredFromNullable<T>(T);
#[cfg(feature = "v2")]
impl<T> RequiredFromNullable<T> {
/// Extracts the inner value from the wrapper
pub fn into_inner(self) -> T {
self.0
}
}
#[cfg(feature = "v2")]
impl<T, ST, DB> Queryable<Nullable<ST>, DB> for RequiredFromNullable<T>
where
DB: diesel::backend::Backend,
T: Queryable<ST, DB>,
Option<T::Row>: FromSql<Nullable<ST>, DB>,
ST: diesel::sql_types::SingleValue,
{
type Row = Option<T::Row>;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
match row {
Some(inner_row) => {
let value = T::build(inner_row)?;
Ok(Self(value))
}
None => Err("Cannot deserialize NULL value for required field. Check if the database column that should not be NULL contains a NULL value.".into()),
}
}
}
#[cfg(feature = "v2")]
/// If the DB value is null, this wrapper will provide a default value for the type `T`.
///
/// This is useful when you want to ensure that a field is always present, even if the database
/// value is NULL. The default value is provided by the `Default` trait implementation of `T`.
pub struct RequiredFromNullableWithDefault<T>(T);
#[cfg(feature = "v2")]
impl<T> RequiredFromNullableWithDefault<T> {
/// Extracts the inner value from the wrapper
pub fn into_inner(self) -> T {
self.0
}
}
#[cfg(feature = "v2")]
impl<T, ST, DB> Queryable<Nullable<ST>, DB> for RequiredFromNullableWithDefault<T>
where
DB: diesel::backend::Backend,
T: Queryable<ST, DB>,
T: Default,
Option<T::Row>: FromSql<Nullable<ST>, DB>,
ST: diesel::sql_types::SingleValue,
{
type Row = Option<T::Row>;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
match row {
Some(inner_row) => {
let value = T::build(inner_row)?;
Ok(Self(value))
}
None => Ok(Self(T::default())),
}
}
}
#[cfg(feature = "v2")]
/// Macro to implement From trait for types wrapped in RequiredFromNullable
#[macro_export]
macro_rules! impl_from_required_from_nullable {
($($type:ty),* $(,)?) => {
$(
impl From<$crate::RequiredFromNullable<$type>> for $type {
fn from(wrapper: $crate::RequiredFromNullable<$type>) -> Self {
wrapper.into_inner()
}
}
)*
};
}
#[cfg(feature = "v2")]
/// Macro to implement From trait for types wrapped in RequiredFromNullableWithDefault
#[macro_export]
macro_rules! impl_from_required_from_nullable_with_default {
($($type:ty),* $(,)?) => {
$(
impl From<$crate::RequiredFromNullableWithDefault<$type>> for $type {
fn from(wrapper: $crate::RequiredFromNullableWithDefault<$type>) -> Self {
wrapper.into_inner()
}
}
)*
};
}
#[cfg(feature = "v2")]
crate::impl_from_required_from_nullable_with_default!(enums::DeleteStatus);
#[cfg(feature = "v2")]
crate::impl_from_required_from_nullable!(
enums::AuthenticationType,
types::MinorUnit,
enums::PaymentMethod,
enums::Currency,
id_type::ProfileId,
time::PrimitiveDateTime,
id_type::RefundReferenceId,
);
}
pub(crate) mod metrics {
use router_env::{counter_metric, global_meter, histogram_metric_f64};
global_meter!(GLOBAL_METER, "ROUTER_API");
counter_metric!(DATABASE_CALLS_COUNT, GLOBAL_METER);
histogram_metric_f64!(DATABASE_CALL_TIME, GLOBAL_METER);
}
#[cfg(feature = "tokenization_v2")]
pub mod tokenization;
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/lib.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2030
}
|
large_file_-3608194933987304401
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/refund.rs
</path>
<file>
use common_utils::{
id_type, pii,
types::{ChargeRefunds, ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit},
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::enums as storage_enums;
#[cfg(feature = "v1")]
use crate::schema::refund;
#[cfg(feature = "v2")]
use crate::{schema_v2::refund, RequiredFromNullable};
#[cfg(feature = "v1")]
#[derive(
Clone,
Debug,
Eq,
Identifiable,
Queryable,
Selectable,
PartialEq,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = refund, primary_key(refund_id), check_for_backend(diesel::pg::Pg))]
pub struct Refund {
pub internal_reference_id: String,
pub refund_id: String, //merchant_reference id
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub external_reference_id: Option<String>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub refund_error_message: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: String,
pub refund_reason: Option<String>,
pub refund_error_code: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
/// INFO: This field is deprecated and replaced by processor_refund_data
pub connector_refund_data: Option<String>,
/// INFO: This field is deprecated and replaced by processor_transaction_data
pub connector_transaction_data: Option<String>,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
pub issuer_error_code: Option<String>,
pub issuer_error_message: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(
Clone,
Debug,
Eq,
Identifiable,
Queryable,
Selectable,
PartialEq,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = refund, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct Refund {
pub payment_id: id_type::GlobalPaymentId,
pub merchant_id: id_type::MerchantId,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub external_reference_id: Option<String>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub refund_error_message: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: id_type::GlobalAttemptId,
pub refund_reason: Option<String>,
pub refund_error_code: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
pub id: id_type::GlobalRefundId,
#[diesel(deserialize_as = RequiredFromNullable<id_type::RefundReferenceId>)]
pub merchant_reference_id: id_type::RefundReferenceId,
pub connector_id: Option<id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v1")]
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
router_derive::Setter,
)]
#[diesel(table_name = refund)]
pub struct RefundNew {
pub refund_id: String,
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub internal_reference_id: String,
pub external_reference_id: Option<String>,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: String,
pub refund_reason: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
router_derive::Setter,
)]
#[diesel(table_name = refund)]
pub struct RefundNew {
pub merchant_reference_id: id_type::RefundReferenceId,
pub payment_id: id_type::GlobalPaymentId,
pub merchant_id: id_type::MerchantId,
pub id: id_type::GlobalRefundId,
pub external_reference_id: Option<String>,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: id_type::GlobalAttemptId,
pub refund_reason: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub connector_id: Option<id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum RefundUpdate {
Update {
connector_refund_id: ConnectorTransactionId,
refund_status: storage_enums::RefundStatus,
sent_to_gateway: bool,
refund_error_message: Option<String>,
refund_arn: String,
updated_by: String,
processor_refund_data: Option<String>,
},
MetadataAndReasonUpdate {
metadata: Option<pii::SecretSerdeValue>,
reason: Option<String>,
updated_by: String,
},
StatusUpdate {
connector_refund_id: Option<ConnectorTransactionId>,
sent_to_gateway: bool,
refund_status: storage_enums::RefundStatus,
updated_by: String,
processor_refund_data: Option<String>,
},
ErrorUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
connector_refund_id: Option<ConnectorTransactionId>,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
issuer_error_code: Option<String>,
issuer_error_message: Option<String>,
},
ManualUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
},
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum RefundUpdate {
Update {
connector_refund_id: ConnectorTransactionId,
refund_status: storage_enums::RefundStatus,
sent_to_gateway: bool,
refund_error_message: Option<String>,
refund_arn: String,
updated_by: String,
processor_refund_data: Option<String>,
},
MetadataAndReasonUpdate {
metadata: Option<pii::SecretSerdeValue>,
reason: Option<String>,
updated_by: String,
},
StatusUpdate {
connector_refund_id: Option<ConnectorTransactionId>,
sent_to_gateway: bool,
refund_status: storage_enums::RefundStatus,
updated_by: String,
processor_refund_data: Option<String>,
},
ErrorUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
connector_refund_id: Option<ConnectorTransactionId>,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
},
ManualUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
},
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = refund)]
pub struct RefundUpdateInternal {
connector_refund_id: Option<ConnectorTransactionId>,
refund_status: Option<storage_enums::RefundStatus>,
sent_to_gateway: Option<bool>,
refund_error_message: Option<String>,
refund_arn: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
refund_reason: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
modified_at: PrimitiveDateTime,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
issuer_error_code: Option<String>,
issuer_error_message: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = refund)]
pub struct RefundUpdateInternal {
connector_refund_id: Option<ConnectorTransactionId>,
refund_status: Option<storage_enums::RefundStatus>,
sent_to_gateway: Option<bool>,
refund_error_message: Option<String>,
refund_arn: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
refund_reason: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
modified_at: PrimitiveDateTime,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
}
#[cfg(feature = "v1")]
impl RefundUpdateInternal {
pub fn create_refund(self, source: Refund) -> Refund {
Refund {
connector_refund_id: self.connector_refund_id,
refund_status: self.refund_status.unwrap_or_default(),
sent_to_gateway: self.sent_to_gateway.unwrap_or_default(),
refund_error_message: self.refund_error_message,
refund_arn: self.refund_arn,
metadata: self.metadata,
refund_reason: self.refund_reason,
refund_error_code: self.refund_error_code,
updated_by: self.updated_by,
modified_at: self.modified_at,
processor_refund_data: self.processor_refund_data,
unified_code: self.unified_code,
unified_message: self.unified_message,
..source
}
}
}
#[cfg(feature = "v2")]
impl RefundUpdateInternal {
pub fn create_refund(self, source: Refund) -> Refund {
Refund {
connector_refund_id: self.connector_refund_id,
refund_status: self.refund_status.unwrap_or_default(),
sent_to_gateway: self.sent_to_gateway.unwrap_or_default(),
refund_error_message: self.refund_error_message,
refund_arn: self.refund_arn,
metadata: self.metadata,
refund_reason: self.refund_reason,
refund_error_code: self.refund_error_code,
updated_by: self.updated_by,
modified_at: self.modified_at,
processor_refund_data: self.processor_refund_data,
unified_code: self.unified_code,
unified_message: self.unified_message,
..source
}
}
}
#[cfg(feature = "v1")]
impl From<RefundUpdate> for RefundUpdateInternal {
fn from(refund_update: RefundUpdate) -> Self {
match refund_update {
RefundUpdate::Update {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id: Some(connector_refund_id),
refund_status: Some(refund_status),
sent_to_gateway: Some(sent_to_gateway),
refund_error_message,
refund_arn: Some(refund_arn),
updated_by,
processor_refund_data,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
RefundUpdate::MetadataAndReasonUpdate {
metadata,
reason,
updated_by,
} => Self {
metadata,
refund_reason: reason,
updated_by,
connector_refund_id: None,
refund_status: None,
sent_to_gateway: None,
refund_error_message: None,
refund_arn: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
RefundUpdate::StatusUpdate {
connector_refund_id,
sent_to_gateway,
refund_status,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id,
sent_to_gateway: Some(sent_to_gateway),
refund_status: Some(refund_status),
updated_by,
processor_refund_data,
refund_error_message: None,
refund_arn: None,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
RefundUpdate::ErrorUpdate {
refund_status,
refund_error_message,
refund_error_code,
unified_code,
unified_message,
updated_by,
connector_refund_id,
processor_refund_data,
issuer_error_code,
issuer_error_message,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id,
processor_refund_data,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
unified_code,
unified_message,
issuer_error_code,
issuer_error_message,
},
RefundUpdate::ManualUpdate {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id: None,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
}
}
}
#[cfg(feature = "v2")]
impl From<RefundUpdate> for RefundUpdateInternal {
fn from(refund_update: RefundUpdate) -> Self {
match refund_update {
RefundUpdate::Update {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id: Some(connector_refund_id),
refund_status: Some(refund_status),
sent_to_gateway: Some(sent_to_gateway),
refund_error_message,
refund_arn: Some(refund_arn),
updated_by,
processor_refund_data,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
},
RefundUpdate::MetadataAndReasonUpdate {
metadata,
reason,
updated_by,
} => Self {
metadata,
refund_reason: reason,
updated_by,
connector_refund_id: None,
refund_status: None,
sent_to_gateway: None,
refund_error_message: None,
refund_arn: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
},
RefundUpdate::StatusUpdate {
connector_refund_id,
sent_to_gateway,
refund_status,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id,
sent_to_gateway: Some(sent_to_gateway),
refund_status: Some(refund_status),
updated_by,
processor_refund_data,
refund_error_message: None,
refund_arn: None,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
},
RefundUpdate::ErrorUpdate {
refund_status,
refund_error_message,
refund_error_code,
unified_code,
unified_message,
updated_by,
connector_refund_id,
processor_refund_data,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id,
processor_refund_data,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
unified_code,
unified_message,
},
RefundUpdate::ManualUpdate {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id: None,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
},
}
}
}
#[cfg(feature = "v1")]
impl RefundUpdate {
pub fn apply_changeset(self, source: Refund) -> Refund {
let RefundUpdateInternal {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
metadata,
refund_reason,
refund_error_code,
updated_by,
modified_at: _,
processor_refund_data,
unified_code,
unified_message,
issuer_error_code,
issuer_error_message,
} = self.into();
Refund {
connector_refund_id: connector_refund_id.or(source.connector_refund_id),
refund_status: refund_status.unwrap_or(source.refund_status),
sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway),
refund_error_message: refund_error_message.or(source.refund_error_message),
refund_error_code: refund_error_code.or(source.refund_error_code),
refund_arn: refund_arn.or(source.refund_arn),
metadata: metadata.or(source.metadata),
refund_reason: refund_reason.or(source.refund_reason),
updated_by,
modified_at: common_utils::date_time::now(),
processor_refund_data: processor_refund_data.or(source.processor_refund_data),
unified_code: unified_code.or(source.unified_code),
unified_message: unified_message.or(source.unified_message),
issuer_error_code: issuer_error_code.or(source.issuer_error_code),
issuer_error_message: issuer_error_message.or(source.issuer_error_message),
..source
}
}
}
#[cfg(feature = "v2")]
impl RefundUpdate {
pub fn apply_changeset(self, source: Refund) -> Refund {
let RefundUpdateInternal {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
metadata,
refund_reason,
refund_error_code,
updated_by,
modified_at: _,
processor_refund_data,
unified_code,
unified_message,
} = self.into();
Refund {
connector_refund_id: connector_refund_id.or(source.connector_refund_id),
refund_status: refund_status.unwrap_or(source.refund_status),
sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway),
refund_error_message: refund_error_message.or(source.refund_error_message),
refund_error_code: refund_error_code.or(source.refund_error_code),
refund_arn: refund_arn.or(source.refund_arn),
metadata: metadata.or(source.metadata),
refund_reason: refund_reason.or(source.refund_reason),
updated_by,
modified_at: common_utils::date_time::now(),
processor_refund_data: processor_refund_data.or(source.processor_refund_data),
unified_code: unified_code.or(source.unified_code),
unified_message: unified_message.or(source.unified_message),
..source
}
}
pub fn build_error_update_for_unified_error_and_message(
unified_error_object: (String, String),
refund_error_message: Option<String>,
refund_error_code: Option<String>,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
let (unified_code, unified_message) = unified_error_object;
Self::ErrorUpdate {
refund_status: Some(storage_enums::RefundStatus::Failure),
refund_error_message,
refund_error_code,
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: Some(unified_code),
unified_message: Some(unified_message),
}
}
pub fn build_error_update_for_integrity_check_failure(
integrity_check_failed_fields: String,
connector_refund_id: Option<ConnectorTransactionId>,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
Self::ErrorUpdate {
refund_status: Some(storage_enums::RefundStatus::ManualReview),
refund_error_message: Some(format!(
"Integrity Check Failed! as data mismatched for fields {integrity_check_failed_fields}"
)),
refund_error_code: Some("IE".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: connector_refund_id.clone(),
processor_refund_data: connector_refund_id.and_then(|x| x.extract_hashed_data()),
unified_code: None,
unified_message: None,
}
}
pub fn build_refund_update(
connector_refund_id: ConnectorTransactionId,
refund_status: storage_enums::RefundStatus,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
Self::Update {
connector_refund_id: connector_refund_id.clone(),
refund_status,
sent_to_gateway: true,
refund_error_message: None,
refund_arn: "".to_string(),
updated_by: storage_scheme.to_string(),
processor_refund_data: connector_refund_id.extract_hashed_data(),
}
}
pub fn build_error_update_for_refund_failure(
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
Self::ErrorUpdate {
refund_status,
refund_error_message,
refund_error_code,
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
}
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct RefundCoreWorkflow {
pub refund_internal_reference_id: String,
pub connector_transaction_id: ConnectorTransactionId,
pub merchant_id: id_type::MerchantId,
pub payment_id: id_type::PaymentId,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct RefundCoreWorkflow {
pub refund_id: id_type::GlobalRefundId,
pub connector_transaction_id: ConnectorTransactionId,
pub merchant_id: id_type::MerchantId,
pub payment_id: id_type::GlobalPaymentId,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v1")]
impl common_utils::events::ApiEventMetric for Refund {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Refund {
payment_id: Some(self.payment_id.clone()),
refund_id: self.refund_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for Refund {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Refund {
payment_id: Some(self.payment_id.clone()),
refund_id: self.id.clone(),
})
}
}
impl ConnectorTransactionIdTrait for Refund {
fn get_optional_connector_refund_id(&self) -> Option<&String> {
match self
.connector_refund_id
.as_ref()
.map(|refund_id| refund_id.get_txn_id(self.processor_refund_data.as_ref()))
.transpose()
{
Ok(refund_id) => refund_id,
// In case hashed data is missing from DB, use the hashed ID as connector transaction ID
Err(_) => self
.connector_refund_id
.as_ref()
.map(|txn_id| txn_id.get_id()),
}
}
fn get_connector_transaction_id(&self) -> &String {
match self
.connector_transaction_id
.get_txn_id(self.processor_transaction_data.as_ref())
{
Ok(txn_id) => txn_id,
// In case hashed data is missing from DB, use the hashed ID as connector transaction ID
Err(_) => self.connector_transaction_id.get_id(),
}
}
}
mod tests {
#[test]
fn test_backwards_compatibility() {
let serialized_refund = r#"{
"internal_reference_id": "internal_ref_123",
"refund_id": "refund_456",
"payment_id": "payment_789",
"merchant_id": "merchant_123",
"connector_transaction_id": "connector_txn_789",
"connector": "stripe",
"connector_refund_id": null,
"external_reference_id": null,
"refund_type": "instant_refund",
"total_amount": 10000,
"currency": "USD",
"refund_amount": 9500,
"refund_status": "Success",
"sent_to_gateway": true,
"refund_error_message": null,
"metadata": null,
"refund_arn": null,
"created_at": "2024-02-26T12:00:00Z",
"updated_at": "2024-02-26T12:00:00Z",
"description": null,
"attempt_id": "attempt_123",
"refund_reason": null,
"refund_error_code": null,
"profile_id": null,
"updated_by": "admin",
"merchant_connector_id": null,
"charges": null,
"connector_transaction_data": null
"unified_code": null,
"unified_message": null,
"processor_transaction_data": null,
}"#;
let deserialized = serde_json::from_str::<super::Refund>(serialized_refund);
assert!(deserialized.is_ok());
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/refund.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6700
}
|
large_file_1819139360882598034
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/process_tracker.rs
</path>
<file>
pub use common_enums::{enums::ProcessTrackerRunner, ApiVersion};
use common_utils::ext_traits::Encode;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, errors, schema::process_tracker, StorageResult};
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Deserialize,
Identifiable,
Queryable,
Selectable,
Serialize,
router_derive::DebugAsDisplay,
)]
#[diesel(table_name = process_tracker, check_for_backend(diesel::pg::Pg))]
pub struct ProcessTracker {
pub id: String,
pub name: Option<String>,
#[diesel(deserialize_as = super::DieselArray<String>)]
pub tag: Vec<String>,
pub runner: Option<String>,
pub retry_count: i32,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub schedule_time: Option<PrimitiveDateTime>,
pub rule: String,
pub tracking_data: serde_json::Value,
pub business_status: String,
pub status: storage_enums::ProcessTrackerStatus,
#[diesel(deserialize_as = super::DieselArray<String>)]
pub event: Vec<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub updated_at: PrimitiveDateTime,
pub version: ApiVersion,
}
impl ProcessTracker {
#[inline(always)]
pub fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool {
valid_statuses.iter().any(|&x| x == self.business_status)
}
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = process_tracker)]
pub struct ProcessTrackerNew {
pub id: String,
pub name: Option<String>,
pub tag: Vec<String>,
pub runner: Option<String>,
pub retry_count: i32,
pub schedule_time: Option<PrimitiveDateTime>,
pub rule: String,
pub tracking_data: serde_json::Value,
pub business_status: String,
pub status: storage_enums::ProcessTrackerStatus,
pub event: Vec<String>,
pub created_at: PrimitiveDateTime,
pub updated_at: PrimitiveDateTime,
pub version: ApiVersion,
}
impl ProcessTrackerNew {
#[allow(clippy::too_many_arguments)]
pub fn new<T>(
process_tracker_id: impl Into<String>,
task: impl Into<String>,
runner: ProcessTrackerRunner,
tag: impl IntoIterator<Item = impl Into<String>>,
tracking_data: T,
retry_count: Option<i32>,
schedule_time: PrimitiveDateTime,
api_version: ApiVersion,
) -> StorageResult<Self>
where
T: Serialize + std::fmt::Debug,
{
let current_time = common_utils::date_time::now();
Ok(Self {
id: process_tracker_id.into(),
name: Some(task.into()),
tag: tag.into_iter().map(Into::into).collect(),
runner: Some(runner.to_string()),
retry_count: retry_count.unwrap_or(0),
schedule_time: Some(schedule_time),
rule: String::new(),
tracking_data: tracking_data
.encode_to_value()
.change_context(errors::DatabaseError::Others)
.attach_printable("Failed to serialize process tracker tracking data")?,
business_status: String::from(business_status::PENDING),
status: storage_enums::ProcessTrackerStatus::New,
event: vec![],
created_at: current_time,
updated_at: current_time,
version: api_version,
})
}
}
#[derive(Debug)]
pub enum ProcessTrackerUpdate {
Update {
name: Option<String>,
retry_count: Option<i32>,
schedule_time: Option<PrimitiveDateTime>,
tracking_data: Option<serde_json::Value>,
business_status: Option<String>,
status: Option<storage_enums::ProcessTrackerStatus>,
updated_at: Option<PrimitiveDateTime>,
},
StatusUpdate {
status: storage_enums::ProcessTrackerStatus,
business_status: Option<String>,
},
StatusRetryUpdate {
status: storage_enums::ProcessTrackerStatus,
retry_count: i32,
schedule_time: PrimitiveDateTime,
},
}
#[derive(Debug, Clone, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = process_tracker)]
pub struct ProcessTrackerUpdateInternal {
name: Option<String>,
retry_count: Option<i32>,
schedule_time: Option<PrimitiveDateTime>,
tracking_data: Option<serde_json::Value>,
business_status: Option<String>,
status: Option<storage_enums::ProcessTrackerStatus>,
updated_at: Option<PrimitiveDateTime>,
}
impl Default for ProcessTrackerUpdateInternal {
fn default() -> Self {
Self {
name: Option::default(),
retry_count: Option::default(),
schedule_time: Option::default(),
tracking_data: Option::default(),
business_status: Option::default(),
status: Option::default(),
updated_at: Some(common_utils::date_time::now()),
}
}
}
impl From<ProcessTrackerUpdate> for ProcessTrackerUpdateInternal {
fn from(process_tracker_update: ProcessTrackerUpdate) -> Self {
match process_tracker_update {
ProcessTrackerUpdate::Update {
name,
retry_count,
schedule_time,
tracking_data,
business_status,
status,
updated_at,
} => Self {
name,
retry_count,
schedule_time,
tracking_data,
business_status,
status,
updated_at,
},
ProcessTrackerUpdate::StatusUpdate {
status,
business_status,
} => Self {
status: Some(status),
business_status,
..Default::default()
},
ProcessTrackerUpdate::StatusRetryUpdate {
status,
retry_count,
schedule_time,
} => Self {
status: Some(status),
retry_count: Some(retry_count),
schedule_time: Some(schedule_time),
..Default::default()
},
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use common_utils::ext_traits::StringExt;
use super::ProcessTrackerRunner;
#[test]
fn test_enum_to_string() {
let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string();
let enum_format: ProcessTrackerRunner =
string_format.parse_enum("ProcessTrackerRunner").unwrap();
assert_eq!(enum_format, ProcessTrackerRunner::PaymentsSyncWorkflow);
}
}
pub mod business_status {
/// Indicates that an irrecoverable error occurred during the workflow execution.
pub const GLOBAL_FAILURE: &str = "GLOBAL_FAILURE";
/// Task successfully completed by consumer.
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const COMPLETED_BY_PT: &str = "COMPLETED_BY_PT";
/// An error occurred during the workflow execution which prevents further execution and
/// retries.
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const FAILURE: &str = "FAILURE";
/// The resource associated with the task was removed, due to which further retries can/should
/// not be done.
pub const REVOKED: &str = "Revoked";
/// The task was executed for the maximum possible number of times without a successful outcome.
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const RETRIES_EXCEEDED: &str = "RETRIES_EXCEEDED";
/// The outgoing webhook was successfully delivered in the initial attempt.
/// Further retries of the task are not required.
pub const INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL: &str = "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL";
/// Indicates that an error occurred during the workflow execution.
/// This status is typically set by the workflow error handler.
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const GLOBAL_ERROR: &str = "GLOBAL_ERROR";
/// The resource associated with the task has been significantly modified since the task was
/// created, due to which further retries of the current task are not required.
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const RESOURCE_STATUS_MISMATCH: &str = "RESOURCE_STATUS_MISMATCH";
/// Business status set for newly created tasks.
pub const PENDING: &str = "Pending";
/// For the PCR Workflow
///
/// This status indicates the completion of a execute task
pub const EXECUTE_WORKFLOW_COMPLETE: &str = "COMPLETED_EXECUTE_TASK";
/// This status indicates the failure of a execute task
pub const EXECUTE_WORKFLOW_FAILURE: &str = "FAILED_EXECUTE_TASK";
/// This status indicates that the execute task was completed to trigger the psync task
pub const EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC: &str = "COMPLETED_EXECUTE_TASK_TO_TRIGGER_PSYNC";
/// This status indicates that the execute task was completed to trigger the review task
pub const EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW: &str =
"COMPLETED_EXECUTE_TASK_TO_TRIGGER_REVIEW";
/// This status indicates that the requeue was triggered for execute task
pub const EXECUTE_WORKFLOW_REQUEUE: &str = "TRIGGER_REQUEUE_FOR_EXECUTE_WORKFLOW";
/// This status indicates the completion of a psync task
pub const PSYNC_WORKFLOW_COMPLETE: &str = "COMPLETED_PSYNC_TASK";
/// This status indicates that the psync task was completed to trigger the review task
pub const PSYNC_WORKFLOW_COMPLETE_FOR_REVIEW: &str = "COMPLETED_PSYNC_TASK_TO_TRIGGER_REVIEW";
/// This status indicates that the requeue was triggered for psync task
pub const PSYNC_WORKFLOW_REQUEUE: &str = "TRIGGER_REQUEUE_FOR_PSYNC_WORKFLOW";
/// This status indicates the completion of a review task
pub const REVIEW_WORKFLOW_COMPLETE: &str = "COMPLETED_REVIEW_TASK";
/// For the CALCULATE_WORKFLOW
///
/// This status indicates an invoice is queued
pub const CALCULATE_WORKFLOW_QUEUED: &str = "CALCULATE_WORKFLOW_QUEUED";
/// This status indicates an invoice has been declined due to hard decline
pub const CALCULATE_WORKFLOW_FINISH: &str = "FAILED_DUE_TO_HARD_DECLINE_ERROR";
/// This status indicates that the invoice is scheduled with the best available token
pub const CALCULATE_WORKFLOW_SCHEDULED: &str = "CALCULATE_WORKFLOW_SCHEDULED";
/// This status indicates the invoice is in payment sync state
pub const CALCULATE_WORKFLOW_PROCESSING: &str = "CALCULATE_WORKFLOW_PROCESSING";
/// This status indicates the workflow has completed successfully when the invoice is paid
pub const CALCULATE_WORKFLOW_COMPLETE: &str = "CALCULATE_WORKFLOW_COMPLETE";
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/process_tracker.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2410
}
|
large_file_4157655083723291845
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/business_profile.rs
</path>
<file>
use std::collections::{HashMap, HashSet};
use common_enums::{AuthenticationConnectors, UIWidgetFormLayout, VaultSdk};
use common_types::primitive_wrappers;
use common_utils::{encryption::Encryption, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
use time::Duration;
#[cfg(feature = "v1")]
use crate::schema::business_profile;
#[cfg(feature = "v2")]
use crate::schema_v2::business_profile;
/// Note: The order of fields in the struct is important.
/// This should be in the same order as the fields in the schema.rs file, otherwise the code will
/// not compile
/// If two adjacent columns have the same type, then the compiler will not throw any error, but the
/// fields read / written will be interchanged
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile, primary_key(profile_id), check_for_backend(diesel::pg::Pg))]
pub struct Profile {
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub version: common_enums::ApiVersion,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: bool,
pub force_3ds_challenge: Option<bool>,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub id: Option<common_utils::id_type::ProfileId>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: Option<bool>,
pub three_ds_decision_rule_algorithm: Option<serde_json::Value>,
pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub is_l2_l3_enabled: Option<bool>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile, primary_key(profile_id))]
pub struct ProfileNew {
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub version: common_enums::ApiVersion,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: bool,
pub force_3ds_challenge: Option<bool>,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub id: Option<common_utils::id_type::ProfileId>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: Option<bool>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub is_l2_l3_enabled: Option<bool>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile)]
pub struct ProfileUpdateInternal {
pub profile_name: Option<String>,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<String>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub is_recon_enabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub is_l2_l3_enabled: Option<bool>,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: Option<bool>,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub is_click_to_pay_enabled: Option<bool>,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: Option<bool>,
pub force_3ds_challenge: Option<bool>,
pub is_debit_routing_enabled: Option<bool>,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: Option<bool>,
pub three_ds_decision_rule_algorithm: Option<serde_json::Value>,
pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
}
#[cfg(feature = "v1")]
impl ProfileUpdateInternal {
pub fn apply_changeset(self, source: Profile) -> Profile {
let Self {
profile_name,
modified_at,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
webhook_details,
metadata,
routing_algorithm,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
is_recon_enabled,
applepay_verified_domains,
payment_link_config,
session_expiry,
authentication_connector_details,
payout_link_config,
is_extended_card_info_enabled,
extended_card_info_config,
is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
is_l2_l3_enabled,
dynamic_routing_algorithm,
is_network_tokenization_enabled,
is_auto_retries_enabled,
max_auto_retries_enabled,
always_request_extended_authorization,
is_click_to_pay_enabled,
authentication_product_ids,
card_testing_guard_config,
card_testing_secret_key,
is_clear_pan_retries_enabled,
force_3ds_challenge,
is_debit_routing_enabled,
merchant_business_country,
is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled,
three_ds_decision_rule_algorithm,
acquirer_config_map,
merchant_category_code,
merchant_country_code,
dispute_polling_interval,
is_manual_retry_enabled,
always_enable_overcapture,
is_external_vault_enabled,
external_vault_connector_details,
billing_processor_id,
} = self;
Profile {
profile_id: source.profile_id,
merchant_id: source.merchant_id,
profile_name: profile_name.unwrap_or(source.profile_name),
created_at: source.created_at,
modified_at,
return_url: return_url.or(source.return_url),
enable_payment_response_hash: enable_payment_response_hash
.unwrap_or(source.enable_payment_response_hash),
payment_response_hash_key: payment_response_hash_key
.or(source.payment_response_hash_key),
redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post
.unwrap_or(source.redirect_to_merchant_with_http_post),
webhook_details: webhook_details.or(source.webhook_details),
metadata: metadata.or(source.metadata),
routing_algorithm: routing_algorithm.or(source.routing_algorithm),
intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time),
frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm),
payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm),
is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled),
applepay_verified_domains: applepay_verified_domains
.or(source.applepay_verified_domains),
payment_link_config: payment_link_config.or(source.payment_link_config),
session_expiry: session_expiry.or(source.session_expiry),
authentication_connector_details: authentication_connector_details
.or(source.authentication_connector_details),
payout_link_config: payout_link_config.or(source.payout_link_config),
is_extended_card_info_enabled: is_extended_card_info_enabled
.or(source.is_extended_card_info_enabled),
is_connector_agnostic_mit_enabled: is_connector_agnostic_mit_enabled
.or(source.is_connector_agnostic_mit_enabled),
extended_card_info_config: extended_card_info_config
.or(source.extended_card_info_config),
use_billing_as_payment_method_billing: use_billing_as_payment_method_billing
.or(source.use_billing_as_payment_method_billing),
collect_shipping_details_from_wallet_connector:
collect_shipping_details_from_wallet_connector
.or(source.collect_shipping_details_from_wallet_connector),
collect_billing_details_from_wallet_connector:
collect_billing_details_from_wallet_connector
.or(source.collect_billing_details_from_wallet_connector),
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.or(source.outgoing_webhook_custom_http_headers),
always_collect_billing_details_from_wallet_connector:
always_collect_billing_details_from_wallet_connector
.or(source.always_collect_billing_details_from_wallet_connector),
always_collect_shipping_details_from_wallet_connector:
always_collect_shipping_details_from_wallet_connector
.or(source.always_collect_shipping_details_from_wallet_connector),
tax_connector_id: tax_connector_id.or(source.tax_connector_id),
is_tax_connector_enabled: is_tax_connector_enabled.or(source.is_tax_connector_enabled),
is_l2_l3_enabled: is_l2_l3_enabled.or(source.is_l2_l3_enabled),
version: source.version,
dynamic_routing_algorithm: dynamic_routing_algorithm
.or(source.dynamic_routing_algorithm),
is_network_tokenization_enabled: is_network_tokenization_enabled
.unwrap_or(source.is_network_tokenization_enabled),
is_auto_retries_enabled: is_auto_retries_enabled.or(source.is_auto_retries_enabled),
max_auto_retries_enabled: max_auto_retries_enabled.or(source.max_auto_retries_enabled),
always_request_extended_authorization: always_request_extended_authorization
.or(source.always_request_extended_authorization),
is_click_to_pay_enabled: is_click_to_pay_enabled
.unwrap_or(source.is_click_to_pay_enabled),
authentication_product_ids: authentication_product_ids
.or(source.authentication_product_ids),
card_testing_guard_config: card_testing_guard_config
.or(source.card_testing_guard_config),
card_testing_secret_key,
is_clear_pan_retries_enabled: is_clear_pan_retries_enabled
.unwrap_or(source.is_clear_pan_retries_enabled),
force_3ds_challenge,
id: source.id,
is_debit_routing_enabled: is_debit_routing_enabled
.unwrap_or(source.is_debit_routing_enabled),
merchant_business_country: merchant_business_country
.or(source.merchant_business_country),
is_iframe_redirection_enabled: is_iframe_redirection_enabled
.or(source.is_iframe_redirection_enabled),
is_pre_network_tokenization_enabled: is_pre_network_tokenization_enabled
.or(source.is_pre_network_tokenization_enabled),
three_ds_decision_rule_algorithm: three_ds_decision_rule_algorithm
.or(source.three_ds_decision_rule_algorithm),
acquirer_config_map: acquirer_config_map.or(source.acquirer_config_map),
merchant_category_code: merchant_category_code.or(source.merchant_category_code),
merchant_country_code: merchant_country_code.or(source.merchant_country_code),
dispute_polling_interval: dispute_polling_interval.or(source.dispute_polling_interval),
is_manual_retry_enabled: is_manual_retry_enabled.or(source.is_manual_retry_enabled),
always_enable_overcapture: always_enable_overcapture
.or(source.always_enable_overcapture),
is_external_vault_enabled: is_external_vault_enabled
.or(source.is_external_vault_enabled),
external_vault_connector_details: external_vault_connector_details
.or(source.external_vault_connector_details),
billing_processor_id: billing_processor_id.or(source.billing_processor_id),
}
}
}
/// Note: The order of fields in the struct is important.
/// This should be in the same order as the fields in the schema.rs file, otherwise the code will
/// not compile
/// If two adjacent columns have the same type, then the compiler will not throw any error, but the
/// fields read / written will be interchanged
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct Profile {
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<common_utils::types::Url>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub version: common_enums::ApiVersion,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: bool,
pub force_3ds_challenge: Option<bool>,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub id: common_utils::id_type::ProfileId,
pub is_iframe_redirection_enabled: Option<bool>,
pub three_ds_decision_rule_algorithm: Option<serde_json::Value>,
pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub is_l2_l3_enabled: Option<bool>,
pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>,
pub should_collect_cvv_during_payment:
Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>,
pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>,
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
}
impl Profile {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &common_utils::id_type::ProfileId {
&self.profile_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::ProfileId {
&self.id
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile, primary_key(profile_id))]
pub struct ProfileNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<common_utils::types::Url>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub version: common_enums::ApiVersion,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: Option<bool>,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>,
pub should_collect_cvv_during_payment:
Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
pub id: common_utils::id_type::ProfileId,
pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>,
pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub is_l2_l3_enabled: Option<bool>,
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = business_profile)]
pub struct ProfileUpdateInternal {
pub profile_name: Option<String>,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<common_utils::types::Url>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub is_recon_enabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: Option<Encryption>,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub is_network_tokenization_enabled: Option<bool>,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub is_click_to_pay_enabled: Option<bool>,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: Option<Encryption>,
pub is_clear_pan_retries_enabled: Option<bool>,
pub is_debit_routing_enabled: Option<bool>,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>,
pub should_collect_cvv_during_payment:
Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>,
pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub is_l2_l3_enabled: Option<bool>,
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
}
#[cfg(feature = "v2")]
impl ProfileUpdateInternal {
pub fn apply_changeset(self, source: Profile) -> Profile {
let Self {
profile_name,
modified_at,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
webhook_details,
metadata,
is_recon_enabled,
applepay_verified_domains,
payment_link_config,
session_expiry,
authentication_connector_details,
payout_link_config,
is_extended_card_info_enabled,
extended_card_info_config,
is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
billing_processor_id,
routing_algorithm_id,
order_fulfillment_time,
order_fulfillment_time_origin,
frm_routing_algorithm_id,
payout_routing_algorithm_id,
default_fallback_routing,
should_collect_cvv_during_payment,
is_network_tokenization_enabled,
is_auto_retries_enabled,
max_auto_retries_enabled,
is_click_to_pay_enabled,
authentication_product_ids,
three_ds_decision_manager_config,
card_testing_guard_config,
card_testing_secret_key,
is_clear_pan_retries_enabled,
is_debit_routing_enabled,
merchant_business_country,
revenue_recovery_retry_algorithm_type,
revenue_recovery_retry_algorithm_data,
is_iframe_redirection_enabled,
is_external_vault_enabled,
external_vault_connector_details,
merchant_category_code,
merchant_country_code,
split_txns_enabled,
is_l2_l3_enabled,
} = self;
Profile {
id: source.id,
merchant_id: source.merchant_id,
profile_name: profile_name.unwrap_or(source.profile_name),
created_at: source.created_at,
modified_at,
return_url: return_url.or(source.return_url),
enable_payment_response_hash: enable_payment_response_hash
.unwrap_or(source.enable_payment_response_hash),
payment_response_hash_key: payment_response_hash_key
.or(source.payment_response_hash_key),
redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post
.unwrap_or(source.redirect_to_merchant_with_http_post),
webhook_details: webhook_details.or(source.webhook_details),
metadata: metadata.or(source.metadata),
is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled),
applepay_verified_domains: applepay_verified_domains
.or(source.applepay_verified_domains),
payment_link_config: payment_link_config.or(source.payment_link_config),
session_expiry: session_expiry.or(source.session_expiry),
authentication_connector_details: authentication_connector_details
.or(source.authentication_connector_details),
payout_link_config: payout_link_config.or(source.payout_link_config),
is_extended_card_info_enabled: is_extended_card_info_enabled
.or(source.is_extended_card_info_enabled),
is_connector_agnostic_mit_enabled: is_connector_agnostic_mit_enabled
.or(source.is_connector_agnostic_mit_enabled),
extended_card_info_config: extended_card_info_config
.or(source.extended_card_info_config),
use_billing_as_payment_method_billing: use_billing_as_payment_method_billing
.or(source.use_billing_as_payment_method_billing),
collect_shipping_details_from_wallet_connector:
collect_shipping_details_from_wallet_connector
.or(source.collect_shipping_details_from_wallet_connector),
collect_billing_details_from_wallet_connector:
collect_billing_details_from_wallet_connector
.or(source.collect_billing_details_from_wallet_connector),
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.or(source.outgoing_webhook_custom_http_headers),
always_collect_billing_details_from_wallet_connector:
always_collect_billing_details_from_wallet_connector
.or(always_collect_billing_details_from_wallet_connector),
always_collect_shipping_details_from_wallet_connector:
always_collect_shipping_details_from_wallet_connector
.or(always_collect_shipping_details_from_wallet_connector),
tax_connector_id: tax_connector_id.or(source.tax_connector_id),
is_tax_connector_enabled: is_tax_connector_enabled.or(source.is_tax_connector_enabled),
routing_algorithm_id: routing_algorithm_id.or(source.routing_algorithm_id),
order_fulfillment_time: order_fulfillment_time.or(source.order_fulfillment_time),
order_fulfillment_time_origin: order_fulfillment_time_origin
.or(source.order_fulfillment_time_origin),
frm_routing_algorithm_id: frm_routing_algorithm_id.or(source.frm_routing_algorithm_id),
payout_routing_algorithm_id: payout_routing_algorithm_id
.or(source.payout_routing_algorithm_id),
default_fallback_routing: default_fallback_routing.or(source.default_fallback_routing),
should_collect_cvv_during_payment: should_collect_cvv_during_payment
.or(source.should_collect_cvv_during_payment),
version: source.version,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: is_network_tokenization_enabled
.unwrap_or(source.is_network_tokenization_enabled),
is_auto_retries_enabled: is_auto_retries_enabled.or(source.is_auto_retries_enabled),
max_auto_retries_enabled: max_auto_retries_enabled.or(source.max_auto_retries_enabled),
always_request_extended_authorization: None,
is_click_to_pay_enabled: is_click_to_pay_enabled
.unwrap_or(source.is_click_to_pay_enabled),
authentication_product_ids: authentication_product_ids
.or(source.authentication_product_ids),
three_ds_decision_manager_config: three_ds_decision_manager_config
.or(source.three_ds_decision_manager_config),
card_testing_guard_config: card_testing_guard_config
.or(source.card_testing_guard_config),
card_testing_secret_key: card_testing_secret_key.or(source.card_testing_secret_key),
is_clear_pan_retries_enabled: is_clear_pan_retries_enabled
.unwrap_or(source.is_clear_pan_retries_enabled),
force_3ds_challenge: None,
is_debit_routing_enabled: is_debit_routing_enabled
.unwrap_or(source.is_debit_routing_enabled),
merchant_business_country: merchant_business_country
.or(source.merchant_business_country),
revenue_recovery_retry_algorithm_type: revenue_recovery_retry_algorithm_type
.or(source.revenue_recovery_retry_algorithm_type),
revenue_recovery_retry_algorithm_data: revenue_recovery_retry_algorithm_data
.or(source.revenue_recovery_retry_algorithm_data),
is_iframe_redirection_enabled: is_iframe_redirection_enabled
.or(source.is_iframe_redirection_enabled),
is_external_vault_enabled: is_external_vault_enabled
.or(source.is_external_vault_enabled),
external_vault_connector_details: external_vault_connector_details
.or(source.external_vault_connector_details),
three_ds_decision_rule_algorithm: None,
acquirer_config_map: None,
merchant_category_code: merchant_category_code.or(source.merchant_category_code),
merchant_country_code: merchant_country_code.or(source.merchant_country_code),
dispute_polling_interval: None,
split_txns_enabled: split_txns_enabled.or(source.split_txns_enabled),
is_manual_retry_enabled: None,
always_enable_overcapture: None,
is_l2_l3_enabled: None,
billing_processor_id: billing_processor_id.or(source.billing_processor_id),
}
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct AuthenticationConnectorDetails {
pub authentication_connectors: Vec<AuthenticationConnectors>,
pub three_ds_requestor_url: String,
pub three_ds_requestor_app_url: Option<String>,
}
common_utils::impl_to_sql_from_sql_json!(AuthenticationConnectorDetails);
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct ExternalVaultConnectorDetails {
pub vault_connector_id: common_utils::id_type::MerchantConnectorAccountId,
pub vault_sdk: Option<VaultSdk>,
}
common_utils::impl_to_sql_from_sql_json!(ExternalVaultConnectorDetails);
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct CardTestingGuardConfig {
pub is_card_ip_blocking_enabled: bool,
pub card_ip_blocking_threshold: i32,
pub is_guest_user_card_blocking_enabled: bool,
pub guest_user_card_blocking_threshold: i32,
pub is_customer_id_blocking_enabled: bool,
pub customer_id_blocking_threshold: i32,
pub card_testing_guard_expiry: i32,
}
common_utils::impl_to_sql_from_sql_json!(CardTestingGuardConfig);
impl Default for CardTestingGuardConfig {
fn default() -> Self {
Self {
is_card_ip_blocking_enabled: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_STATUS,
card_ip_blocking_threshold: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_THRESHOLD,
is_guest_user_card_blocking_enabled:
common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS,
guest_user_card_blocking_threshold:
common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD,
is_customer_id_blocking_enabled:
common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_STATUS,
customer_id_blocking_threshold:
common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD,
card_testing_guard_expiry:
common_utils::consts::DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS,
}
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MultipleWebhookDetail {
pub webhook_endpoint_id: common_utils::id_type::WebhookEndpointId,
pub webhook_url: Secret<String>,
pub events: HashSet<common_enums::EventType>,
pub status: common_enums::OutgoingWebhookEndpointStatus,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Json)]
pub struct WebhookDetails {
pub webhook_version: Option<String>,
pub webhook_username: Option<String>,
pub webhook_password: Option<Secret<String>>,
pub webhook_url: Option<Secret<String>>,
pub payment_created_enabled: Option<bool>,
pub payment_succeeded_enabled: Option<bool>,
pub payment_failed_enabled: Option<bool>,
pub payment_statuses_enabled: Option<Vec<common_enums::IntentStatus>>,
pub refund_statuses_enabled: Option<Vec<common_enums::RefundStatus>>,
pub payout_statuses_enabled: Option<Vec<common_enums::PayoutStatus>>,
pub multiple_webhooks_list: Option<Vec<MultipleWebhookDetail>>,
}
common_utils::impl_to_sql_from_sql_json!(WebhookDetails);
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct BusinessPaymentLinkConfig {
pub domain_name: Option<String>,
#[serde(flatten)]
pub default_config: Option<PaymentLinkConfigRequest>,
pub business_specific_configs: Option<HashMap<String, PaymentLinkConfigRequest>>,
pub allowed_domains: Option<HashSet<String>>,
pub branding_visibility: Option<bool>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PaymentLinkConfigRequest {
pub theme: Option<String>,
pub logo: Option<String>,
pub seller_name: Option<String>,
pub sdk_layout: Option<String>,
pub display_sdk_only: Option<bool>,
pub enabled_saved_payment_method: Option<bool>,
pub hide_card_nickname_field: Option<bool>,
pub show_card_form_by_default: Option<bool>,
pub background_image: Option<PaymentLinkBackgroundImageConfig>,
pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>,
pub payment_button_text: Option<String>,
pub custom_message_for_card_terms: Option<String>,
pub payment_button_colour: Option<String>,
pub skip_status_screen: Option<bool>,
pub payment_button_text_colour: Option<String>,
pub background_colour: Option<String>,
pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>,
pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>,
pub enable_button_only_on_form_ready: Option<bool>,
pub payment_form_header_text: Option<String>,
pub payment_form_label_type: Option<common_enums::PaymentLinkSdkLabelType>,
pub show_card_terms: Option<common_enums::PaymentLinkShowSdkTerms>,
pub is_setup_mandate_flow: Option<bool>,
pub color_icon_card_cvc_error: Option<String>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)]
pub struct PaymentLinkBackgroundImageConfig {
pub url: common_utils::types::Url,
pub position: Option<common_enums::ElementPosition>,
pub size: Option<common_enums::ElementSize>,
}
common_utils::impl_to_sql_from_sql_json!(BusinessPaymentLinkConfig);
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct BusinessPayoutLinkConfig {
#[serde(flatten)]
pub config: BusinessGenericLinkConfig,
pub form_layout: Option<UIWidgetFormLayout>,
pub payout_test_mode: Option<bool>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct BusinessGenericLinkConfig {
pub domain_name: Option<String>,
pub allowed_domains: HashSet<String>,
#[serde(flatten)]
pub ui_config: common_utils::link_utils::GenericLinkUiConfig,
}
common_utils::impl_to_sql_from_sql_json!(BusinessPayoutLinkConfig);
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct RevenueRecoveryAlgorithmData {
pub monitoring_configured_timestamp: time::PrimitiveDateTime,
}
impl RevenueRecoveryAlgorithmData {
pub fn has_exceeded_monitoring_threshold(&self, monitoring_threshold_in_seconds: i64) -> bool {
let total_threshold_time = self.monitoring_configured_timestamp
+ Duration::seconds(monitoring_threshold_in_seconds);
common_utils::date_time::now() >= total_threshold_time
}
}
common_utils::impl_to_sql_from_sql_json!(RevenueRecoveryAlgorithmData);
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/business_profile.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 9783
}
|
large_file_5024752540630922007
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/schema.rs
</path>
<file>
// @generated automatically by Diesel CLI.
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
address (address_id) {
#[max_length = 64]
address_id -> Varchar,
#[max_length = 128]
city -> Nullable<Varchar>,
country -> Nullable<CountryAlpha2>,
line1 -> Nullable<Bytea>,
line2 -> Nullable<Bytea>,
line3 -> Nullable<Bytea>,
state -> Nullable<Bytea>,
zip -> Nullable<Bytea>,
first_name -> Nullable<Bytea>,
last_name -> Nullable<Bytea>,
phone_number -> Nullable<Bytea>,
#[max_length = 8]
country_code -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
email -> Nullable<Bytea>,
origin_zip -> Nullable<Bytea>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
api_keys (key_id) {
#[max_length = 64]
key_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
name -> Varchar,
#[max_length = 256]
description -> Nullable<Varchar>,
#[max_length = 128]
hashed_api_key -> Varchar,
#[max_length = 16]
prefix -> Varchar,
created_at -> Timestamp,
expires_at -> Nullable<Timestamp>,
last_used -> Nullable<Timestamp>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
authentication (authentication_id) {
#[max_length = 64]
authentication_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
authentication_connector -> Nullable<Varchar>,
#[max_length = 64]
connector_authentication_id -> Nullable<Varchar>,
authentication_data -> Nullable<Jsonb>,
#[max_length = 64]
payment_method_id -> Varchar,
#[max_length = 64]
authentication_type -> Nullable<Varchar>,
#[max_length = 64]
authentication_status -> Varchar,
#[max_length = 64]
authentication_lifecycle_status -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
error_message -> Nullable<Text>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
connector_metadata -> Nullable<Jsonb>,
maximum_supported_version -> Nullable<Jsonb>,
#[max_length = 64]
threeds_server_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
cavv -> Nullable<Varchar>,
#[max_length = 64]
authentication_flow_type -> Nullable<Varchar>,
message_version -> Nullable<Jsonb>,
#[max_length = 64]
eci -> Nullable<Varchar>,
#[max_length = 64]
trans_status -> Nullable<Varchar>,
#[max_length = 64]
acquirer_bin -> Nullable<Varchar>,
#[max_length = 64]
acquirer_merchant_id -> Nullable<Varchar>,
three_ds_method_data -> Nullable<Varchar>,
three_ds_method_url -> Nullable<Varchar>,
acs_url -> Nullable<Varchar>,
challenge_request -> Nullable<Varchar>,
acs_reference_number -> Nullable<Varchar>,
acs_trans_id -> Nullable<Varchar>,
acs_signed_content -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 255]
payment_id -> Nullable<Varchar>,
#[max_length = 128]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
ds_trans_id -> Nullable<Varchar>,
#[max_length = 128]
directory_server_id -> Nullable<Varchar>,
#[max_length = 64]
acquirer_country_code -> Nullable<Varchar>,
service_details -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 128]
authentication_client_secret -> Nullable<Varchar>,
force_3ds_challenge -> Nullable<Bool>,
psd2_sca_exemption_type -> Nullable<ScaExemptionType>,
#[max_length = 2048]
return_url -> Nullable<Varchar>,
amount -> Nullable<Int8>,
currency -> Nullable<Currency>,
billing_address -> Nullable<Bytea>,
shipping_address -> Nullable<Bytea>,
browser_info -> Nullable<Jsonb>,
email -> Nullable<Bytea>,
#[max_length = 128]
profile_acquirer_id -> Nullable<Varchar>,
challenge_code -> Nullable<Varchar>,
challenge_cancel -> Nullable<Varchar>,
challenge_code_reason -> Nullable<Varchar>,
message_extension -> Nullable<Jsonb>,
#[max_length = 255]
challenge_request_key -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist (merchant_id, fingerprint_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_fingerprint (merchant_id, fingerprint_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
fingerprint_id -> Varchar,
data_kind -> BlocklistDataKind,
encrypted_fingerprint -> Text,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
blocklist_lookup (merchant_id, fingerprint) {
#[max_length = 64]
merchant_id -> Varchar,
fingerprint -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
business_profile (profile_id) {
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_name -> Varchar,
created_at -> Timestamp,
modified_at -> Timestamp,
return_url -> Nullable<Text>,
enable_payment_response_hash -> Bool,
#[max_length = 255]
payment_response_hash_key -> Nullable<Varchar>,
redirect_to_merchant_with_http_post -> Bool,
webhook_details -> Nullable<Json>,
metadata -> Nullable<Json>,
routing_algorithm -> Nullable<Json>,
intent_fulfillment_time -> Nullable<Int8>,
frm_routing_algorithm -> Nullable<Jsonb>,
payout_routing_algorithm -> Nullable<Jsonb>,
is_recon_enabled -> Bool,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
payment_link_config -> Nullable<Jsonb>,
session_expiry -> Nullable<Int8>,
authentication_connector_details -> Nullable<Jsonb>,
payout_link_config -> Nullable<Jsonb>,
is_extended_card_info_enabled -> Nullable<Bool>,
extended_card_info_config -> Nullable<Jsonb>,
is_connector_agnostic_mit_enabled -> Nullable<Bool>,
use_billing_as_payment_method_billing -> Nullable<Bool>,
collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
collect_billing_details_from_wallet_connector -> Nullable<Bool>,
outgoing_webhook_custom_http_headers -> Nullable<Bytea>,
always_collect_billing_details_from_wallet_connector -> Nullable<Bool>,
always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
#[max_length = 64]
tax_connector_id -> Nullable<Varchar>,
is_tax_connector_enabled -> Nullable<Bool>,
version -> ApiVersion,
dynamic_routing_algorithm -> Nullable<Json>,
is_network_tokenization_enabled -> Bool,
is_auto_retries_enabled -> Nullable<Bool>,
max_auto_retries_enabled -> Nullable<Int2>,
always_request_extended_authorization -> Nullable<Bool>,
is_click_to_pay_enabled -> Bool,
authentication_product_ids -> Nullable<Jsonb>,
card_testing_guard_config -> Nullable<Jsonb>,
card_testing_secret_key -> Nullable<Bytea>,
is_clear_pan_retries_enabled -> Bool,
force_3ds_challenge -> Nullable<Bool>,
is_debit_routing_enabled -> Bool,
merchant_business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
id -> Nullable<Varchar>,
is_iframe_redirection_enabled -> Nullable<Bool>,
is_pre_network_tokenization_enabled -> Nullable<Bool>,
three_ds_decision_rule_algorithm -> Nullable<Jsonb>,
acquirer_config_map -> Nullable<Jsonb>,
#[max_length = 16]
merchant_category_code -> Nullable<Varchar>,
#[max_length = 32]
merchant_country_code -> Nullable<Varchar>,
dispute_polling_interval -> Nullable<Int4>,
is_manual_retry_enabled -> Nullable<Bool>,
always_enable_overcapture -> Nullable<Bool>,
#[max_length = 64]
billing_processor_id -> Nullable<Varchar>,
is_external_vault_enabled -> Nullable<Bool>,
external_vault_connector_details -> Nullable<Jsonb>,
is_l2_l3_enabled -> Nullable<Bool>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
callback_mapper (id, type_) {
#[max_length = 128]
id -> Varchar,
#[sql_name = "type"]
#[max_length = 64]
type_ -> Varchar,
data -> Jsonb,
created_at -> Timestamp,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
captures (capture_id) {
#[max_length = 64]
capture_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
status -> CaptureStatus,
amount -> Int8,
currency -> Nullable<Currency>,
#[max_length = 255]
connector -> Varchar,
#[max_length = 255]
error_message -> Nullable<Varchar>,
#[max_length = 255]
error_code -> Nullable<Varchar>,
#[max_length = 255]
error_reason -> Nullable<Varchar>,
tax_amount -> Nullable<Int8>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
authorized_attempt_id -> Varchar,
#[max_length = 128]
connector_capture_id -> Nullable<Varchar>,
capture_sequence -> Int2,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
#[max_length = 512]
connector_capture_data -> Nullable<Varchar>,
processor_capture_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
cards_info (card_iin) {
#[max_length = 16]
card_iin -> Varchar,
card_issuer -> Nullable<Text>,
card_network -> Nullable<Text>,
card_type -> Nullable<Text>,
card_subtype -> Nullable<Text>,
card_issuing_country -> Nullable<Text>,
#[max_length = 32]
bank_code_id -> Nullable<Varchar>,
#[max_length = 32]
bank_code -> Nullable<Varchar>,
#[max_length = 32]
country_code -> Nullable<Varchar>,
date_created -> Timestamp,
last_updated -> Nullable<Timestamp>,
last_updated_provider -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
configs (key) {
#[max_length = 255]
key -> Varchar,
config -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
customers (customer_id, merchant_id) {
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
name -> Nullable<Bytea>,
email -> Nullable<Bytea>,
phone -> Nullable<Bytea>,
#[max_length = 8]
phone_country_code -> Nullable<Varchar>,
#[max_length = 255]
description -> Nullable<Varchar>,
created_at -> Timestamp,
metadata -> Nullable<Json>,
connector_customer -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
address_id -> Nullable<Varchar>,
#[max_length = 64]
default_payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
version -> ApiVersion,
tax_registration_id -> Nullable<Bytea>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dashboard_metadata (id) {
id -> Int4,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
org_id -> Varchar,
data_key -> DashboardMetadata,
data_value -> Json,
#[max_length = 64]
created_by -> Varchar,
created_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dispute (dispute_id) {
#[max_length = 64]
dispute_id -> Varchar,
#[max_length = 255]
amount -> Varchar,
#[max_length = 255]
currency -> Varchar,
dispute_stage -> DisputeStage,
dispute_status -> DisputeStatus,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
connector_status -> Varchar,
#[max_length = 255]
connector_dispute_id -> Varchar,
#[max_length = 255]
connector_reason -> Nullable<Varchar>,
#[max_length = 255]
connector_reason_code -> Nullable<Varchar>,
challenge_required_by -> Nullable<Timestamp>,
connector_created_at -> Nullable<Timestamp>,
connector_updated_at -> Nullable<Timestamp>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 255]
connector -> Varchar,
evidence -> Jsonb,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
dispute_amount -> Int8,
#[max_length = 32]
organization_id -> Varchar,
dispute_currency -> Nullable<Currency>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
dynamic_routing_stats (attempt_id, merchant_id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
amount -> Int8,
#[max_length = 64]
success_based_routing_connector -> Varchar,
#[max_length = 64]
payment_connector -> Varchar,
currency -> Nullable<Currency>,
#[max_length = 64]
payment_method -> Nullable<Varchar>,
capture_method -> Nullable<CaptureMethod>,
authentication_type -> Nullable<AuthenticationType>,
payment_status -> AttemptStatus,
conclusive_classification -> SuccessBasedRoutingConclusiveState,
created_at -> Timestamp,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
#[max_length = 64]
global_success_based_connector -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
events (event_id) {
#[max_length = 64]
event_id -> Varchar,
event_type -> EventType,
event_class -> EventClass,
is_webhook_notified -> Bool,
#[max_length = 64]
primary_object_id -> Varchar,
primary_object_type -> EventObjectType,
created_at -> Timestamp,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
business_profile_id -> Nullable<Varchar>,
primary_object_created_at -> Nullable<Timestamp>,
#[max_length = 64]
idempotent_event_id -> Nullable<Varchar>,
#[max_length = 64]
initial_attempt_id -> Nullable<Varchar>,
request -> Nullable<Bytea>,
response -> Nullable<Bytea>,
delivery_attempt -> Nullable<WebhookDeliveryAttempt>,
metadata -> Nullable<Jsonb>,
is_overall_delivery_successful -> Nullable<Bool>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
file_metadata (file_id, merchant_id) {
#[max_length = 64]
file_id -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
file_name -> Nullable<Varchar>,
file_size -> Int4,
#[max_length = 255]
file_type -> Varchar,
#[max_length = 255]
provider_file_id -> Nullable<Varchar>,
#[max_length = 255]
file_upload_provider -> Nullable<Varchar>,
available -> Bool,
created_at -> Timestamp,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
fraud_check (frm_id, attempt_id, payment_id, merchant_id) {
#[max_length = 64]
frm_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
created_at -> Timestamp,
#[max_length = 255]
frm_name -> Varchar,
#[max_length = 255]
frm_transaction_id -> Nullable<Varchar>,
frm_transaction_type -> FraudCheckType,
frm_status -> FraudCheckStatus,
frm_score -> Nullable<Int4>,
frm_reason -> Nullable<Jsonb>,
#[max_length = 255]
frm_error -> Nullable<Varchar>,
payment_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
modified_at -> Timestamp,
#[max_length = 64]
last_step -> Varchar,
payment_capture_method -> Nullable<CaptureMethod>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
gateway_status_map (connector, flow, sub_flow, code, message) {
#[max_length = 64]
connector -> Varchar,
#[max_length = 64]
flow -> Varchar,
#[max_length = 64]
sub_flow -> Varchar,
#[max_length = 255]
code -> Varchar,
#[max_length = 1024]
message -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 64]
router_error -> Nullable<Varchar>,
#[max_length = 64]
decision -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
step_up_possible -> Bool,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
#[max_length = 64]
error_category -> Nullable<Varchar>,
clear_pan_possible -> Bool,
feature_data -> Nullable<Jsonb>,
#[max_length = 64]
feature -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
generic_link (link_id) {
#[max_length = 64]
link_id -> Varchar,
#[max_length = 64]
primary_reference -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
created_at -> Timestamp,
last_modified_at -> Timestamp,
expiry -> Timestamp,
link_data -> Jsonb,
link_status -> Jsonb,
link_type -> GenericLinkType,
url -> Text,
return_url -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
hyperswitch_ai_interaction_default (id, created_at) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
session_id -> Nullable<Varchar>,
#[max_length = 64]
user_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Nullable<Varchar>,
user_query -> Nullable<Bytea>,
response -> Nullable<Bytea>,
database_query -> Nullable<Text>,
#[max_length = 64]
interaction_status -> Nullable<Varchar>,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
incremental_authorization (authorization_id, merchant_id) {
#[max_length = 64]
authorization_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
amount -> Int8,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
status -> Varchar,
#[max_length = 255]
error_code -> Nullable<Varchar>,
error_message -> Nullable<Text>,
#[max_length = 64]
connector_authorization_id -> Nullable<Varchar>,
previously_authorized_amount -> Int8,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
invoice (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 128]
subscription_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 128]
merchant_connector_id -> Varchar,
#[max_length = 64]
payment_intent_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
#[max_length = 64]
customer_id -> Varchar,
amount -> Int8,
#[max_length = 3]
currency -> Varchar,
#[max_length = 64]
status -> Varchar,
#[max_length = 128]
provider_name -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
connector_invoice_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
locker_mock_up (card_id) {
#[max_length = 255]
card_id -> Varchar,
#[max_length = 255]
external_id -> Varchar,
#[max_length = 255]
card_fingerprint -> Varchar,
#[max_length = 255]
card_global_fingerprint -> Varchar,
#[max_length = 255]
merchant_id -> Varchar,
#[max_length = 255]
card_number -> Varchar,
#[max_length = 255]
card_exp_year -> Varchar,
#[max_length = 255]
card_exp_month -> Varchar,
#[max_length = 255]
name_on_card -> Nullable<Varchar>,
#[max_length = 255]
nickname -> Nullable<Varchar>,
#[max_length = 255]
customer_id -> Nullable<Varchar>,
duplicate -> Nullable<Bool>,
#[max_length = 8]
card_cvc -> Nullable<Varchar>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
enc_card_data -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
mandate (mandate_id) {
#[max_length = 64]
mandate_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_method_id -> Varchar,
mandate_status -> MandateStatus,
mandate_type -> MandateType,
customer_accepted_at -> Nullable<Timestamp>,
#[max_length = 64]
customer_ip_address -> Nullable<Varchar>,
#[max_length = 255]
customer_user_agent -> Nullable<Varchar>,
#[max_length = 128]
network_transaction_id -> Nullable<Varchar>,
#[max_length = 64]
previous_attempt_id -> Nullable<Varchar>,
created_at -> Timestamp,
mandate_amount -> Nullable<Int8>,
mandate_currency -> Nullable<Currency>,
amount_captured -> Nullable<Int8>,
#[max_length = 64]
connector -> Varchar,
#[max_length = 128]
connector_mandate_id -> Nullable<Varchar>,
start_date -> Nullable<Timestamp>,
end_date -> Nullable<Timestamp>,
metadata -> Nullable<Jsonb>,
connector_mandate_ids -> Nullable<Jsonb>,
#[max_length = 64]
original_payment_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
#[max_length = 2048]
customer_user_agent_extended -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_account (merchant_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 255]
return_url -> Nullable<Varchar>,
enable_payment_response_hash -> Bool,
#[max_length = 255]
payment_response_hash_key -> Nullable<Varchar>,
redirect_to_merchant_with_http_post -> Bool,
merchant_name -> Nullable<Bytea>,
merchant_details -> Nullable<Bytea>,
webhook_details -> Nullable<Json>,
sub_merchants_enabled -> Nullable<Bool>,
#[max_length = 64]
parent_merchant_id -> Nullable<Varchar>,
#[max_length = 128]
publishable_key -> Nullable<Varchar>,
storage_scheme -> MerchantStorageScheme,
#[max_length = 64]
locker_id -> Nullable<Varchar>,
metadata -> Nullable<Jsonb>,
routing_algorithm -> Nullable<Json>,
primary_business_details -> Json,
intent_fulfillment_time -> Nullable<Int8>,
created_at -> Timestamp,
modified_at -> Timestamp,
frm_routing_algorithm -> Nullable<Jsonb>,
payout_routing_algorithm -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
is_recon_enabled -> Bool,
#[max_length = 64]
default_profile -> Nullable<Varchar>,
recon_status -> ReconStatus,
payment_link_config -> Nullable<Jsonb>,
pm_collect_link_config -> Nullable<Jsonb>,
version -> ApiVersion,
is_platform_account -> Bool,
#[max_length = 64]
id -> Nullable<Varchar>,
#[max_length = 64]
product_type -> Nullable<Varchar>,
#[max_length = 64]
merchant_account_type -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_connector_account (merchant_connector_id) {
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
connector_name -> Varchar,
connector_account_details -> Bytea,
test_mode -> Nullable<Bool>,
disabled -> Nullable<Bool>,
#[max_length = 128]
merchant_connector_id -> Varchar,
payment_methods_enabled -> Nullable<Array<Nullable<Json>>>,
connector_type -> ConnectorType,
metadata -> Nullable<Jsonb>,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
business_country -> Nullable<CountryAlpha2>,
#[max_length = 255]
business_label -> Nullable<Varchar>,
#[max_length = 64]
business_sub_label -> Nullable<Varchar>,
frm_configs -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
connector_webhook_details -> Nullable<Jsonb>,
frm_config -> Nullable<Array<Nullable<Jsonb>>>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
pm_auth_config -> Nullable<Jsonb>,
status -> ConnectorStatus,
additional_merchant_data -> Nullable<Bytea>,
connector_wallets_details -> Nullable<Bytea>,
version -> ApiVersion,
#[max_length = 64]
id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
merchant_key_store (merchant_id) {
#[max_length = 64]
merchant_id -> Varchar,
key -> Bytea,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
organization (org_id) {
#[max_length = 32]
org_id -> Varchar,
org_name -> Nullable<Text>,
organization_details -> Nullable<Jsonb>,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 32]
id -> Nullable<Varchar>,
organization_name -> Nullable<Text>,
version -> ApiVersion,
#[max_length = 64]
organization_type -> Nullable<Varchar>,
#[max_length = 64]
platform_merchant_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_attempt (attempt_id, merchant_id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
attempt_id -> Varchar,
status -> AttemptStatus,
amount -> Int8,
currency -> Nullable<Currency>,
save_to_locker -> Nullable<Bool>,
#[max_length = 64]
connector -> Nullable<Varchar>,
error_message -> Nullable<Text>,
offer_amount -> Nullable<Int8>,
surcharge_amount -> Nullable<Int8>,
tax_amount -> Nullable<Int8>,
#[max_length = 64]
payment_method_id -> Nullable<Varchar>,
payment_method -> Nullable<Varchar>,
#[max_length = 128]
connector_transaction_id -> Nullable<Varchar>,
capture_method -> Nullable<CaptureMethod>,
capture_on -> Nullable<Timestamp>,
confirm -> Bool,
authentication_type -> Nullable<AuthenticationType>,
created_at -> Timestamp,
modified_at -> Timestamp,
last_synced -> Nullable<Timestamp>,
#[max_length = 255]
cancellation_reason -> Nullable<Varchar>,
amount_to_capture -> Nullable<Int8>,
#[max_length = 64]
mandate_id -> Nullable<Varchar>,
browser_info -> Nullable<Jsonb>,
#[max_length = 255]
error_code -> Nullable<Varchar>,
#[max_length = 128]
payment_token -> Nullable<Varchar>,
connector_metadata -> Nullable<Jsonb>,
#[max_length = 50]
payment_experience -> Nullable<Varchar>,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
payment_method_data -> Nullable<Jsonb>,
#[max_length = 64]
business_sub_label -> Nullable<Varchar>,
straight_through_algorithm -> Nullable<Jsonb>,
preprocessing_step_id -> Nullable<Varchar>,
mandate_details -> Nullable<Jsonb>,
error_reason -> Nullable<Text>,
multiple_capture_count -> Nullable<Int2>,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
amount_capturable -> Int8,
#[max_length = 32]
updated_by -> Varchar,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
authentication_data -> Nullable<Json>,
encoded_data -> Nullable<Text>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
net_amount -> Nullable<Int8>,
external_three_ds_authentication_attempted -> Nullable<Bool>,
#[max_length = 64]
authentication_connector -> Nullable<Varchar>,
#[max_length = 64]
authentication_id -> Nullable<Varchar>,
mandate_data -> Nullable<Jsonb>,
#[max_length = 64]
fingerprint_id -> Nullable<Varchar>,
#[max_length = 64]
payment_method_billing_address_id -> Nullable<Varchar>,
#[max_length = 64]
charge_id -> Nullable<Varchar>,
#[max_length = 64]
client_source -> Nullable<Varchar>,
#[max_length = 64]
client_version -> Nullable<Varchar>,
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 32]
card_network -> Nullable<Varchar>,
shipping_cost -> Nullable<Int8>,
order_tax_amount -> Nullable<Int8>,
#[max_length = 512]
connector_transaction_data -> Nullable<Varchar>,
connector_mandate_detail -> Nullable<Jsonb>,
request_extended_authorization -> Nullable<Bool>,
extended_authorization_applied -> Nullable<Bool>,
capture_before -> Nullable<Timestamp>,
processor_transaction_data -> Nullable<Text>,
card_discovery -> Nullable<CardDiscovery>,
charges -> Nullable<Jsonb>,
#[max_length = 64]
issuer_error_code -> Nullable<Varchar>,
issuer_error_message -> Nullable<Text>,
#[max_length = 64]
processor_merchant_id -> Nullable<Varchar>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
setup_future_usage_applied -> Nullable<FutureUsage>,
routing_approach -> Nullable<RoutingApproach>,
#[max_length = 255]
connector_request_reference_id -> Nullable<Varchar>,
#[max_length = 255]
network_transaction_id -> Nullable<Varchar>,
is_overcapture_enabled -> Nullable<Bool>,
network_details -> Nullable<Jsonb>,
is_stored_credential -> Nullable<Bool>,
authorized_amount -> Nullable<Int8>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_intent (payment_id, merchant_id) {
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
status -> IntentStatus,
amount -> Int8,
currency -> Nullable<Currency>,
amount_captured -> Nullable<Int8>,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 255]
return_url -> Nullable<Varchar>,
metadata -> Nullable<Jsonb>,
#[max_length = 64]
connector_id -> Nullable<Varchar>,
#[max_length = 64]
shipping_address_id -> Nullable<Varchar>,
#[max_length = 64]
billing_address_id -> Nullable<Varchar>,
#[max_length = 255]
statement_descriptor_name -> Nullable<Varchar>,
#[max_length = 255]
statement_descriptor_suffix -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
last_synced -> Nullable<Timestamp>,
setup_future_usage -> Nullable<FutureUsage>,
off_session -> Nullable<Bool>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
#[max_length = 64]
active_attempt_id -> Varchar,
business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
business_label -> Nullable<Varchar>,
order_details -> Nullable<Array<Nullable<Jsonb>>>,
allowed_payment_method_types -> Nullable<Json>,
connector_metadata -> Nullable<Json>,
feature_metadata -> Nullable<Json>,
attempt_count -> Int2,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_decision -> Nullable<Varchar>,
#[max_length = 255]
payment_link_id -> Nullable<Varchar>,
payment_confirm_source -> Nullable<PaymentSource>,
#[max_length = 32]
updated_by -> Varchar,
surcharge_applicable -> Nullable<Bool>,
request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>,
incremental_authorization_allowed -> Nullable<Bool>,
authorization_count -> Nullable<Int4>,
session_expiry -> Nullable<Timestamp>,
#[max_length = 64]
fingerprint_id -> Nullable<Varchar>,
request_external_three_ds_authentication -> Nullable<Bool>,
charges -> Nullable<Jsonb>,
frm_metadata -> Nullable<Jsonb>,
customer_details -> Nullable<Bytea>,
billing_details -> Nullable<Bytea>,
#[max_length = 255]
merchant_order_reference_id -> Nullable<Varchar>,
shipping_details -> Nullable<Bytea>,
is_payment_processor_token_flow -> Nullable<Bool>,
shipping_cost -> Nullable<Int8>,
#[max_length = 32]
organization_id -> Varchar,
tax_details -> Nullable<Jsonb>,
skip_external_tax_calculation -> Nullable<Bool>,
request_extended_authorization -> Nullable<Bool>,
psd2_sca_exemption_type -> Nullable<ScaExemptionType>,
split_payments -> Nullable<Jsonb>,
#[max_length = 64]
platform_merchant_id -> Nullable<Varchar>,
force_3ds_challenge -> Nullable<Bool>,
force_3ds_challenge_trigger -> Nullable<Bool>,
#[max_length = 64]
processor_merchant_id -> Nullable<Varchar>,
#[max_length = 255]
created_by -> Nullable<Varchar>,
is_iframe_redirection_enabled -> Nullable<Bool>,
#[max_length = 2048]
extended_return_url -> Nullable<Varchar>,
is_payment_id_from_merchant -> Nullable<Bool>,
#[max_length = 64]
payment_channel -> Nullable<Varchar>,
tax_status -> Nullable<Varchar>,
discount_amount -> Nullable<Int8>,
shipping_amount_tax -> Nullable<Int8>,
duty_amount -> Nullable<Int8>,
order_date -> Nullable<Timestamp>,
enable_partial_authorization -> Nullable<Bool>,
enable_overcapture -> Nullable<Bool>,
#[max_length = 64]
mit_category -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_link (payment_link_id) {
#[max_length = 255]
payment_link_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 255]
link_to_pay -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
amount -> Int8,
currency -> Nullable<Currency>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
fulfilment_time -> Nullable<Timestamp>,
#[max_length = 64]
custom_merchant_name -> Nullable<Varchar>,
payment_link_config -> Nullable<Jsonb>,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 255]
secure_link -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payment_methods (payment_method_id) {
#[max_length = 64]
customer_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
payment_method_id -> Varchar,
accepted_currency -> Nullable<Array<Nullable<Currency>>>,
#[max_length = 32]
scheme -> Nullable<Varchar>,
#[max_length = 128]
token -> Nullable<Varchar>,
#[max_length = 255]
cardholder_name -> Nullable<Varchar>,
#[max_length = 64]
issuer_name -> Nullable<Varchar>,
#[max_length = 64]
issuer_country -> Nullable<Varchar>,
payer_country -> Nullable<Array<Nullable<Text>>>,
is_stored -> Nullable<Bool>,
#[max_length = 32]
swift_code -> Nullable<Varchar>,
#[max_length = 128]
direct_debit_token -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified -> Timestamp,
payment_method -> Nullable<Varchar>,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
#[max_length = 128]
payment_method_issuer -> Nullable<Varchar>,
payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>,
metadata -> Nullable<Json>,
payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
locker_id -> Nullable<Varchar>,
last_used_at -> Timestamp,
connector_mandate_details -> Nullable<Jsonb>,
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
status -> Varchar,
#[max_length = 255]
network_transaction_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
payment_method_billing_address -> Nullable<Bytea>,
#[max_length = 64]
updated_by -> Nullable<Varchar>,
version -> ApiVersion,
#[max_length = 128]
network_token_requestor_reference_id -> Nullable<Varchar>,
#[max_length = 64]
network_token_locker_id -> Nullable<Varchar>,
network_token_payment_method_data -> Nullable<Bytea>,
#[max_length = 64]
external_vault_source -> Nullable<Varchar>,
#[max_length = 64]
vault_type -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payout_attempt (merchant_id, payout_attempt_id) {
#[max_length = 64]
payout_attempt_id -> Varchar,
#[max_length = 64]
payout_id -> Varchar,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
address_id -> Nullable<Varchar>,
#[max_length = 64]
connector -> Nullable<Varchar>,
#[max_length = 128]
connector_payout_id -> Nullable<Varchar>,
#[max_length = 64]
payout_token -> Nullable<Varchar>,
status -> PayoutStatus,
is_eligible -> Nullable<Bool>,
error_message -> Nullable<Text>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
business_label -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
routing_info -> Nullable<Jsonb>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
additional_payout_method_data -> Nullable<Jsonb>,
#[max_length = 255]
merchant_order_reference_id -> Nullable<Varchar>,
payout_connector_metadata -> Nullable<Jsonb>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
payouts (merchant_id, payout_id) {
#[max_length = 64]
payout_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
customer_id -> Nullable<Varchar>,
#[max_length = 64]
address_id -> Nullable<Varchar>,
payout_type -> Nullable<PayoutType>,
#[max_length = 64]
payout_method_id -> Nullable<Varchar>,
amount -> Int8,
destination_currency -> Currency,
source_currency -> Currency,
#[max_length = 255]
description -> Nullable<Varchar>,
recurring -> Bool,
auto_fulfill -> Bool,
#[max_length = 255]
return_url -> Nullable<Varchar>,
#[max_length = 64]
entity_type -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
attempt_count -> Int2,
#[max_length = 64]
profile_id -> Varchar,
status -> PayoutStatus,
confirm -> Nullable<Bool>,
#[max_length = 255]
payout_link_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
#[max_length = 32]
priority -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
process_tracker (id) {
#[max_length = 127]
id -> Varchar,
#[max_length = 64]
name -> Nullable<Varchar>,
tag -> Array<Nullable<Text>>,
#[max_length = 64]
runner -> Nullable<Varchar>,
retry_count -> Int4,
schedule_time -> Nullable<Timestamp>,
#[max_length = 255]
rule -> Varchar,
tracking_data -> Json,
#[max_length = 255]
business_status -> Varchar,
status -> ProcessTrackerStatus,
event -> Array<Nullable<Text>>,
created_at -> Timestamp,
updated_at -> Timestamp,
version -> ApiVersion,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
refund (merchant_id, refund_id) {
#[max_length = 64]
internal_reference_id -> Varchar,
#[max_length = 64]
refund_id -> Varchar,
#[max_length = 64]
payment_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 128]
connector_transaction_id -> Varchar,
#[max_length = 64]
connector -> Varchar,
#[max_length = 128]
connector_refund_id -> Nullable<Varchar>,
#[max_length = 64]
external_reference_id -> Nullable<Varchar>,
refund_type -> RefundType,
total_amount -> Int8,
currency -> Currency,
refund_amount -> Int8,
refund_status -> RefundStatus,
sent_to_gateway -> Bool,
refund_error_message -> Nullable<Text>,
metadata -> Nullable<Json>,
#[max_length = 128]
refund_arn -> Nullable<Varchar>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 255]
description -> Nullable<Varchar>,
#[max_length = 64]
attempt_id -> Varchar,
#[max_length = 255]
refund_reason -> Nullable<Varchar>,
refund_error_code -> Nullable<Text>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 32]
updated_by -> Varchar,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
charges -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
#[max_length = 512]
connector_refund_data -> Nullable<Varchar>,
#[max_length = 512]
connector_transaction_data -> Nullable<Varchar>,
split_refunds -> Nullable<Jsonb>,
#[max_length = 255]
unified_code -> Nullable<Varchar>,
#[max_length = 1024]
unified_message -> Nullable<Varchar>,
processor_refund_data -> Nullable<Text>,
processor_transaction_data -> Nullable<Text>,
#[max_length = 64]
issuer_error_code -> Nullable<Varchar>,
issuer_error_message -> Nullable<Text>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
relay (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 128]
connector_resource_id -> Varchar,
#[max_length = 64]
connector_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
relay_type -> RelayType,
request_data -> Nullable<Jsonb>,
status -> RelayStatus,
#[max_length = 128]
connector_reference_id -> Nullable<Varchar>,
#[max_length = 64]
error_code -> Nullable<Varchar>,
error_message -> Nullable<Text>,
created_at -> Timestamp,
modified_at -> Timestamp,
response_data -> Nullable<Jsonb>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
reverse_lookup (lookup_id) {
#[max_length = 128]
lookup_id -> Varchar,
#[max_length = 128]
sk_id -> Varchar,
#[max_length = 128]
pk_id -> Varchar,
#[max_length = 128]
source -> Varchar,
#[max_length = 32]
updated_by -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
roles (role_id) {
#[max_length = 64]
role_name -> Varchar,
#[max_length = 64]
role_id -> Varchar,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
org_id -> Varchar,
groups -> Array<Nullable<Text>>,
scope -> RoleScope,
created_at -> Timestamp,
#[max_length = 64]
created_by -> Varchar,
last_modified_at -> Timestamp,
#[max_length = 64]
last_modified_by -> Varchar,
#[max_length = 64]
entity_type -> Varchar,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
tenant_id -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
routing_algorithm (algorithm_id) {
#[max_length = 64]
algorithm_id -> Varchar,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
name -> Varchar,
#[max_length = 256]
description -> Nullable<Varchar>,
kind -> RoutingAlgorithmKind,
algorithm_data -> Jsonb,
created_at -> Timestamp,
modified_at -> Timestamp,
algorithm_for -> TransactionType,
#[max_length = 64]
decision_engine_routing_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
subscription (id) {
#[max_length = 128]
id -> Varchar,
#[max_length = 128]
status -> Varchar,
#[max_length = 128]
billing_processor -> Nullable<Varchar>,
#[max_length = 128]
payment_method_id -> Nullable<Varchar>,
#[max_length = 128]
merchant_connector_id -> Nullable<Varchar>,
#[max_length = 128]
client_secret -> Nullable<Varchar>,
#[max_length = 128]
connector_subscription_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Varchar,
#[max_length = 64]
customer_id -> Varchar,
metadata -> Nullable<Jsonb>,
created_at -> Timestamp,
modified_at -> Timestamp,
#[max_length = 64]
profile_id -> Varchar,
#[max_length = 128]
merchant_reference_id -> Nullable<Varchar>,
#[max_length = 128]
plan_id -> Nullable<Varchar>,
#[max_length = 128]
item_price_id -> Nullable<Varchar>,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
themes (theme_id) {
#[max_length = 64]
theme_id -> Varchar,
#[max_length = 64]
tenant_id -> Varchar,
#[max_length = 64]
org_id -> Nullable<Varchar>,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
entity_type -> Varchar,
#[max_length = 64]
theme_name -> Varchar,
#[max_length = 64]
email_primary_color -> Varchar,
#[max_length = 64]
email_foreground_color -> Varchar,
#[max_length = 64]
email_background_color -> Varchar,
#[max_length = 64]
email_entity_name -> Varchar,
email_entity_logo_url -> Text,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
unified_translations (unified_code, unified_message, locale) {
#[max_length = 255]
unified_code -> Varchar,
#[max_length = 1024]
unified_message -> Varchar,
#[max_length = 255]
locale -> Varchar,
#[max_length = 1024]
translation -> Varchar,
created_at -> Timestamp,
last_modified_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_authentication_methods (id) {
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
auth_id -> Varchar,
#[max_length = 64]
owner_id -> Varchar,
#[max_length = 64]
owner_type -> Varchar,
#[max_length = 64]
auth_type -> Varchar,
private_config -> Nullable<Bytea>,
public_config -> Nullable<Jsonb>,
allow_signup -> Bool,
created_at -> Timestamp,
last_modified_at -> Timestamp,
#[max_length = 64]
email_domain -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_key_store (user_id) {
#[max_length = 64]
user_id -> Varchar,
key -> Bytea,
created_at -> Timestamp,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
user_roles (id) {
id -> Int4,
#[max_length = 64]
user_id -> Varchar,
#[max_length = 64]
merchant_id -> Nullable<Varchar>,
#[max_length = 64]
role_id -> Varchar,
#[max_length = 64]
org_id -> Nullable<Varchar>,
status -> UserStatus,
#[max_length = 64]
created_by -> Varchar,
#[max_length = 64]
last_modified_by -> Varchar,
created_at -> Timestamp,
last_modified -> Timestamp,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
#[max_length = 64]
entity_id -> Nullable<Varchar>,
#[max_length = 64]
entity_type -> Nullable<Varchar>,
version -> UserRoleVersion,
#[max_length = 64]
tenant_id -> Varchar,
}
}
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
users (user_id) {
#[max_length = 64]
user_id -> Varchar,
#[max_length = 255]
email -> Varchar,
#[max_length = 255]
name -> Varchar,
#[max_length = 255]
password -> Nullable<Varchar>,
is_verified -> Bool,
created_at -> Timestamp,
last_modified_at -> Timestamp,
totp_status -> TotpStatus,
totp_secret -> Nullable<Bytea>,
totp_recovery_codes -> Nullable<Array<Nullable<Text>>>,
last_password_modified_at -> Nullable<Timestamp>,
lineage_context -> Nullable<Jsonb>,
}
}
diesel::allow_tables_to_appear_in_same_query!(
address,
api_keys,
authentication,
blocklist,
blocklist_fingerprint,
blocklist_lookup,
business_profile,
callback_mapper,
captures,
cards_info,
configs,
customers,
dashboard_metadata,
dispute,
dynamic_routing_stats,
events,
file_metadata,
fraud_check,
gateway_status_map,
generic_link,
hyperswitch_ai_interaction,
hyperswitch_ai_interaction_default,
incremental_authorization,
invoice,
locker_mock_up,
mandate,
merchant_account,
merchant_connector_account,
merchant_key_store,
organization,
payment_attempt,
payment_intent,
payment_link,
payment_methods,
payout_attempt,
payouts,
process_tracker,
refund,
relay,
reverse_lookup,
roles,
routing_algorithm,
subscription,
themes,
unified_translations,
user_authentication_methods,
user_key_store,
user_roles,
users,
);
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/schema.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 14001
}
|
large_file_2804560311117922128
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/customers.rs
</path>
<file>
use common_enums::ApiVersion;
use common_utils::{encryption::Encryption, pii, types::Description};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
#[cfg(feature = "v1")]
use crate::schema::customers;
#[cfg(feature = "v2")]
use crate::{
diesel_impl::RequiredFromNullableWithDefault, enums::DeleteStatus, schema_v2::customers,
};
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, Insertable,
)]
#[diesel(table_name = customers)]
pub struct CustomerNew {
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub description: Option<Description>,
pub phone_country_code: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<pii::SecretSerdeValue>,
pub created_at: PrimitiveDateTime,
pub modified_at: PrimitiveDateTime,
pub address_id: Option<String>,
pub updated_by: Option<String>,
pub version: ApiVersion,
pub tax_registration_id: Option<Encryption>,
}
#[cfg(feature = "v1")]
impl CustomerNew {
pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) {
self.updated_by = Some(storage_scheme.to_string());
}
}
#[cfg(feature = "v1")]
impl From<CustomerNew> for Customer {
fn from(customer_new: CustomerNew) -> Self {
Self {
customer_id: customer_new.customer_id,
merchant_id: customer_new.merchant_id,
name: customer_new.name,
email: customer_new.email,
phone: customer_new.phone,
phone_country_code: customer_new.phone_country_code,
description: customer_new.description,
created_at: customer_new.created_at,
metadata: customer_new.metadata,
connector_customer: customer_new.connector_customer,
modified_at: customer_new.modified_at,
address_id: customer_new.address_id,
default_payment_method_id: None,
updated_by: customer_new.updated_by,
version: customer_new.version,
tax_registration_id: customer_new.tax_registration_id,
}
}
}
#[cfg(feature = "v2")]
#[derive(
Clone, Debug, Insertable, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize,
)]
#[diesel(table_name = customers, primary_key(id))]
pub struct CustomerNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
pub modified_at: PrimitiveDateTime,
pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>,
pub updated_by: Option<String>,
pub version: ApiVersion,
pub tax_registration_id: Option<Encryption>,
pub merchant_reference_id: Option<common_utils::id_type::CustomerId>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub status: DeleteStatus,
pub id: common_utils::id_type::GlobalCustomerId,
}
#[cfg(feature = "v2")]
impl CustomerNew {
pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) {
self.updated_by = Some(storage_scheme.to_string());
}
}
#[cfg(feature = "v2")]
impl From<CustomerNew> for Customer {
fn from(customer_new: CustomerNew) -> Self {
Self {
merchant_id: customer_new.merchant_id,
name: customer_new.name,
email: customer_new.email,
phone: customer_new.phone,
phone_country_code: customer_new.phone_country_code,
description: customer_new.description,
created_at: customer_new.created_at,
metadata: customer_new.metadata,
connector_customer: customer_new.connector_customer,
modified_at: customer_new.modified_at,
default_payment_method_id: None,
updated_by: customer_new.updated_by,
tax_registration_id: customer_new.tax_registration_id,
merchant_reference_id: customer_new.merchant_reference_id,
default_billing_address: customer_new.default_billing_address,
default_shipping_address: customer_new.default_shipping_address,
id: customer_new.id,
version: customer_new.version,
status: customer_new.status,
}
}
}
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, Identifiable, Queryable, Selectable, serde::Deserialize, serde::Serialize,
)]
#[diesel(table_name = customers, primary_key(customer_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct Customer {
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<pii::SecretSerdeValue>,
pub modified_at: PrimitiveDateTime,
pub address_id: Option<String>,
pub default_payment_method_id: Option<String>,
pub updated_by: Option<String>,
pub version: ApiVersion,
pub tax_registration_id: Option<Encryption>,
}
#[cfg(feature = "v2")]
#[derive(
Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize,
)]
#[diesel(table_name = customers, primary_key(id))]
pub struct Customer {
pub merchant_id: common_utils::id_type::MerchantId,
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
pub modified_at: PrimitiveDateTime,
pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>,
pub updated_by: Option<String>,
pub version: ApiVersion,
pub tax_registration_id: Option<Encryption>,
pub merchant_reference_id: Option<common_utils::id_type::CustomerId>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
#[diesel(deserialize_as = RequiredFromNullableWithDefault<DeleteStatus>)]
pub status: DeleteStatus,
pub id: common_utils::id_type::GlobalCustomerId,
}
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize,
)]
#[diesel(table_name = customers)]
pub struct CustomerUpdateInternal {
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub description: Option<Description>,
pub phone_country_code: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: PrimitiveDateTime,
pub connector_customer: Option<pii::SecretSerdeValue>,
pub address_id: Option<String>,
pub default_payment_method_id: Option<Option<String>>,
pub updated_by: Option<String>,
pub tax_registration_id: Option<Encryption>,
}
#[cfg(feature = "v1")]
impl CustomerUpdateInternal {
pub fn apply_changeset(self, source: Customer) -> Customer {
let Self {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
address_id,
default_payment_method_id,
tax_registration_id,
..
} = self;
Customer {
name: name.map_or(source.name, Some),
email: email.map_or(source.email, Some),
phone: phone.map_or(source.phone, Some),
description: description.map_or(source.description, Some),
phone_country_code: phone_country_code.map_or(source.phone_country_code, Some),
metadata: metadata.map_or(source.metadata, Some),
modified_at: common_utils::date_time::now(),
connector_customer: connector_customer.map_or(source.connector_customer, Some),
address_id: address_id.map_or(source.address_id, Some),
default_payment_method_id: default_payment_method_id
.flatten()
.map_or(source.default_payment_method_id, Some),
tax_registration_id: tax_registration_id.map_or(source.tax_registration_id, Some),
..source
}
}
}
#[cfg(feature = "v2")]
#[derive(
Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize,
)]
#[diesel(table_name = customers)]
pub struct CustomerUpdateInternal {
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
pub description: Option<Description>,
pub phone_country_code: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: PrimitiveDateTime,
pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
pub default_payment_method_id: Option<Option<common_utils::id_type::GlobalPaymentMethodId>>,
pub updated_by: Option<String>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub status: Option<DeleteStatus>,
pub tax_registration_id: Option<Encryption>,
}
#[cfg(feature = "v2")]
impl CustomerUpdateInternal {
pub fn apply_changeset(self, source: Customer) -> Customer {
let Self {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
default_payment_method_id,
default_billing_address,
default_shipping_address,
status,
tax_registration_id,
..
} = self;
Customer {
name: name.map_or(source.name, Some),
email: email.map_or(source.email, Some),
phone: phone.map_or(source.phone, Some),
description: description.map_or(source.description, Some),
phone_country_code: phone_country_code.map_or(source.phone_country_code, Some),
metadata: metadata.map_or(source.metadata, Some),
modified_at: common_utils::date_time::now(),
connector_customer: connector_customer.map_or(source.connector_customer, Some),
default_payment_method_id: default_payment_method_id
.flatten()
.map_or(source.default_payment_method_id, Some),
default_billing_address: default_billing_address
.map_or(source.default_billing_address, Some),
default_shipping_address: default_shipping_address
.map_or(source.default_shipping_address, Some),
status: status.unwrap_or(source.status),
tax_registration_id: tax_registration_id.map_or(source.tax_registration_id, Some),
..source
}
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/customers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2402
}
|
large_file_-3117988538510863184
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/payout_attempt.rs
</path>
<file>
use common_utils::{
payout_method_utils, pii,
types::{UnifiedCode, UnifiedMessage},
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{self, Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::payout_attempt};
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = payout_attempt, primary_key(payout_attempt_id), check_for_backend(diesel::pg::Pg))]
pub struct PayoutAttempt {
pub payout_attempt_id: String,
pub payout_id: common_utils::id_type::PayoutId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub merchant_id: common_utils::id_type::MerchantId,
pub address_id: Option<String>,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
pub payout_token: Option<String>,
pub status: storage_enums::PayoutStatus,
pub is_eligible: Option<bool>,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub routing_info: Option<serde_json::Value>,
pub unified_code: Option<UnifiedCode>,
pub unified_message: Option<UnifiedMessage>,
pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
pub merchant_order_reference_id: Option<String>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
serde::Serialize,
serde::Deserialize,
router_derive::DebugAsDisplay,
router_derive::Setter,
)]
#[diesel(table_name = payout_attempt)]
pub struct PayoutAttemptNew {
pub payout_attempt_id: String,
pub payout_id: common_utils::id_type::PayoutId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub merchant_id: common_utils::id_type::MerchantId,
pub address_id: Option<String>,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
pub payout_token: Option<String>,
pub status: storage_enums::PayoutStatus,
pub is_eligible: Option<bool>,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub routing_info: Option<serde_json::Value>,
pub unified_code: Option<UnifiedCode>,
pub unified_message: Option<UnifiedMessage>,
pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
pub merchant_order_reference_id: Option<String>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PayoutAttemptUpdate {
StatusUpdate {
connector_payout_id: Option<String>,
status: storage_enums::PayoutStatus,
error_message: Option<String>,
error_code: Option<String>,
is_eligible: Option<bool>,
unified_code: Option<UnifiedCode>,
unified_message: Option<UnifiedMessage>,
payout_connector_metadata: Option<pii::SecretSerdeValue>,
},
PayoutTokenUpdate {
payout_token: String,
},
BusinessUpdate {
business_country: Option<storage_enums::CountryAlpha2>,
business_label: Option<String>,
address_id: Option<String>,
customer_id: Option<common_utils::id_type::CustomerId>,
},
UpdateRouting {
connector: String,
routing_info: Option<serde_json::Value>,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
},
AdditionalPayoutMethodDataUpdate {
additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
},
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = payout_attempt)]
pub struct PayoutAttemptUpdateInternal {
pub payout_token: Option<String>,
pub connector_payout_id: Option<String>,
pub status: Option<storage_enums::PayoutStatus>,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub is_eligible: Option<bool>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub connector: Option<String>,
pub routing_info: Option<serde_json::Value>,
pub last_modified_at: PrimitiveDateTime,
pub address_id: Option<String>,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub unified_code: Option<UnifiedCode>,
pub unified_message: Option<UnifiedMessage>,
pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
pub merchant_order_reference_id: Option<String>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
impl Default for PayoutAttemptUpdateInternal {
fn default() -> Self {
Self {
payout_token: None,
connector_payout_id: None,
status: None,
error_message: None,
error_code: None,
is_eligible: None,
business_country: None,
business_label: None,
connector: None,
routing_info: None,
merchant_connector_id: None,
last_modified_at: common_utils::date_time::now(),
address_id: None,
customer_id: None,
unified_code: None,
unified_message: None,
additional_payout_method_data: None,
merchant_order_reference_id: None,
payout_connector_metadata: None,
}
}
}
impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
fn from(payout_update: PayoutAttemptUpdate) -> Self {
match payout_update {
PayoutAttemptUpdate::PayoutTokenUpdate { payout_token } => Self {
payout_token: Some(payout_token),
..Default::default()
},
PayoutAttemptUpdate::StatusUpdate {
connector_payout_id,
status,
error_message,
error_code,
is_eligible,
unified_code,
unified_message,
payout_connector_metadata,
} => Self {
connector_payout_id,
status: Some(status),
error_message,
error_code,
is_eligible,
unified_code,
unified_message,
payout_connector_metadata,
..Default::default()
},
PayoutAttemptUpdate::BusinessUpdate {
business_country,
business_label,
address_id,
customer_id,
} => Self {
business_country,
business_label,
address_id,
customer_id,
..Default::default()
},
PayoutAttemptUpdate::UpdateRouting {
connector,
routing_info,
merchant_connector_id,
} => Self {
connector: Some(connector),
routing_info,
merchant_connector_id,
..Default::default()
},
PayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate {
additional_payout_method_data,
} => Self {
additional_payout_method_data,
..Default::default()
},
}
}
}
impl PayoutAttemptUpdate {
pub fn apply_changeset(self, source: PayoutAttempt) -> PayoutAttempt {
let PayoutAttemptUpdateInternal {
payout_token,
connector_payout_id,
status,
error_message,
error_code,
is_eligible,
business_country,
business_label,
connector,
routing_info,
last_modified_at,
address_id,
customer_id,
merchant_connector_id,
unified_code,
unified_message,
additional_payout_method_data,
merchant_order_reference_id,
payout_connector_metadata,
} = self.into();
PayoutAttempt {
payout_token: payout_token.or(source.payout_token),
connector_payout_id: connector_payout_id.or(source.connector_payout_id),
status: status.unwrap_or(source.status),
error_message: error_message.or(source.error_message),
error_code: error_code.or(source.error_code),
is_eligible: is_eligible.or(source.is_eligible),
business_country: business_country.or(source.business_country),
business_label: business_label.or(source.business_label),
connector: connector.or(source.connector),
routing_info: routing_info.or(source.routing_info),
last_modified_at,
address_id: address_id.or(source.address_id),
customer_id: customer_id.or(source.customer_id),
merchant_connector_id: merchant_connector_id.or(source.merchant_connector_id),
unified_code: unified_code.or(source.unified_code),
unified_message: unified_message.or(source.unified_message),
additional_payout_method_data: additional_payout_method_data
.or(source.additional_payout_method_data),
merchant_order_reference_id: merchant_order_reference_id
.or(source.merchant_order_reference_id),
payout_connector_metadata: payout_connector_metadata
.or(source.payout_connector_metadata),
..source
}
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/payout_attempt.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2145
}
|
large_file_-1060342207870300367
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/authentication.rs
</path>
<file>
use std::str::FromStr;
use common_utils::{
encryption::Encryption,
errors::{CustomResult, ValidationError},
pii,
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use error_stack::ResultExt;
use serde::{self, Deserialize, Serialize};
use serde_json;
use crate::schema::authentication;
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = authentication, primary_key(authentication_id), check_for_backend(diesel::pg::Pg))]
pub struct Authentication {
pub authentication_id: common_utils::id_type::AuthenticationId,
pub merchant_id: common_utils::id_type::MerchantId,
pub authentication_connector: Option<String>,
pub connector_authentication_id: Option<String>,
pub authentication_data: Option<serde_json::Value>,
pub payment_method_id: String,
pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
pub authentication_status: common_enums::AuthenticationStatus,
pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: time::PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: time::PrimitiveDateTime,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<String>,
pub cavv: Option<String>,
pub authentication_flow_type: Option<String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<String>,
pub trans_status: Option<common_enums::TransactionStatus>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
pub three_ds_method_data: Option<String>,
pub three_ds_method_url: Option<String>,
pub acs_url: Option<String>,
pub challenge_request: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub profile_id: common_utils::id_type::ProfileId,
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub ds_trans_id: Option<String>,
pub directory_server_id: Option<String>,
pub acquirer_country_code: Option<String>,
pub service_details: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub authentication_client_secret: Option<String>,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
pub return_url: Option<String>,
pub amount: Option<common_utils::types::MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub billing_address: Option<Encryption>,
pub shipping_address: Option<Encryption>,
pub browser_info: Option<serde_json::Value>,
pub email: Option<Encryption>,
pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,
pub challenge_code: Option<String>,
pub challenge_cancel: Option<String>,
pub challenge_code_reason: Option<String>,
pub message_extension: Option<pii::SecretSerdeValue>,
pub challenge_request_key: Option<String>,
}
impl Authentication {
pub fn is_separate_authn_required(&self) -> bool {
self.maximum_supported_version
.as_ref()
.is_some_and(|version| version.get_major() == 2)
}
// get authentication_connector from authentication record and check if it is jwt flow
pub fn is_jwt_flow(&self) -> CustomResult<bool, ValidationError> {
Ok(self
.authentication_connector
.clone()
.map(|connector| {
common_enums::AuthenticationConnectors::from_str(&connector)
.change_context(ValidationError::InvalidValue {
message: "failed to parse authentication_connector".to_string(),
})
.map(|connector_enum| connector_enum.is_jwt_flow())
})
.transpose()?
.unwrap_or(false))
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Insertable)]
#[diesel(table_name = authentication)]
pub struct AuthenticationNew {
pub authentication_id: common_utils::id_type::AuthenticationId,
pub merchant_id: common_utils::id_type::MerchantId,
pub authentication_connector: Option<String>,
pub connector_authentication_id: Option<String>,
// pub authentication_data: Option<serde_json::Value>,
pub payment_method_id: String,
pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
pub authentication_status: common_enums::AuthenticationStatus,
pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<String>,
pub cavv: Option<String>,
pub authentication_flow_type: Option<String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<String>,
pub trans_status: Option<common_enums::TransactionStatus>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
pub three_ds_method_data: Option<String>,
pub three_ds_method_url: Option<String>,
pub acs_url: Option<String>,
pub challenge_request: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub profile_id: common_utils::id_type::ProfileId,
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub ds_trans_id: Option<String>,
pub directory_server_id: Option<String>,
pub acquirer_country_code: Option<String>,
pub service_details: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub authentication_client_secret: Option<String>,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
pub return_url: Option<String>,
pub amount: Option<common_utils::types::MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub billing_address: Option<Encryption>,
pub shipping_address: Option<Encryption>,
pub browser_info: Option<serde_json::Value>,
pub email: Option<Encryption>,
pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,
pub challenge_code: Option<String>,
pub challenge_cancel: Option<String>,
pub challenge_code_reason: Option<String>,
pub message_extension: Option<pii::SecretSerdeValue>,
pub challenge_request_key: Option<String>,
}
#[derive(Debug)]
pub enum AuthenticationUpdate {
PreAuthenticationVersionCallUpdate {
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
message_version: common_utils::types::SemanticVersion,
},
PreAuthenticationThreeDsMethodCall {
threeds_server_transaction_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
acquirer_bin: Option<String>,
acquirer_merchant_id: Option<String>,
connector_metadata: Option<serde_json::Value>,
},
PreAuthenticationUpdate {
threeds_server_transaction_id: String,
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
connector_authentication_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
message_version: common_utils::types::SemanticVersion,
connector_metadata: Option<serde_json::Value>,
authentication_status: common_enums::AuthenticationStatus,
acquirer_bin: Option<String>,
acquirer_merchant_id: Option<String>,
directory_server_id: Option<String>,
acquirer_country_code: Option<String>,
billing_address: Option<Encryption>,
shipping_address: Option<Encryption>,
browser_info: Box<Option<serde_json::Value>>,
email: Option<Encryption>,
},
AuthenticationUpdate {
trans_status: common_enums::TransactionStatus,
authentication_type: common_enums::DecoupledAuthenticationType,
acs_url: Option<String>,
challenge_request: Option<String>,
acs_reference_number: Option<String>,
acs_trans_id: Option<String>,
acs_signed_content: Option<String>,
connector_metadata: Option<serde_json::Value>,
authentication_status: common_enums::AuthenticationStatus,
ds_trans_id: Option<String>,
eci: Option<String>,
challenge_code: Option<String>,
challenge_cancel: Option<String>,
challenge_code_reason: Option<String>,
message_extension: Option<pii::SecretSerdeValue>,
challenge_request_key: Option<String>,
},
PostAuthenticationUpdate {
trans_status: common_enums::TransactionStatus,
eci: Option<String>,
authentication_status: common_enums::AuthenticationStatus,
challenge_cancel: Option<String>,
challenge_code_reason: Option<String>,
},
ErrorUpdate {
error_message: Option<String>,
error_code: Option<String>,
authentication_status: common_enums::AuthenticationStatus,
connector_authentication_id: Option<String>,
},
PostAuthorizationUpdate {
authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
},
AuthenticationStatusUpdate {
trans_status: common_enums::TransactionStatus,
authentication_status: common_enums::AuthenticationStatus,
},
}
#[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Serialize, Deserialize)]
#[diesel(table_name = authentication)]
pub struct AuthenticationUpdateInternal {
pub connector_authentication_id: Option<String>,
// pub authentication_data: Option<serde_json::Value>,
pub payment_method_id: Option<String>,
pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
pub authentication_status: Option<common_enums::AuthenticationStatus>,
pub authentication_lifecycle_status: Option<common_enums::AuthenticationLifecycleStatus>,
pub modified_at: time::PrimitiveDateTime,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<String>,
pub authentication_flow_type: Option<String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<String>,
pub trans_status: Option<common_enums::TransactionStatus>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
pub three_ds_method_data: Option<String>,
pub three_ds_method_url: Option<String>,
pub acs_url: Option<String>,
pub challenge_request: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub ds_trans_id: Option<String>,
pub directory_server_id: Option<String>,
pub acquirer_country_code: Option<String>,
pub service_details: Option<serde_json::Value>,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
pub billing_address: Option<Encryption>,
pub shipping_address: Option<Encryption>,
pub browser_info: Option<serde_json::Value>,
pub email: Option<Encryption>,
pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,
pub challenge_code: Option<String>,
pub challenge_cancel: Option<String>,
pub challenge_code_reason: Option<String>,
pub message_extension: Option<pii::SecretSerdeValue>,
pub challenge_request_key: Option<String>,
}
impl Default for AuthenticationUpdateInternal {
fn default() -> Self {
Self {
connector_authentication_id: Default::default(),
payment_method_id: Default::default(),
authentication_type: Default::default(),
authentication_status: Default::default(),
authentication_lifecycle_status: Default::default(),
modified_at: common_utils::date_time::now(),
error_message: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
maximum_supported_version: Default::default(),
threeds_server_transaction_id: Default::default(),
authentication_flow_type: Default::default(),
message_version: Default::default(),
eci: Default::default(),
trans_status: Default::default(),
acquirer_bin: Default::default(),
acquirer_merchant_id: Default::default(),
three_ds_method_data: Default::default(),
three_ds_method_url: Default::default(),
acs_url: Default::default(),
challenge_request: Default::default(),
acs_reference_number: Default::default(),
acs_trans_id: Default::default(),
acs_signed_content: Default::default(),
ds_trans_id: Default::default(),
directory_server_id: Default::default(),
acquirer_country_code: Default::default(),
service_details: Default::default(),
force_3ds_challenge: Default::default(),
psd2_sca_exemption_type: Default::default(),
billing_address: Default::default(),
shipping_address: Default::default(),
browser_info: Default::default(),
email: Default::default(),
profile_acquirer_id: Default::default(),
challenge_code: Default::default(),
challenge_cancel: Default::default(),
challenge_code_reason: Default::default(),
message_extension: Default::default(),
challenge_request_key: Default::default(),
}
}
}
impl AuthenticationUpdateInternal {
pub fn apply_changeset(self, source: Authentication) -> Authentication {
let Self {
connector_authentication_id,
payment_method_id,
authentication_type,
authentication_status,
authentication_lifecycle_status,
modified_at: _,
error_code,
error_message,
connector_metadata,
maximum_supported_version,
threeds_server_transaction_id,
authentication_flow_type,
message_version,
eci,
trans_status,
acquirer_bin,
acquirer_merchant_id,
three_ds_method_data,
three_ds_method_url,
acs_url,
challenge_request,
acs_reference_number,
acs_trans_id,
acs_signed_content,
ds_trans_id,
directory_server_id,
acquirer_country_code,
service_details,
force_3ds_challenge,
psd2_sca_exemption_type,
billing_address,
shipping_address,
browser_info,
email,
profile_acquirer_id,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
challenge_request_key,
} = self;
Authentication {
connector_authentication_id: connector_authentication_id
.or(source.connector_authentication_id),
payment_method_id: payment_method_id.unwrap_or(source.payment_method_id),
authentication_type: authentication_type.or(source.authentication_type),
authentication_status: authentication_status.unwrap_or(source.authentication_status),
authentication_lifecycle_status: authentication_lifecycle_status
.unwrap_or(source.authentication_lifecycle_status),
modified_at: common_utils::date_time::now(),
error_code: error_code.or(source.error_code),
error_message: error_message.or(source.error_message),
connector_metadata: connector_metadata.or(source.connector_metadata),
maximum_supported_version: maximum_supported_version
.or(source.maximum_supported_version),
threeds_server_transaction_id: threeds_server_transaction_id
.or(source.threeds_server_transaction_id),
authentication_flow_type: authentication_flow_type.or(source.authentication_flow_type),
message_version: message_version.or(source.message_version),
eci: eci.or(source.eci),
trans_status: trans_status.or(source.trans_status),
acquirer_bin: acquirer_bin.or(source.acquirer_bin),
acquirer_merchant_id: acquirer_merchant_id.or(source.acquirer_merchant_id),
three_ds_method_data: three_ds_method_data.or(source.three_ds_method_data),
three_ds_method_url: three_ds_method_url.or(source.three_ds_method_url),
acs_url: acs_url.or(source.acs_url),
challenge_request: challenge_request.or(source.challenge_request),
acs_reference_number: acs_reference_number.or(source.acs_reference_number),
acs_trans_id: acs_trans_id.or(source.acs_trans_id),
acs_signed_content: acs_signed_content.or(source.acs_signed_content),
ds_trans_id: ds_trans_id.or(source.ds_trans_id),
directory_server_id: directory_server_id.or(source.directory_server_id),
acquirer_country_code: acquirer_country_code.or(source.acquirer_country_code),
service_details: service_details.or(source.service_details),
force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge),
psd2_sca_exemption_type: psd2_sca_exemption_type.or(source.psd2_sca_exemption_type),
billing_address: billing_address.or(source.billing_address),
shipping_address: shipping_address.or(source.shipping_address),
browser_info: browser_info.or(source.browser_info),
email: email.or(source.email),
profile_acquirer_id: profile_acquirer_id.or(source.profile_acquirer_id),
challenge_code: challenge_code.or(source.challenge_code),
challenge_cancel: challenge_cancel.or(source.challenge_cancel),
challenge_code_reason: challenge_code_reason.or(source.challenge_code_reason),
message_extension: message_extension.or(source.message_extension),
challenge_request_key: challenge_request_key.or(source.challenge_request_key),
..source
}
}
}
impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {
fn from(auth_update: AuthenticationUpdate) -> Self {
match auth_update {
AuthenticationUpdate::ErrorUpdate {
error_message,
error_code,
authentication_status,
connector_authentication_id,
} => Self {
error_code,
error_message,
authentication_status: Some(authentication_status),
connector_authentication_id,
authentication_type: None,
authentication_lifecycle_status: None,
modified_at: common_utils::date_time::now(),
payment_method_id: None,
connector_metadata: None,
..Default::default()
},
AuthenticationUpdate::PostAuthorizationUpdate {
authentication_lifecycle_status,
} => Self {
connector_authentication_id: None,
payment_method_id: None,
authentication_type: None,
authentication_status: None,
authentication_lifecycle_status: Some(authentication_lifecycle_status),
modified_at: common_utils::date_time::now(),
error_message: None,
error_code: None,
connector_metadata: None,
..Default::default()
},
AuthenticationUpdate::PreAuthenticationUpdate {
threeds_server_transaction_id,
maximum_supported_3ds_version,
connector_authentication_id,
three_ds_method_data,
three_ds_method_url,
message_version,
connector_metadata,
authentication_status,
acquirer_bin,
acquirer_merchant_id,
directory_server_id,
acquirer_country_code,
billing_address,
shipping_address,
browser_info,
email,
} => Self {
threeds_server_transaction_id: Some(threeds_server_transaction_id),
maximum_supported_version: Some(maximum_supported_3ds_version),
connector_authentication_id: Some(connector_authentication_id),
three_ds_method_data,
three_ds_method_url,
message_version: Some(message_version),
connector_metadata,
authentication_status: Some(authentication_status),
acquirer_bin,
acquirer_merchant_id,
directory_server_id,
acquirer_country_code,
billing_address,
shipping_address,
browser_info: *browser_info,
email,
..Default::default()
},
AuthenticationUpdate::AuthenticationUpdate {
trans_status,
authentication_type,
acs_url,
challenge_request,
acs_reference_number,
acs_trans_id,
acs_signed_content,
connector_metadata,
authentication_status,
ds_trans_id,
eci,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
challenge_request_key,
} => Self {
trans_status: Some(trans_status),
authentication_type: Some(authentication_type),
acs_url,
challenge_request,
acs_reference_number,
acs_trans_id,
acs_signed_content,
connector_metadata,
authentication_status: Some(authentication_status),
ds_trans_id,
eci,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
challenge_request_key,
..Default::default()
},
AuthenticationUpdate::PostAuthenticationUpdate {
trans_status,
eci,
authentication_status,
challenge_cancel,
challenge_code_reason,
} => Self {
trans_status: Some(trans_status),
eci,
authentication_status: Some(authentication_status),
challenge_cancel,
challenge_code_reason,
..Default::default()
},
AuthenticationUpdate::PreAuthenticationVersionCallUpdate {
maximum_supported_3ds_version,
message_version,
} => Self {
maximum_supported_version: Some(maximum_supported_3ds_version),
message_version: Some(message_version),
..Default::default()
},
AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {
threeds_server_transaction_id,
three_ds_method_data,
three_ds_method_url,
acquirer_bin,
acquirer_merchant_id,
connector_metadata,
} => Self {
threeds_server_transaction_id: Some(threeds_server_transaction_id),
three_ds_method_data,
three_ds_method_url,
acquirer_bin,
acquirer_merchant_id,
connector_metadata,
..Default::default()
},
AuthenticationUpdate::AuthenticationStatusUpdate {
trans_status,
authentication_status,
} => Self {
trans_status: Some(trans_status),
authentication_status: Some(authentication_status),
..Default::default()
},
}
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/authentication.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4758
}
|
large_file_-4486871888406585762
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/mandate.rs
</path>
<file>
use common_enums::MerchantStorageScheme;
use common_utils::pii;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::mandate};
#[derive(
Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize,
)]
#[diesel(table_name = mandate, primary_key(mandate_id), check_for_backend(diesel::pg::Pg))]
pub struct Mandate {
pub mandate_id: String,
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub mandate_status: storage_enums::MandateStatus,
pub mandate_type: storage_enums::MandateType,
pub customer_accepted_at: Option<PrimitiveDateTime>,
pub customer_ip_address: Option<Secret<String, pii::IpAddress>>,
pub customer_user_agent: Option<String>,
pub network_transaction_id: Option<String>,
pub previous_attempt_id: Option<String>,
pub created_at: PrimitiveDateTime,
pub mandate_amount: Option<i64>,
pub mandate_currency: Option<storage_enums::Currency>,
pub amount_captured: Option<i64>,
pub connector: String,
pub connector_mandate_id: Option<String>,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_ids: Option<pii::SecretSerdeValue>,
pub original_payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub updated_by: Option<String>,
// This is the extended version of customer user agent that can store string upto 2048 characters unlike customer user agent that can store 255 characters at max
pub customer_user_agent_extended: Option<String>,
}
#[derive(
router_derive::Setter,
Clone,
Debug,
Default,
Insertable,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = mandate)]
pub struct MandateNew {
pub mandate_id: String,
pub customer_id: common_utils::id_type::CustomerId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub mandate_status: storage_enums::MandateStatus,
pub mandate_type: storage_enums::MandateType,
pub customer_accepted_at: Option<PrimitiveDateTime>,
pub customer_ip_address: Option<Secret<String, pii::IpAddress>>,
pub customer_user_agent: Option<String>,
pub network_transaction_id: Option<String>,
pub previous_attempt_id: Option<String>,
pub created_at: Option<PrimitiveDateTime>,
pub mandate_amount: Option<i64>,
pub mandate_currency: Option<storage_enums::Currency>,
pub amount_captured: Option<i64>,
pub connector: String,
pub connector_mandate_id: Option<String>,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_ids: Option<pii::SecretSerdeValue>,
pub original_payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub updated_by: Option<String>,
pub customer_user_agent_extended: Option<String>,
}
impl Mandate {
/// Returns customer_user_agent_extended with customer_user_agent as fallback
pub fn get_user_agent_extended(&self) -> Option<String> {
self.customer_user_agent_extended
.clone()
.or_else(|| self.customer_user_agent.clone())
}
}
impl MandateNew {
pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) {
self.updated_by = Some(storage_scheme.to_string());
}
/// Returns customer_user_agent_extended with customer_user_agent as fallback
pub fn get_customer_user_agent_extended(&self) -> Option<String> {
self.customer_user_agent_extended
.clone()
.or_else(|| self.customer_user_agent.clone())
}
}
#[derive(Debug)]
pub enum MandateUpdate {
StatusUpdate {
mandate_status: storage_enums::MandateStatus,
},
CaptureAmountUpdate {
amount_captured: Option<i64>,
},
ConnectorReferenceUpdate {
connector_mandate_ids: Option<pii::SecretSerdeValue>,
},
ConnectorMandateIdUpdate {
connector_mandate_id: Option<String>,
connector_mandate_ids: Option<pii::SecretSerdeValue>,
payment_method_id: String,
original_payment_id: Option<common_utils::id_type::PaymentId>,
},
}
impl MandateUpdate {
pub fn convert_to_mandate_update(
self,
storage_scheme: MerchantStorageScheme,
) -> MandateUpdateInternal {
let mut updated_object = MandateUpdateInternal::from(self);
updated_object.updated_by = Some(storage_scheme.to_string());
updated_object
}
}
#[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct SingleUseMandate {
pub amount: i64,
pub currency: storage_enums::Currency,
}
#[derive(
Clone,
Debug,
Default,
AsChangeset,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = mandate)]
pub struct MandateUpdateInternal {
mandate_status: Option<storage_enums::MandateStatus>,
amount_captured: Option<i64>,
connector_mandate_ids: Option<pii::SecretSerdeValue>,
connector_mandate_id: Option<String>,
payment_method_id: Option<String>,
original_payment_id: Option<common_utils::id_type::PaymentId>,
updated_by: Option<String>,
}
impl From<MandateUpdate> for MandateUpdateInternal {
fn from(mandate_update: MandateUpdate) -> Self {
match mandate_update {
MandateUpdate::StatusUpdate { mandate_status } => Self {
mandate_status: Some(mandate_status),
connector_mandate_ids: None,
amount_captured: None,
connector_mandate_id: None,
payment_method_id: None,
original_payment_id: None,
updated_by: None,
},
MandateUpdate::CaptureAmountUpdate { amount_captured } => Self {
mandate_status: None,
amount_captured,
connector_mandate_ids: None,
connector_mandate_id: None,
payment_method_id: None,
original_payment_id: None,
updated_by: None,
},
MandateUpdate::ConnectorReferenceUpdate {
connector_mandate_ids,
} => Self {
connector_mandate_ids,
..Default::default()
},
MandateUpdate::ConnectorMandateIdUpdate {
connector_mandate_id,
connector_mandate_ids,
payment_method_id,
original_payment_id,
} => Self {
connector_mandate_id,
connector_mandate_ids,
payment_method_id: Some(payment_method_id),
original_payment_id,
..Default::default()
},
}
}
}
impl MandateUpdateInternal {
pub fn apply_changeset(self, source: Mandate) -> Mandate {
let Self {
mandate_status,
amount_captured,
connector_mandate_ids,
connector_mandate_id,
payment_method_id,
original_payment_id,
updated_by,
} = self;
Mandate {
mandate_status: mandate_status.unwrap_or(source.mandate_status),
amount_captured: amount_captured.map_or(source.amount_captured, Some),
connector_mandate_ids: connector_mandate_ids.map_or(source.connector_mandate_ids, Some),
connector_mandate_id: connector_mandate_id.map_or(source.connector_mandate_id, Some),
payment_method_id: payment_method_id.unwrap_or(source.payment_method_id),
original_payment_id: original_payment_id.map_or(source.original_payment_id, Some),
updated_by: updated_by.map_or(source.updated_by, Some),
..source
}
}
}
impl From<&MandateNew> for Mandate {
fn from(mandate_new: &MandateNew) -> Self {
Self {
mandate_id: mandate_new.mandate_id.clone(),
customer_id: mandate_new.customer_id.clone(),
merchant_id: mandate_new.merchant_id.clone(),
payment_method_id: mandate_new.payment_method_id.clone(),
mandate_status: mandate_new.mandate_status,
mandate_type: mandate_new.mandate_type,
customer_accepted_at: mandate_new.customer_accepted_at,
customer_ip_address: mandate_new.customer_ip_address.clone(),
customer_user_agent: None,
network_transaction_id: mandate_new.network_transaction_id.clone(),
previous_attempt_id: mandate_new.previous_attempt_id.clone(),
created_at: mandate_new
.created_at
.unwrap_or_else(common_utils::date_time::now),
mandate_amount: mandate_new.mandate_amount,
mandate_currency: mandate_new.mandate_currency,
amount_captured: mandate_new.amount_captured,
connector: mandate_new.connector.clone(),
connector_mandate_id: mandate_new.connector_mandate_id.clone(),
start_date: mandate_new.start_date,
end_date: mandate_new.end_date,
metadata: mandate_new.metadata.clone(),
connector_mandate_ids: mandate_new.connector_mandate_ids.clone(),
original_payment_id: mandate_new.original_payment_id.clone(),
merchant_connector_id: mandate_new.merchant_connector_id.clone(),
updated_by: mandate_new.updated_by.clone(),
// Using customer_user_agent as a fallback
customer_user_agent_extended: mandate_new.get_customer_user_agent_extended(),
}
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/mandate.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2148
}
|
large_file_7349506525157592339
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/user/sample_data.rs
</path>
<file>
#[cfg(feature = "v1")]
use common_enums::{
AttemptStatus, AuthenticationType, CaptureMethod, Currency, PaymentExperience, PaymentMethod,
PaymentMethodType,
};
#[cfg(feature = "v1")]
use common_types::primitive_wrappers::{
ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool,
};
#[cfg(feature = "v1")]
use common_utils::types::{ConnectorTransactionId, MinorUnit};
#[cfg(feature = "v1")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "v1")]
use time::PrimitiveDateTime;
#[cfg(feature = "v1")]
use crate::{
enums::{MandateDataType, MandateDetails},
schema::payment_attempt,
ConnectorMandateReferenceId, NetworkDetails, PaymentAttemptNew,
};
// #[cfg(feature = "v2")]
// #[derive(
// Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
// )]
// #[diesel(table_name = payment_attempt)]
// pub struct PaymentAttemptBatchNew {
// pub payment_id: common_utils::id_type::PaymentId,
// pub merchant_id: common_utils::id_type::MerchantId,
// pub status: AttemptStatus,
// pub error_message: Option<String>,
// pub surcharge_amount: Option<i64>,
// pub tax_on_surcharge: Option<i64>,
// pub payment_method_id: Option<String>,
// pub authentication_type: Option<AuthenticationType>,
// #[serde(with = "common_utils::custom_serde::iso8601")]
// pub created_at: PrimitiveDateTime,
// #[serde(with = "common_utils::custom_serde::iso8601")]
// pub modified_at: PrimitiveDateTime,
// #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
// pub last_synced: Option<PrimitiveDateTime>,
// pub cancellation_reason: Option<String>,
// pub browser_info: Option<serde_json::Value>,
// pub payment_token: Option<String>,
// pub error_code: Option<String>,
// pub connector_metadata: Option<serde_json::Value>,
// pub payment_experience: Option<PaymentExperience>,
// pub payment_method_data: Option<serde_json::Value>,
// pub preprocessing_step_id: Option<String>,
// pub error_reason: Option<String>,
// pub connector_response_reference_id: Option<String>,
// pub multiple_capture_count: Option<i16>,
// pub amount_capturable: i64,
// pub updated_by: String,
// pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
// pub authentication_data: Option<serde_json::Value>,
// pub encoded_data: Option<String>,
// pub unified_code: Option<String>,
// pub unified_message: Option<String>,
// pub net_amount: Option<i64>,
// pub external_three_ds_authentication_attempted: Option<bool>,
// pub authentication_connector: Option<String>,
// pub authentication_id: Option<String>,
// pub fingerprint_id: Option<String>,
// pub charge_id: Option<String>,
// pub client_source: Option<String>,
// pub client_version: Option<String>,
// pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,
// pub profile_id: common_utils::id_type::ProfileId,
// pub organization_id: common_utils::id_type::OrganizationId,
// }
// #[cfg(feature = "v2")]
// #[allow(dead_code)]
// impl PaymentAttemptBatchNew {
// // Used to verify compatibility with PaymentAttemptTable
// fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew {
// // PaymentAttemptNew {
// // payment_id: self.payment_id,
// // merchant_id: self.merchant_id,
// // status: self.status,
// // error_message: self.error_message,
// // surcharge_amount: self.surcharge_amount,
// // tax_amount: self.tax_amount,
// // payment_method_id: self.payment_method_id,
// // confirm: self.confirm,
// // authentication_type: self.authentication_type,
// // created_at: self.created_at,
// // modified_at: self.modified_at,
// // last_synced: self.last_synced,
// // cancellation_reason: self.cancellation_reason,
// // browser_info: self.browser_info,
// // payment_token: self.payment_token,
// // error_code: self.error_code,
// // connector_metadata: self.connector_metadata,
// // payment_experience: self.payment_experience,
// // card_network: self
// // .payment_method_data
// // .as_ref()
// // .and_then(|data| data.as_object())
// // .and_then(|card| card.get("card"))
// // .and_then(|v| v.as_object())
// // .and_then(|v| v.get("card_network"))
// // .and_then(|network| network.as_str())
// // .map(|network| network.to_string()),
// // payment_method_data: self.payment_method_data,
// // straight_through_algorithm: self.straight_through_algorithm,
// // preprocessing_step_id: self.preprocessing_step_id,
// // error_reason: self.error_reason,
// // multiple_capture_count: self.multiple_capture_count,
// // connector_response_reference_id: self.connector_response_reference_id,
// // amount_capturable: self.amount_capturable,
// // updated_by: self.updated_by,
// // merchant_connector_id: self.merchant_connector_id,
// // authentication_data: self.authentication_data,
// // encoded_data: self.encoded_data,
// // unified_code: self.unified_code,
// // unified_message: self.unified_message,
// // net_amount: self.net_amount,
// // external_three_ds_authentication_attempted: self
// // .external_three_ds_authentication_attempted,
// // authentication_connector: self.authentication_connector,
// // authentication_id: self.authentication_id,
// // payment_method_billing_address_id: self.payment_method_billing_address_id,
// // fingerprint_id: self.fingerprint_id,
// // charge_id: self.charge_id,
// // client_source: self.client_source,
// // client_version: self.client_version,
// // customer_acceptance: self.customer_acceptance,
// // profile_id: self.profile_id,
// // organization_id: self.organization_id,
// // }
// todo!()
// }
// }
#[cfg(feature = "v1")]
#[derive(
Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
)]
#[diesel(table_name = payment_attempt)]
pub struct PaymentAttemptBatchNew {
pub payment_id: common_utils::id_type::PaymentId,
pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
pub status: AttemptStatus,
pub amount: MinorUnit,
pub currency: Option<Currency>,
pub save_to_locker: Option<bool>,
pub connector: Option<String>,
pub error_message: Option<String>,
pub offer_amount: Option<MinorUnit>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<String>,
pub payment_method: Option<PaymentMethod>,
pub capture_method: Option<CaptureMethod>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub capture_on: Option<PrimitiveDateTime>,
pub confirm: bool,
pub authentication_type: Option<AuthenticationType>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<String>,
pub browser_info: Option<serde_json::Value>,
pub payment_token: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub payment_experience: Option<PaymentExperience>,
pub payment_method_type: Option<PaymentMethodType>,
pub payment_method_data: Option<serde_json::Value>,
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
pub mandate_details: Option<MandateDataType>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
pub connector_transaction_id: Option<ConnectorTransactionId>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub updated_by: String,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub net_amount: Option<MinorUnit>,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<common_utils::id_type::AuthenticationId>,
pub mandate_data: Option<MandateDetails>,
pub payment_method_billing_address_id: Option<String>,
pub fingerprint_id: Option<String>,
pub charge_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,
pub profile_id: common_utils::id_type::ProfileId,
pub organization_id: common_utils::id_type::OrganizationId,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub processor_transaction_data: Option<String>,
pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
pub capture_before: Option<PrimitiveDateTime>,
pub card_discovery: Option<common_enums::CardDiscovery>,
pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
pub created_by: Option<String>,
pub setup_future_usage_applied: Option<common_enums::FutureUsage>,
pub routing_approach: Option<common_enums::RoutingApproach>,
pub connector_request_reference_id: Option<String>,
pub network_transaction_id: Option<String>,
pub network_details: Option<NetworkDetails>,
pub is_stored_credential: Option<bool>,
pub authorized_amount: Option<MinorUnit>,
}
#[cfg(feature = "v1")]
#[allow(dead_code)]
impl PaymentAttemptBatchNew {
// Used to verify compatibility with PaymentAttemptTable
fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew {
PaymentAttemptNew {
payment_id: self.payment_id,
merchant_id: self.merchant_id,
attempt_id: self.attempt_id,
status: self.status,
amount: self.amount,
currency: self.currency,
save_to_locker: self.save_to_locker,
connector: self.connector,
error_message: self.error_message,
offer_amount: self.offer_amount,
surcharge_amount: self.surcharge_amount,
tax_amount: self.tax_amount,
payment_method_id: self.payment_method_id,
payment_method: self.payment_method,
capture_method: self.capture_method,
capture_on: self.capture_on,
confirm: self.confirm,
authentication_type: self.authentication_type,
created_at: self.created_at,
modified_at: self.modified_at,
last_synced: self.last_synced,
cancellation_reason: self.cancellation_reason,
amount_to_capture: self.amount_to_capture,
mandate_id: self.mandate_id,
browser_info: self.browser_info,
payment_token: self.payment_token,
error_code: self.error_code,
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
card_network: self
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|v| v.as_object())
.and_then(|v| v.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
preprocessing_step_id: self.preprocessing_step_id,
mandate_details: self.mandate_details,
error_reason: self.error_reason,
multiple_capture_count: self.multiple_capture_count,
connector_response_reference_id: self.connector_response_reference_id,
amount_capturable: self.amount_capturable,
updated_by: self.updated_by,
merchant_connector_id: self.merchant_connector_id,
authentication_data: self.authentication_data,
encoded_data: self.encoded_data,
unified_code: self.unified_code,
unified_message: self.unified_message,
net_amount: self.net_amount,
external_three_ds_authentication_attempted: self
.external_three_ds_authentication_attempted,
authentication_connector: self.authentication_connector,
authentication_id: self.authentication_id,
mandate_data: self.mandate_data,
payment_method_billing_address_id: self.payment_method_billing_address_id,
fingerprint_id: self.fingerprint_id,
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
profile_id: self.profile_id,
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
order_tax_amount: self.order_tax_amount,
connector_mandate_detail: self.connector_mandate_detail,
request_extended_authorization: self.request_extended_authorization,
extended_authorization_applied: self.extended_authorization_applied,
capture_before: self.capture_before,
card_discovery: self.card_discovery,
processor_merchant_id: self.processor_merchant_id,
created_by: self.created_by,
setup_future_usage_applied: self.setup_future_usage_applied,
routing_approach: self.routing_approach,
connector_request_reference_id: self.connector_request_reference_id,
network_transaction_id: self.network_transaction_id,
network_details: self.network_details,
is_stored_credential: self.is_stored_credential,
authorized_amount: self.authorized_amount,
}
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/user/sample_data.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3211
}
|
large_file_-5219693893058902486
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/query/payment_attempt.rs
</path>
<file>
#[cfg(feature = "v1")]
use std::collections::HashSet;
use async_bb8_diesel::AsyncRunQueryDsl;
#[cfg(feature = "v1")]
use diesel::Table;
use diesel::{
associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl,
};
use error_stack::{report, ResultExt};
use super::generics;
#[cfg(feature = "v1")]
use crate::schema::payment_attempt::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::payment_attempt::dsl;
#[cfg(feature = "v1")]
use crate::{enums::IntentStatus, payment_attempt::PaymentAttemptUpdate, PaymentIntent};
use crate::{
enums::{self},
errors::DatabaseError,
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdateInternal},
query::generics::db_metrics,
PgPooledConn, StorageResult,
};
impl PaymentAttemptNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentAttempt> {
generics::generic_insert(conn, self).await
}
}
impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn update_with_attempt_id(
self,
conn: &PgPooledConn,
payment_attempt: PaymentAttemptUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::attempt_id
.eq(self.attempt_id.to_owned())
.and(dsl::merchant_id.eq(self.merchant_id.to_owned())),
PaymentAttemptUpdateInternal::from(payment_attempt).populate_derived_fields(&self),
)
.await
{
Err(error) => match error.current_context() {
DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
#[cfg(feature = "v2")]
pub async fn update_with_attempt_id(
self,
conn: &PgPooledConn,
payment_attempt: PaymentAttemptUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(conn, dsl::id.eq(self.id.to_owned()), payment_attempt)
.await
{
Err(error) => match error.current_context() {
DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
#[cfg(feature = "v1")]
pub async fn find_optional_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_id.eq(payment_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_by_connector_transaction_id_payment_id_merchant_id(
conn: &PgPooledConn,
connector_transaction_id: &common_utils::types::ConnectorTransactionId,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::connector_transaction_id
.eq(connector_transaction_id.get_id().to_owned())
.and(dsl::payment_id.eq(payment_id.to_owned()))
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_last_successful_attempt_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
// perform ordering on the application level instead of database level
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
dsl::payment_id
.eq(payment_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::status.eq(enums::AttemptStatus::Charged)),
Some(1),
None,
Some(dsl::modified_at.desc()),
)
.await?
.into_iter()
.nth(0)
.ok_or(report!(DatabaseError::NotFound))
}
#[cfg(feature = "v1")]
pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
// perform ordering on the application level instead of database level
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
dsl::payment_id
.eq(payment_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(
dsl::status
.eq(enums::AttemptStatus::Charged)
.or(dsl::status.eq(enums::AttemptStatus::PartialCharged)),
),
Some(1),
None,
Some(dsl::modified_at.desc()),
)
.await?
.into_iter()
.nth(0)
.ok_or(report!(DatabaseError::NotFound))
}
#[cfg(feature = "v2")]
pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id(
conn: &PgPooledConn,
payment_id: &common_utils::id_type::GlobalPaymentId,
) -> StorageResult<Self> {
// perform ordering on the application level instead of database level
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
dsl::payment_id.eq(payment_id.to_owned()).and(
dsl::status
.eq(enums::AttemptStatus::Charged)
.or(dsl::status.eq(enums::AttemptStatus::PartialCharged)),
),
Some(1),
None,
Some(dsl::modified_at.desc()),
)
.await?
.into_iter()
.nth(0)
.ok_or(report!(DatabaseError::NotFound))
}
#[cfg(feature = "v1")]
pub async fn find_by_merchant_id_connector_txn_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
connector_txn_id: &str,
) -> StorageResult<Self> {
let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data(
connector_txn_id.to_string(),
);
let connector_transaction_id = txn_id
.get_txn_id(txn_data.as_ref())
.change_context(DatabaseError::Others)
.attach_printable_lazy(|| {
format!("Failed to retrieve txn_id for ({txn_id:?}, {txn_data:?})")
})?;
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())),
)
.await
}
#[cfg(feature = "v2")]
pub async fn find_by_profile_id_connector_transaction_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
connector_txn_id: &str,
) -> StorageResult<Self> {
let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data(
connector_txn_id.to_string(),
);
let connector_transaction_id = txn_id
.get_txn_id(txn_data.as_ref())
.change_context(DatabaseError::Others)
.attach_printable_lazy(|| {
format!("Failed to retrieve txn_id for ({txn_id:?}, {txn_data:?})")
})?;
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::profile_id
.eq(profile_id.to_owned())
.and(dsl::connector_payment_id.eq(connector_transaction_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_by_merchant_id_attempt_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::attempt_id.eq(attempt_id.to_owned())),
)
.await
}
#[cfg(feature = "v2")]
pub async fn find_by_id(
conn: &PgPooledConn,
id: &common_utils::id_type::GlobalAttemptId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::id.eq(id.to_owned()),
)
.await
}
#[cfg(feature = "v2")]
pub async fn find_by_payment_id(
conn: &PgPooledConn,
payment_id: &common_utils::id_type::GlobalPaymentId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::payment_id.eq(payment_id.to_owned()),
None,
None,
Some(dsl::created_at.asc()),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_by_merchant_id_preprocessing_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
preprocessing_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::preprocessing_step_id.eq(preprocessing_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_by_payment_id_merchant_id_attempt_id(
conn: &PgPooledConn,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::payment_id.eq(payment_id.to_owned()).and(
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::attempt_id.eq(attempt_id.to_owned())),
),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_by_merchant_id_payment_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_id.eq(payment_id.to_owned())),
None,
None,
None,
)
.await
}
#[cfg(feature = "v1")]
pub async fn get_filters_for_payments(
conn: &PgPooledConn,
pi: &[PaymentIntent],
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<(
Vec<String>,
Vec<enums::Currency>,
Vec<IntentStatus>,
Vec<enums::PaymentMethod>,
Vec<enums::PaymentMethodType>,
Vec<enums::AuthenticationType>,
)> {
let active_attempts: Vec<String> = pi
.iter()
.map(|payment_intent| payment_intent.clone().active_attempt_id)
.collect();
let filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(dsl::attempt_id.eq_any(active_attempts));
let intent_status: Vec<IntentStatus> = pi
.iter()
.map(|payment_intent| payment_intent.status)
.collect::<HashSet<IntentStatus>>()
.into_iter()
.collect();
let filter_connector = filter
.clone()
.select(dsl::connector)
.distinct()
.get_results_async::<Option<String>>(conn)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by connector")?
.into_iter()
.flatten()
.collect::<Vec<String>>();
let filter_currency = filter
.clone()
.select(dsl::currency)
.distinct()
.get_results_async::<Option<enums::Currency>>(conn)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by currency")?
.into_iter()
.flatten()
.collect::<Vec<enums::Currency>>();
let filter_payment_method = filter
.clone()
.select(dsl::payment_method)
.distinct()
.get_results_async::<Option<enums::PaymentMethod>>(conn)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by payment method")?
.into_iter()
.flatten()
.collect::<Vec<enums::PaymentMethod>>();
let filter_payment_method_type = filter
.clone()
.select(dsl::payment_method_type)
.distinct()
.get_results_async::<Option<enums::PaymentMethodType>>(conn)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by payment method type")?
.into_iter()
.flatten()
.collect::<Vec<enums::PaymentMethodType>>();
let filter_authentication_type = filter
.clone()
.select(dsl::authentication_type)
.distinct()
.get_results_async::<Option<enums::AuthenticationType>>(conn)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by authentication type")?
.into_iter()
.flatten()
.collect::<Vec<enums::AuthenticationType>>();
Ok((
filter_connector,
filter_currency,
intent_status,
filter_payment_method,
filter_payment_method_type,
filter_authentication_type,
))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn get_total_count_of_attempts(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<String>>,
payment_method_type: Option<Vec<enums::PaymentMethod>>,
payment_method_subtype: Option<Vec<enums::PaymentMethodType>>,
authentication_type: Option<Vec<enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
card_network: Option<Vec<enums::CardNetwork>>,
) -> StorageResult<i64> {
let mut filter = <Self as HasTable>::table()
.count()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(dsl::id.eq_any(active_attempt_ids.to_owned()))
.into_boxed();
if let Some(connectors) = connector {
filter = filter.filter(dsl::connector.eq_any(connectors));
}
if let Some(payment_method_types) = payment_method_type {
filter = filter.filter(dsl::payment_method_type_v2.eq_any(payment_method_types));
}
if let Some(payment_method_subtypes) = payment_method_subtype {
filter = filter.filter(dsl::payment_method_subtype.eq_any(payment_method_subtypes));
}
if let Some(authentication_types) = authentication_type {
filter = filter.filter(dsl::authentication_type.eq_any(authentication_types));
}
if let Some(merchant_connector_ids) = merchant_connector_id {
filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_ids));
}
if let Some(card_networks) = card_network {
filter = filter.filter(dsl::card_network.eq_any(card_networks));
}
router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
// TODO: Remove these logs after debugging the issue for delay in count query
let start_time = std::time::Instant::now();
router_env::logger::debug!("Executing count query start_time: {:?}", start_time);
let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_result_async::<i64>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering count of payments");
let duration = start_time.elapsed();
router_env::logger::debug!("Completed count query in {:?}", duration);
result
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn get_total_count_of_attempts(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<String>>,
payment_method: Option<Vec<enums::PaymentMethod>>,
payment_method_type: Option<Vec<enums::PaymentMethodType>>,
authentication_type: Option<Vec<enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
card_network: Option<Vec<enums::CardNetwork>>,
card_discovery: Option<Vec<enums::CardDiscovery>>,
) -> StorageResult<i64> {
let mut filter = <Self as HasTable>::table()
.count()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned()))
.into_boxed();
if let Some(connector) = connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
if let Some(payment_method) = payment_method {
filter = filter.filter(dsl::payment_method.eq_any(payment_method));
}
if let Some(payment_method_type) = payment_method_type {
filter = filter.filter(dsl::payment_method_type.eq_any(payment_method_type));
}
if let Some(authentication_type) = authentication_type {
filter = filter.filter(dsl::authentication_type.eq_any(authentication_type));
}
if let Some(merchant_connector_id) = merchant_connector_id {
filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id))
}
if let Some(card_network) = card_network {
filter = filter.filter(dsl::card_network.eq_any(card_network))
}
if let Some(card_discovery) = card_discovery {
filter = filter.filter(dsl::card_discovery.eq_any(card_discovery))
}
router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
// TODO: Remove these logs after debugging the issue for delay in count query
let start_time = std::time::Instant::now();
router_env::logger::debug!("Executing count query start_time: {:?}", start_time);
let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_result_async::<i64>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering count of payments");
let duration = start_time.elapsed();
router_env::logger::debug!("Completed count query in {:?}", duration);
result
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/query/payment_attempt.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4469
}
|
large_file_-8608635625164112533
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/query/events.rs
</path>
<file>
use std::collections::HashSet;
use diesel::{
associations::HasTable, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods,
};
use super::generics;
use crate::{
events::{Event, EventNew, EventUpdateInternal},
schema::events::dsl,
PgPooledConn, StorageResult,
};
impl EventNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Event> {
generics::generic_insert(conn, self).await
}
}
impl Event {
pub async fn find_by_merchant_id_event_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::event_id.eq(event_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_idempotent_event_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
idempotent_event_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::idempotent_event_id.eq(idempotent_event_id.to_owned())),
)
.await
}
pub async fn list_initial_attempts_by_merchant_id_primary_object_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
None,
None,
Some(dsl::created_at.desc()),
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn list_initial_attempts_by_merchant_id_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> StorageResult<Vec<Self>> {
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{debug_query, pg::Pg, QueryDsl};
use error_stack::ResultExt;
use router_env::logger;
use super::generics::db_metrics::{track_database_call, DatabaseOperation};
use crate::errors::DatabaseError;
let mut query = Self::table()
.filter(
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.order(dsl::created_at.desc())
.into_boxed();
query = Self::apply_filters(
query,
None,
(dsl::created_at, created_after, created_before),
limit,
offset,
event_types,
is_delivered,
);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
.await
.change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
.attach_printable("Error filtering events by constraints")
}
pub async fn list_by_merchant_id_initial_attempt_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),
None,
None,
Some(dsl::created_at.desc()),
)
.await
}
pub async fn list_initial_attempts_by_profile_id_primary_object_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
primary_object_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::business_profile_id.eq(profile_id.to_owned()))
.and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
None,
None,
Some(dsl::created_at.desc()),
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn list_initial_attempts_by_profile_id_constraints(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> StorageResult<Vec<Self>> {
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{debug_query, pg::Pg, QueryDsl};
use error_stack::ResultExt;
use router_env::logger;
use super::generics::db_metrics::{track_database_call, DatabaseOperation};
use crate::errors::DatabaseError;
let mut query = Self::table()
.filter(
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::business_profile_id.eq(profile_id.to_owned())),
)
.order(dsl::created_at.desc())
.into_boxed();
query = Self::apply_filters(
query,
None,
(dsl::created_at, created_after, created_before),
limit,
offset,
event_types,
is_delivered,
);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
.await
.change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
.attach_printable("Error filtering events by constraints")
}
pub async fn list_by_profile_id_initial_attempt_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
initial_attempt_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::business_profile_id
.eq(profile_id.to_owned())
.and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),
None,
None,
Some(dsl::created_at.desc()),
)
.await
}
pub async fn update_by_merchant_id_event_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: EventUpdateInternal,
) -> StorageResult<Self> {
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::event_id.eq(event_id.to_owned())),
event,
)
.await
}
fn apply_filters<T>(
mut query: T,
profile_id: Option<common_utils::id_type::ProfileId>,
(column, created_after, created_before): (
dsl::created_at,
time::PrimitiveDateTime,
time::PrimitiveDateTime,
),
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> T
where
T: diesel::query_dsl::methods::LimitDsl<Output = T>
+ diesel::query_dsl::methods::OffsetDsl<Output = T>,
T: diesel::query_dsl::methods::FilterDsl<
diesel::dsl::GtEq<dsl::created_at, time::PrimitiveDateTime>,
Output = T,
>,
T: diesel::query_dsl::methods::FilterDsl<
diesel::dsl::LtEq<dsl::created_at, time::PrimitiveDateTime>,
Output = T,
>,
T: diesel::query_dsl::methods::FilterDsl<
diesel::dsl::Eq<dsl::business_profile_id, common_utils::id_type::ProfileId>,
Output = T,
>,
T: diesel::query_dsl::methods::FilterDsl<
diesel::dsl::EqAny<dsl::event_type, HashSet<common_enums::EventType>>,
Output = T,
>,
T: diesel::query_dsl::methods::FilterDsl<
diesel::dsl::Eq<dsl::is_overall_delivery_successful, bool>,
Output = T,
>,
{
if let Some(profile_id) = profile_id {
query = query.filter(dsl::business_profile_id.eq(profile_id));
}
query = query
.filter(column.ge(created_after))
.filter(column.le(created_before));
if let Some(limit) = limit {
query = query.limit(limit);
}
if let Some(offset) = offset {
query = query.offset(offset);
}
if !event_types.is_empty() {
query = query.filter(dsl::event_type.eq_any(event_types));
}
if let Some(is_delivered) = is_delivered {
query = query.filter(dsl::is_overall_delivery_successful.eq(is_delivered));
}
query
}
pub async fn count_initial_attempts_by_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> StorageResult<i64> {
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{debug_query, pg::Pg, QueryDsl};
use error_stack::ResultExt;
use router_env::logger;
use super::generics::db_metrics::{track_database_call, DatabaseOperation};
use crate::errors::DatabaseError;
let mut query = Self::table()
.count()
.filter(
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.into_boxed();
query = Self::apply_filters(
query,
profile_id,
(dsl::created_at, created_after, created_before),
None,
None,
event_types,
is_delivered,
);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<Self, _, _>(
query.get_result_async::<i64>(conn),
DatabaseOperation::Count,
)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error counting events by constraints")
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/query/events.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2650
}
|
large_file_679304729511034925
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/query/payment_method.rs
</path>
<file>
use async_bb8_diesel::AsyncRunQueryDsl;
#[cfg(feature = "v1")]
use diesel::Table;
use diesel::{
associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl,
};
use error_stack::ResultExt;
use super::generics;
#[cfg(feature = "v1")]
use crate::schema::payment_methods::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::payment_methods::dsl::{self, id as pm_id};
use crate::{
enums as storage_enums, errors,
payment_method::{self, PaymentMethod, PaymentMethodNew},
PgPooledConn, StorageResult,
};
impl PaymentMethodNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentMethod> {
generics::generic_insert(conn, self).await
}
}
#[cfg(feature = "v1")]
impl PaymentMethod {
pub async fn delete_by_payment_method_id(
conn: &PgPooledConn,
payment_method_id: String,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, Self>(
conn,
dsl::payment_method_id.eq(payment_method_id),
)
.await
}
pub async fn delete_by_merchant_id_payment_method_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_method_id: &str,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, Self>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_method_id.eq(payment_method_id.to_owned())),
)
.await
}
pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::locker_id.eq(locker_id.to_owned()),
)
.await
}
pub async fn find_by_payment_method_id(
conn: &PgPooledConn,
payment_method_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::payment_method_id.eq(payment_method_id.to_owned()),
)
.await
}
pub async fn find_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
None,
None,
None,
)
.await
}
pub async fn find_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
limit,
None,
Some(dsl::last_used_at.desc()),
)
.await
}
pub async fn get_count_by_customer_id_merchant_id_status(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> StorageResult<i64> {
let filter = <Self as HasTable>::table()
.count()
.filter(
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::status.eq(status.to_owned())),
)
.into_boxed();
router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_result_async::<i64>(conn),
generics::db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Failed to get a count of payment methods")
}
pub async fn get_count_by_merchant_id_status(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> StorageResult<i64> {
let query = <Self as HasTable>::table().count().filter(
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::status.eq(status.to_owned())),
);
router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
query.get_result_async::<i64>(conn),
generics::db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Failed to get a count of payment methods")
}
pub async fn find_by_customer_id_merchant_id_status(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
status: storage_enums::PaymentMethodStatus,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::status.eq(status)),
limit,
None,
Some(dsl::last_used_at.desc()),
)
.await
}
pub async fn update_with_payment_method_id(
self,
conn: &PgPooledConn,
payment_method: payment_method::PaymentMethodUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::payment_method_id.eq(self.payment_method_id.to_owned()),
payment_method,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
}
#[cfg(feature = "v2")]
impl PaymentMethod {
pub async fn find_by_id(
conn: &PgPooledConn,
id: &common_utils::id_type::GlobalPaymentMethodId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, pm_id.eq(id.to_owned()))
.await
}
pub async fn find_by_global_customer_id_merchant_id_status(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::GlobalCustomerId,
merchant_id: &common_utils::id_type::MerchantId,
status: storage_enums::PaymentMethodStatus,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::status.eq(status)),
limit,
None,
Some(dsl::last_used_at.desc()),
)
.await
}
pub async fn find_by_global_customer_id(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::GlobalCustomerId,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id.eq(customer_id.to_owned()),
limit,
None,
Some(dsl::last_used_at.desc()),
)
.await
}
pub async fn update_with_id(
self,
conn: &PgPooledConn,
payment_method: payment_method::PaymentMethodUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(conn, pm_id.eq(self.id.to_owned()), payment_method)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
pub async fn find_by_fingerprint_id(
conn: &PgPooledConn,
fingerprint_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::locker_fingerprint_id.eq(fingerprint_id.to_owned()),
)
.await
}
pub async fn get_count_by_merchant_id_status(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> StorageResult<i64> {
let query = <Self as HasTable>::table().count().filter(
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::status.eq(status.to_owned())),
);
router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
query.get_result_async::<i64>(conn),
generics::db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Failed to get a count of payment methods")
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/query/payment_method.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2321
}
|
large_file_-2017940047153083555
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/query/user_role.rs
</path>
<file>
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::id_type;
use diesel::{
associations::HasTable,
debug_query,
pg::Pg,
result::Error as DieselError,
sql_types::{Bool, Nullable},
BoolExpressionMethods, ExpressionMethods, QueryDsl,
};
use error_stack::{report, ResultExt};
use crate::{
enums::{UserRoleVersion, UserStatus},
errors,
query::generics,
schema::user_roles::dsl,
user_role::*,
PgPooledConn, StorageResult,
};
impl UserRoleNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserRole> {
generics::generic_insert(conn, self).await
}
}
impl UserRole {
fn check_user_in_lineage(
tenant_id: id_type::TenantId,
org_id: Option<id_type::OrganizationId>,
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
) -> Box<
dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>>
+ 'static,
> {
// Checking in user roles, for a user in token hierarchy, only one of the relations will be true:
// either tenant level, org level, merchant level, or profile level
// Tenant-level: (tenant_id = ? && org_id = null && merchant_id = null && profile_id = null)
// Org-level: (org_id = ? && merchant_id = null && profile_id = null)
// Merchant-level: (org_id = ? && merchant_id = ? && profile_id = null)
// Profile-level: (org_id = ? && merchant_id = ? && profile_id = ?)
Box::new(
// Tenant-level condition
dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.is_null())
.and(dsl::merchant_id.is_null())
.and(dsl::profile_id.is_null())
.or(
// Org-level condition
dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.eq(org_id.clone()))
.and(dsl::merchant_id.is_null())
.and(dsl::profile_id.is_null()),
)
.or(
// Merchant-level condition
dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.eq(org_id.clone()))
.and(dsl::merchant_id.eq(merchant_id.clone()))
.and(dsl::profile_id.is_null()),
)
.or(
// Profile-level condition
dsl::tenant_id
.eq(tenant_id)
.and(dsl::org_id.eq(org_id))
.and(dsl::merchant_id.eq(merchant_id))
.and(dsl::profile_id.eq(profile_id)),
),
)
}
pub async fn find_by_user_id_tenant_id_org_id_merchant_id_profile_id(
conn: &PgPooledConn,
user_id: String,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: id_type::MerchantId,
profile_id: id_type::ProfileId,
version: UserRoleVersion,
) -> StorageResult<Self> {
let check_lineage = Self::check_user_in_lineage(
tenant_id,
Some(org_id),
Some(merchant_id),
Some(profile_id),
);
let predicate = dsl::user_id
.eq(user_id)
.and(check_lineage)
.and(dsl::version.eq(version));
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await
}
#[allow(clippy::too_many_arguments)]
pub async fn update_by_user_id_tenant_id_org_id_merchant_id_profile_id(
conn: &PgPooledConn,
user_id: String,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
update: UserRoleUpdate,
version: UserRoleVersion,
) -> StorageResult<Self> {
let check_lineage = dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.is_null())
.and(dsl::merchant_id.is_null())
.and(dsl::profile_id.is_null())
.or(
// Org-level condition
dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.eq(org_id.clone()))
.and(dsl::merchant_id.is_null())
.and(dsl::profile_id.is_null()),
)
.or(
// Merchant-level condition
dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.eq(org_id.clone()))
.and(dsl::merchant_id.eq(merchant_id.clone()))
.and(dsl::profile_id.is_null()),
)
.or(
// Profile-level condition
dsl::tenant_id
.eq(tenant_id)
.and(dsl::org_id.eq(org_id))
.and(dsl::merchant_id.eq(merchant_id))
.and(dsl::profile_id.eq(profile_id)),
);
let predicate = dsl::user_id
.eq(user_id)
.and(check_lineage)
.and(dsl::version.eq(version));
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
UserRoleUpdateInternal,
_,
_,
>(conn, predicate, update.into())
.await
}
pub async fn delete_by_user_id_tenant_id_org_id_merchant_id_profile_id(
conn: &PgPooledConn,
user_id: String,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: id_type::MerchantId,
profile_id: id_type::ProfileId,
version: UserRoleVersion,
) -> StorageResult<Self> {
let check_lineage = Self::check_user_in_lineage(
tenant_id,
Some(org_id),
Some(merchant_id),
Some(profile_id),
);
let predicate = dsl::user_id
.eq(user_id)
.and(check_lineage)
.and(dsl::version.eq(version));
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(conn, predicate)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn generic_user_roles_list_for_user(
conn: &PgPooledConn,
user_id: String,
tenant_id: id_type::TenantId,
org_id: Option<id_type::OrganizationId>,
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
entity_id: Option<String>,
status: Option<UserStatus>,
version: Option<UserRoleVersion>,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
let mut query = <Self as HasTable>::table()
.filter(dsl::user_id.eq(user_id).and(dsl::tenant_id.eq(tenant_id)))
.into_boxed();
if let Some(org_id) = org_id {
query = query.filter(dsl::org_id.eq(org_id));
}
if let Some(merchant_id) = merchant_id {
query = query.filter(dsl::merchant_id.eq(merchant_id));
}
if let Some(profile_id) = profile_id {
query = query.filter(dsl::profile_id.eq(profile_id));
}
if let Some(entity_id) = entity_id {
query = query.filter(dsl::entity_id.eq(entity_id));
}
if let Some(version) = version {
query = query.filter(dsl::version.eq(version));
}
if let Some(status) = status {
query = query.filter(dsl::status.eq(status));
}
if let Some(limit) = limit {
query = query.limit(limit.into());
}
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
query.get_results_async(conn),
generics::db_metrics::DatabaseOperation::Filter,
)
.await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::NotFound => {
Err(report!(err)).change_context(errors::DatabaseError::NotFound)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
}
#[allow(clippy::too_many_arguments)]
pub async fn generic_user_roles_list_for_org_and_extra(
conn: &PgPooledConn,
user_id: Option<String>,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
version: Option<UserRoleVersion>,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
let mut query = <Self as HasTable>::table()
.filter(dsl::org_id.eq(org_id).and(dsl::tenant_id.eq(tenant_id)))
.into_boxed();
if let Some(user_id) = user_id {
query = query.filter(dsl::user_id.eq(user_id));
}
if let Some(merchant_id) = merchant_id {
query = query.filter(dsl::merchant_id.eq(merchant_id));
}
if let Some(profile_id) = profile_id {
query = query.filter(dsl::profile_id.eq(profile_id));
}
if let Some(version) = version {
query = query.filter(dsl::version.eq(version));
}
if let Some(limit) = limit {
query = query.limit(limit.into());
}
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
query.get_results_async(conn),
generics::db_metrics::DatabaseOperation::Filter,
)
.await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::NotFound => {
Err(report!(err)).change_context(errors::DatabaseError::NotFound)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
}
pub async fn list_user_roles_by_user_id_across_tenants(
conn: &PgPooledConn,
user_id: String,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
let mut query = <Self as HasTable>::table()
.filter(dsl::user_id.eq(user_id))
.into_boxed();
if let Some(limit) = limit {
query = query.limit(limit.into());
}
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
query.get_results_async(conn),
generics::db_metrics::DatabaseOperation::Filter,
)
.await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::NotFound => {
Err(report!(err)).change_context(errors::DatabaseError::NotFound)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/query/user_role.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2528
}
|
large_file_-4378477858245697240
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/query/generics.rs
</path>
<file>
use std::fmt::Debug;
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{
associations::HasTable,
debug_query,
dsl::{count_star, Find, IsNotNull, Limit},
helper_types::{Filter, IntoBoxed},
insertable::CanInsertInSingleQuery,
pg::{Pg, PgConnection},
query_builder::{
AsChangeset, AsQuery, DeleteStatement, InsertStatement, IntoUpdateTarget, QueryFragment,
QueryId, UpdateStatement,
},
query_dsl::{
methods::{BoxedDsl, FilterDsl, FindDsl, LimitDsl, OffsetDsl, OrderDsl, SelectDsl},
LoadQuery, RunQueryDsl,
},
result::Error as DieselError,
Expression, ExpressionMethods, Insertable, QueryDsl, QuerySource, Table,
};
use error_stack::{report, ResultExt};
use router_env::logger;
use crate::{errors, query::utils::GetPrimaryKey, PgPooledConn, StorageResult};
pub mod db_metrics {
#[derive(Debug)]
pub enum DatabaseOperation {
FindOne,
Filter,
Update,
Insert,
Delete,
DeleteWithResult,
UpdateWithResults,
UpdateOne,
Count,
}
#[inline]
pub async fn track_database_call<T, Fut, U>(future: Fut, operation: DatabaseOperation) -> U
where
Fut: std::future::Future<Output = U>,
{
let start = std::time::Instant::now();
let output = future.await;
let time_elapsed = start.elapsed();
let table_name = std::any::type_name::<T>().rsplit("::").nth(1);
let attributes = router_env::metric_attributes!(
("table", table_name.unwrap_or("undefined")),
("operation", format!("{:?}", operation))
);
crate::metrics::DATABASE_CALLS_COUNT.add(1, attributes);
crate::metrics::DATABASE_CALL_TIME.record(time_elapsed.as_secs_f64(), attributes);
output
}
}
use db_metrics::*;
pub async fn generic_insert<T, V, R>(conn: &PgPooledConn, values: V) -> StorageResult<R>
where
T: HasTable<Table = T> + Table + 'static + Debug,
V: Debug + Insertable<T>,
<T as QuerySource>::FromClause: QueryFragment<Pg> + Debug,
<V as Insertable<T>>::Values: CanInsertInSingleQuery<Pg> + QueryFragment<Pg> + 'static,
InsertStatement<T, <V as Insertable<T>>::Values>:
AsQuery + LoadQuery<'static, PgConnection, R> + Send,
R: Send + 'static,
{
let debug_values = format!("{values:?}");
let query = diesel::insert_into(<T as HasTable>::table()).values(values);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
match track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Insert)
.await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::DatabaseError(diesel::result::DatabaseErrorKind::UniqueViolation, _) => {
Err(report!(err)).change_context(errors::DatabaseError::UniqueViolation)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
.attach_printable_lazy(|| format!("Error while inserting {debug_values}"))
}
pub async fn generic_update<T, V, P>(
conn: &PgPooledConn,
predicate: P,
values: V,
) -> StorageResult<usize>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug,
Filter<T, P>: IntoUpdateTarget,
UpdateStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static,
{
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Update)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating {debug_values}"))
}
pub async fn generic_update_with_results<T, V, P, R>(
conn: &PgPooledConn,
predicate: P,
values: V,
) -> StorageResult<Vec<R>>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static,
Filter<T, P>: IntoUpdateTarget + 'static,
UpdateStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + Clone,
R: Send + 'static,
// For cloning query (UpdateStatement)
<Filter<T, P> as HasTable>::Table: Clone,
<Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone,
<V as AsChangeset>::Changeset: Clone,
<<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone,
{
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values);
match track_database_call::<T, _, _>(
query.to_owned().get_results_async(conn),
DatabaseOperation::UpdateWithResults,
)
.await
{
Ok(result) => {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
Ok(result)
}
Err(DieselError::QueryBuilderError(_)) => {
Err(report!(errors::DatabaseError::NoFieldsToUpdate))
.attach_printable_lazy(|| format!("Error while updating {debug_values}"))
}
Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))
.attach_printable_lazy(|| format!("Error while updating {debug_values}")),
Err(error) => Err(error)
.change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating {debug_values}")),
}
}
pub async fn generic_update_with_unique_predicate_get_result<T, V, P, R>(
conn: &PgPooledConn,
predicate: P,
values: V,
) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static,
Filter<T, P>: IntoUpdateTarget + 'static,
UpdateStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send,
R: Send + 'static,
// For cloning query (UpdateStatement)
<Filter<T, P> as HasTable>::Table: Clone,
<Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone,
<V as AsChangeset>::Changeset: Clone,
<<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone,
{
generic_update_with_results::<<T as HasTable>::Table, _, _, _>(conn, predicate, values)
.await
.map(|mut vec_r| {
if vec_r.is_empty() {
Err(errors::DatabaseError::NotFound)
} else if vec_r.len() != 1 {
Err(errors::DatabaseError::Others)
} else {
vec_r.pop().ok_or(errors::DatabaseError::Others)
}
.attach_printable("Maybe not queried using a unique key")
})?
}
pub async fn generic_update_by_id<T, V, Pk, R>(
conn: &PgPooledConn,
id: Pk,
values: V,
) -> StorageResult<R>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
V: AsChangeset<Target = <Find<T, Pk> as HasTable>::Table> + Debug,
Find<T, Pk>: IntoUpdateTarget + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
UpdateStatement<
<Find<T, Pk> as HasTable>::Table,
<Find<T, Pk> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
Find<T, Pk>: LimitDsl,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
R: Send + 'static,
Pk: Clone + Debug,
// For cloning query (UpdateStatement)
<Find<T, Pk> as HasTable>::Table: Clone,
<Find<T, Pk> as IntoUpdateTarget>::WhereClause: Clone,
<V as AsChangeset>::Changeset: Clone,
<<Find<T, Pk> as HasTable>::Table as QuerySource>::FromClause: Clone,
{
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().find(id.to_owned())).set(values);
match track_database_call::<T, _, _>(
query.to_owned().get_result_async(conn),
DatabaseOperation::UpdateOne,
)
.await
{
Ok(result) => {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
Ok(result)
}
Err(DieselError::QueryBuilderError(_)) => {
Err(report!(errors::DatabaseError::NoFieldsToUpdate))
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}"))
}
Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),
Err(error) => Err(error)
.change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),
}
}
pub async fn generic_delete<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<bool>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: IntoUpdateTarget,
DeleteStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
>: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static,
{
let query = diesel::delete(<T as HasTable>::table().filter(predicate));
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Delete)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting")
.and_then(|result| match result {
n if n > 0 => {
logger::debug!("{n} records deleted");
Ok(true)
}
0 => {
Err(report!(errors::DatabaseError::NotFound).attach_printable("No records deleted"))
}
_ => Ok(true), // n is usize, rustc requires this for exhaustive check
})
}
pub async fn generic_delete_one_with_result<T, P, R>(
conn: &PgPooledConn,
predicate: P,
) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: IntoUpdateTarget,
DeleteStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + Clone + 'static,
{
let query = diesel::delete(<T as HasTable>::table().filter(predicate));
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(
query.get_results_async(conn),
DatabaseOperation::DeleteWithResult,
)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting")
.and_then(|result| {
result.first().cloned().ok_or_else(|| {
report!(errors::DatabaseError::NotFound)
.attach_printable("Object to be deleted does not exist")
})
})
}
async fn generic_find_by_id_core<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
Pk: Clone + Debug,
R: Send + 'static,
{
let query = <T as HasTable>::table().find(id.to_owned());
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
match track_database_call::<T, _, _>(query.first_async(conn), DatabaseOperation::FindOne).await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::NotFound => {
Err(report!(err)).change_context(errors::DatabaseError::NotFound)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
.attach_printable_lazy(|| format!("Error finding record by primary key: {id:?}"))
}
pub async fn generic_find_by_id<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
Pk: Clone + Debug,
R: Send + 'static,
{
generic_find_by_id_core::<T, _, _>(conn, id).await
}
pub async fn generic_find_by_id_optional<T, Pk, R>(
conn: &PgPooledConn,
id: Pk,
) -> StorageResult<Option<R>>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
<T as HasTable>::Table: FindDsl<Pk>,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
Pk: Clone + Debug,
R: Send + 'static,
{
to_optional(generic_find_by_id_core::<T, _, _>(conn, id).await)
}
async fn generic_find_one_core<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + 'static,
{
let query = <T as HasTable>::table().filter(predicate);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::FindOne)
.await
.map_err(|err| match err {
DieselError::NotFound => report!(err).change_context(errors::DatabaseError::NotFound),
_ => report!(err).change_context(errors::DatabaseError::Others),
})
.attach_printable("Error finding record by predicate")
}
pub async fn generic_find_one<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + 'static,
{
generic_find_one_core::<T, _, _>(conn, predicate).await
}
pub async fn generic_find_one_optional<T, P, R>(
conn: &PgPooledConn,
predicate: P,
) -> StorageResult<Option<R>>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + 'static,
{
to_optional(generic_find_one_core::<T, _, _>(conn, predicate).await)
}
pub(super) async fn generic_filter<T, P, O, R>(
conn: &PgPooledConn,
predicate: P,
limit: Option<i64>,
offset: Option<i64>,
order: Option<O>,
) -> StorageResult<Vec<R>>
where
T: HasTable<Table = T> + Table + BoxedDsl<'static, Pg> + GetPrimaryKey + 'static,
IntoBoxed<'static, T, Pg>: FilterDsl<P, Output = IntoBoxed<'static, T, Pg>>
+ FilterDsl<IsNotNull<T::PK>, Output = IntoBoxed<'static, T, Pg>>
+ LimitDsl<Output = IntoBoxed<'static, T, Pg>>
+ OffsetDsl<Output = IntoBoxed<'static, T, Pg>>
+ OrderDsl<O, Output = IntoBoxed<'static, T, Pg>>
+ LoadQuery<'static, PgConnection, R>
+ QueryFragment<Pg>
+ Send,
O: Expression,
R: Send + 'static,
{
let mut query = T::table().into_boxed();
query = query
.filter(predicate)
.filter(T::table().get_primary_key().is_not_null());
if let Some(limit) = limit {
query = query.limit(limit);
}
if let Some(offset) = offset {
query = query.offset(offset);
}
if let Some(order) = order {
query = query.order(order);
}
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by predicate")
}
pub async fn generic_count<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<usize>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + SelectDsl<count_star> + 'static,
Filter<T, P>: SelectDsl<count_star>,
diesel::dsl::Select<Filter<T, P>, count_star>:
LoadQuery<'static, PgConnection, i64> + QueryFragment<Pg> + Send + 'static,
{
let query = <T as HasTable>::table()
.filter(predicate)
.select(count_star());
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
let count_i64: i64 =
track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Count)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error counting records by predicate")?;
let count_usize = usize::try_from(count_i64).map_err(|_| {
report!(errors::DatabaseError::Others).attach_printable("Count value does not fit in usize")
})?;
Ok(count_usize)
}
fn to_optional<T>(arg: StorageResult<T>) -> StorageResult<Option<T>> {
match arg {
Ok(value) => Ok(Some(value)),
Err(err) => match err.current_context() {
errors::DatabaseError::NotFound => Ok(None),
_ => Err(err),
},
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/query/generics.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4733
}
|
large_file_-3525267590793645211
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: diesel_models
File: crates/diesel_models/src/query/customers.rs
</path>
<file>
use common_utils::id_type;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
#[cfg(feature = "v1")]
use crate::schema::customers::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::customers::dsl;
use crate::{
customers::{Customer, CustomerNew, CustomerUpdateInternal},
errors, PgPooledConn, StorageResult,
};
impl CustomerNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Customer> {
generics::generic_insert(conn, self).await
}
}
pub struct CustomerListConstraints {
pub limit: i64,
pub offset: Option<i64>,
pub customer_id: Option<id_type::CustomerId>,
pub time_range: Option<common_utils::types::TimeRange>,
}
impl Customer {
#[cfg(feature = "v2")]
pub async fn update_by_id(
conn: &PgPooledConn,
id: id_type::GlobalCustomerId,
customer: CustomerUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
id.clone(),
customer,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id).await
}
_ => Err(error),
},
result => result,
}
}
#[cfg(feature = "v2")]
pub async fn find_by_global_id(
conn: &PgPooledConn,
id: &id_type::GlobalCustomerId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await
}
#[cfg(feature = "v1")]
pub async fn get_customer_count_by_merchant_id_and_constraints(
conn: &PgPooledConn,
merchant_id: &id_type::MerchantId,
customer_list_constraints: CustomerListConstraints,
) -> StorageResult<usize> {
if let Some(customer_id) = customer_list_constraints.customer_id {
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::customer_id.eq(customer_id));
generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await
} else if let Some(time_range) = customer_list_constraints.time_range {
let start_time = time_range.start_time;
let end_time = time_range
.end_time
.unwrap_or_else(common_utils::date_time::now);
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::created_at.between(start_time, end_time));
generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await
} else {
generics::generic_count::<<Self as HasTable>::Table, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
)
.await
}
}
#[cfg(feature = "v2")]
pub async fn get_customer_count_by_merchant_id_and_constraints(
conn: &PgPooledConn,
merchant_id: &id_type::MerchantId,
customer_list_constraints: CustomerListConstraints,
) -> StorageResult<usize> {
if let Some(customer_id) = customer_list_constraints.customer_id {
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::merchant_reference_id.eq(customer_id));
generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await
} else if let Some(time_range) = customer_list_constraints.time_range {
let start_time = time_range.start_time;
let end_time = time_range
.end_time
.unwrap_or_else(common_utils::date_time::now);
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::created_at.between(start_time, end_time));
generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await
} else {
generics::generic_count::<<Self as HasTable>::Table, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
)
.await
}
}
#[cfg(feature = "v1")]
pub async fn list_customers_by_merchant_id_and_constraints(
conn: &PgPooledConn,
merchant_id: &id_type::MerchantId,
constraints: CustomerListConstraints,
) -> StorageResult<Vec<Self>> {
if let Some(customer_id) = constraints.customer_id {
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::customer_id.eq(customer_id));
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
} else if let Some(time_range) = constraints.time_range {
let start_time = time_range.start_time;
let end_time = time_range
.end_time
.unwrap_or_else(common_utils::date_time::now);
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::created_at.between(start_time, end_time));
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
} else {
let predicate = dsl::merchant_id.eq(merchant_id.clone());
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
}
}
#[cfg(feature = "v2")]
pub async fn list_customers_by_merchant_id_and_constraints(
conn: &PgPooledConn,
merchant_id: &id_type::MerchantId,
constraints: CustomerListConstraints,
) -> StorageResult<Vec<Self>> {
if let Some(customer_id) = constraints.customer_id {
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::merchant_reference_id.eq(customer_id));
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
} else if let Some(time_range) = constraints.time_range {
let start_time = time_range.start_time;
let end_time = time_range
.end_time
.unwrap_or_else(common_utils::date_time::now);
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::created_at.between(start_time, end_time));
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
} else {
let predicate = dsl::merchant_id.eq(merchant_id.clone());
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
}
}
#[cfg(feature = "v2")]
pub async fn find_optional_by_merchant_id_merchant_reference_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::merchant_reference_id.eq(customer_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_optional_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id.to_owned(), merchant_id.to_owned()),
)
.await
}
#[cfg(feature = "v1")]
pub async fn update_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: CustomerUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
(customer_id.clone(), merchant_id.clone()),
customer,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id, merchant_id),
)
.await
}
_ => Err(error),
},
result => result,
}
}
#[cfg(feature = "v1")]
pub async fn delete_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.await
}
#[cfg(feature = "v2")]
pub async fn find_by_merchant_reference_id_merchant_id(
conn: &PgPooledConn,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id.to_owned(), merchant_id.to_owned()),
)
.await
}
}
</file>
|
{
"crate": "diesel_models",
"file": "crates/diesel_models/src/query/customers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2432
}
|
large_file_-1466912476996706785
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: scheduler
File: crates/scheduler/src/consumer.rs
</path>
<file>
// TODO: Figure out what to log
use std::{
sync::{self, atomic},
time as std_time,
};
pub mod types;
pub mod workflows;
use common_utils::{errors::CustomResult, id_type, signals::get_allowed_signals};
use diesel_models::enums;
pub use diesel_models::{self, process_tracker as storage};
use error_stack::ResultExt;
use futures::future;
use redis_interface::{RedisConnectionPool, RedisEntryId};
use router_env::{
instrument,
tracing::{self, Instrument},
};
use time::PrimitiveDateTime;
use tokio::sync::mpsc;
use uuid::Uuid;
use super::env::logger;
pub use super::workflows::ProcessTrackerWorkflow;
use crate::{
configs::settings::SchedulerSettings, db::process_tracker::ProcessTrackerInterface, errors,
metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface, SchedulerSessionState,
};
// Valid consumer business statuses
pub fn valid_business_statuses() -> Vec<&'static str> {
vec![storage::business_status::PENDING]
}
#[instrument(skip_all)]
pub async fn start_consumer<T: SchedulerAppState + 'static, U: SchedulerSessionState + 'static, F>(
state: &T,
settings: sync::Arc<SchedulerSettings>,
workflow_selector: impl workflows::ProcessTrackerWorkflows<U> + 'static + Copy + std::fmt::Debug,
(tx, mut rx): (mpsc::Sender<()>, mpsc::Receiver<()>),
app_state_to_session_state: F,
) -> CustomResult<(), errors::ProcessTrackerError>
where
F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>,
{
use std::time::Duration;
use rand::distributions::{Distribution, Uniform};
let mut rng = rand::thread_rng();
// TODO: this can be removed once rand-0.9 is released
// reference - https://github.com/rust-random/rand/issues/1326#issuecomment-1635331942
#[allow(unknown_lints)]
#[allow(clippy::unnecessary_fallible_conversions)]
let timeout = Uniform::try_from(0..=settings.loop_interval)
.change_context(errors::ProcessTrackerError::ConfigurationError)?;
tokio::time::sleep(Duration::from_millis(timeout.sample(&mut rng))).await;
let mut interval = tokio::time::interval(Duration::from_millis(settings.loop_interval));
let mut shutdown_interval =
tokio::time::interval(Duration::from_millis(settings.graceful_shutdown_interval));
let consumer_operation_counter = sync::Arc::new(atomic::AtomicU64::new(0));
let signal = get_allowed_signals()
.map_err(|error| {
logger::error!(?error, "Signal Handler Error");
errors::ProcessTrackerError::ConfigurationError
})
.attach_printable("Failed while creating a signals handler")?;
let handle = signal.handle();
let task_handle =
tokio::spawn(common_utils::signals::signal_handler(signal, tx).in_current_span());
'consumer: loop {
match rx.try_recv() {
Err(mpsc::error::TryRecvError::Empty) => {
interval.tick().await;
// A guard from env to disable the consumer
if settings.consumer.disabled {
continue;
}
consumer_operation_counter.fetch_add(1, atomic::Ordering::SeqCst);
let start_time = std_time::Instant::now();
let tenants = state.get_tenants();
for tenant in tenants {
let session_state = app_state_to_session_state(state, &tenant)?;
pt_utils::consumer_operation_handler(
session_state.clone(),
settings.clone(),
|error| {
logger::error!(?error, "Failed to perform consumer operation");
},
workflow_selector,
)
.await;
}
let end_time = std_time::Instant::now();
let duration = end_time.saturating_duration_since(start_time).as_secs_f64();
logger::debug!("Time taken to execute consumer_operation: {}s", duration);
let current_count =
consumer_operation_counter.fetch_sub(1, atomic::Ordering::SeqCst);
logger::info!("Current tasks being executed: {}", current_count);
}
Ok(()) | Err(mpsc::error::TryRecvError::Disconnected) => {
logger::debug!("Awaiting shutdown!");
rx.close();
loop {
shutdown_interval.tick().await;
let active_tasks = consumer_operation_counter.load(atomic::Ordering::Acquire);
logger::info!("Active tasks: {active_tasks}");
match active_tasks {
0 => {
logger::info!("Terminating consumer");
break 'consumer;
}
_ => continue,
}
}
}
}
}
handle.close();
task_handle
.await
.change_context(errors::ProcessTrackerError::UnexpectedFlow)?;
Ok(())
}
#[instrument(skip_all)]
pub async fn consumer_operations<T: SchedulerSessionState + 'static>(
state: &T,
settings: &SchedulerSettings,
workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + Copy + std::fmt::Debug,
) -> CustomResult<(), errors::ProcessTrackerError> {
let stream_name = settings.stream.clone();
let group_name = settings.consumer.consumer_group.clone();
let consumer_name = format!("consumer_{}", Uuid::new_v4());
let _group_created = &mut state
.get_db()
.consumer_group_create(&stream_name, &group_name, &RedisEntryId::AfterLastID)
.await;
let mut tasks = state
.get_db()
.as_scheduler()
.fetch_consumer_tasks(&stream_name, &group_name, &consumer_name)
.await?;
if !tasks.is_empty() {
logger::info!("{} picked {} tasks", consumer_name, tasks.len());
}
let mut handler = vec![];
for task in tasks.iter_mut() {
let pickup_time = common_utils::date_time::now();
pt_utils::add_histogram_metrics(&pickup_time, task, &stream_name);
metrics::TASK_CONSUMED.add(1, &[]);
handler.push(tokio::task::spawn(start_workflow(
state.clone(),
task.clone(),
pickup_time,
workflow_selector,
)))
}
future::join_all(handler).await;
Ok(())
}
#[instrument(skip(db, redis_conn))]
pub async fn fetch_consumer_tasks(
db: &dyn ProcessTrackerInterface,
redis_conn: &RedisConnectionPool,
stream_name: &str,
group_name: &str,
consumer_name: &str,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::ProcessTrackerError> {
let batches = pt_utils::get_batches(redis_conn, stream_name, group_name, consumer_name).await?;
// Returning early to avoid execution of database queries when `batches` is empty
if batches.is_empty() {
return Ok(Vec::new());
}
let mut tasks = batches.into_iter().fold(Vec::new(), |mut acc, batch| {
acc.extend_from_slice(
batch
.trackers
.into_iter()
.filter(|task| task.is_valid_business_status(&valid_business_statuses()))
.collect::<Vec<_>>()
.as_slice(),
);
acc
});
let task_ids = tasks
.iter()
.map(|task| task.id.to_owned())
.collect::<Vec<_>>();
db.process_tracker_update_process_status_by_ids(
task_ids,
storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::ProcessStarted,
business_status: None,
},
)
.await
.change_context(errors::ProcessTrackerError::ProcessFetchingFailed)?;
tasks
.iter_mut()
.for_each(|x| x.status = enums::ProcessTrackerStatus::ProcessStarted);
Ok(tasks)
}
// Accept flow_options if required
#[instrument(skip(state), fields(workflow_id))]
pub async fn start_workflow<T>(
state: T,
process: storage::ProcessTracker,
_pickup_time: PrimitiveDateTime,
workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + std::fmt::Debug,
) -> CustomResult<(), errors::ProcessTrackerError>
where
T: SchedulerSessionState,
{
tracing::Span::current().record("workflow_id", Uuid::new_v4().to_string());
logger::info!(pt.name=?process.name, pt.id=%process.id);
let res = workflow_selector
.trigger_workflow(&state.clone(), process.clone())
.await
.inspect_err(|error| {
logger::error!(?error, "Failed to trigger workflow");
});
metrics::TASK_PROCESSED.add(1, &[]);
res
}
#[instrument(skip_all)]
pub async fn consumer_error_handler(
state: &(dyn SchedulerInterface + 'static),
process: storage::ProcessTracker,
error: errors::ProcessTrackerError,
) -> CustomResult<(), errors::ProcessTrackerError> {
logger::error!(pt.name=?process.name, pt.id=%process.id, ?error, "Failed to execute workflow");
state
.process_tracker_update_process_status_by_ids(
vec![process.id],
storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Finish,
business_status: Some(String::from(storage::business_status::GLOBAL_ERROR)),
},
)
.await
.change_context(errors::ProcessTrackerError::ProcessUpdateFailed)?;
Ok(())
}
pub async fn create_task(
db: &dyn ProcessTrackerInterface,
process_tracker_entry: storage::ProcessTrackerNew,
) -> CustomResult<(), storage_impl::errors::StorageError> {
db.insert_process(process_tracker_entry).await?;
Ok(())
}
</file>
|
{
"crate": "scheduler",
"file": "crates/scheduler/src/consumer.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2114
}
|
large_file_344156867231708081
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: scheduler
File: crates/scheduler/src/utils.rs
</path>
<file>
use std::sync;
use common_utils::errors::CustomResult;
use diesel_models::enums::{self, ProcessTrackerStatus};
pub use diesel_models::process_tracker as storage;
use error_stack::{report, ResultExt};
use redis_interface::{RedisConnectionPool, RedisEntryId};
use router_env::{instrument, tracing};
use uuid::Uuid;
use super::{
consumer::{self, types::process_data, workflows},
env::logger,
};
use crate::{
configs::settings::SchedulerSettings, consumer::types::ProcessTrackerBatch, errors,
flow::SchedulerFlow, metrics, SchedulerInterface, SchedulerSessionState,
};
pub async fn divide_and_append_tasks<T>(
state: &T,
flow: SchedulerFlow,
tasks: Vec<storage::ProcessTracker>,
settings: &SchedulerSettings,
) -> CustomResult<(), errors::ProcessTrackerError>
where
T: SchedulerInterface + Send + Sync + ?Sized,
{
let batches = divide(tasks, settings);
// Safety: Assuming we won't deal with more than `u64::MAX` batches at once
#[allow(clippy::as_conversions)]
metrics::BATCHES_CREATED.add(batches.len() as u64, &[]); // Metrics
for batch in batches {
let result = update_status_and_append(state, flow, batch).await;
match result {
Ok(_) => (),
Err(error) => logger::error!(?error),
}
}
Ok(())
}
pub async fn update_status_and_append<T>(
state: &T,
flow: SchedulerFlow,
pt_batch: ProcessTrackerBatch,
) -> CustomResult<(), errors::ProcessTrackerError>
where
T: SchedulerInterface + Send + Sync + ?Sized,
{
let process_ids: Vec<String> = pt_batch
.trackers
.iter()
.map(|process| process.id.to_owned())
.collect();
match flow {
SchedulerFlow::Producer => state
.process_tracker_update_process_status_by_ids(
process_ids,
storage::ProcessTrackerUpdate::StatusUpdate {
status: ProcessTrackerStatus::Processing,
business_status: None,
},
)
.await
.map_or_else(
|error| {
logger::error!(?error, "Error while updating process status");
Err(error.change_context(errors::ProcessTrackerError::ProcessUpdateFailed))
},
|count| {
logger::debug!("Updated status of {count} processes");
Ok(())
},
),
SchedulerFlow::Cleaner => {
let res = state
.reinitialize_limbo_processes(process_ids, common_utils::date_time::now())
.await;
match res {
Ok(count) => {
logger::debug!("Reinitialized {count} processes");
Ok(())
}
Err(error) => {
logger::error!(?error, "Error while reinitializing processes");
Err(error.change_context(errors::ProcessTrackerError::ProcessUpdateFailed))
}
}
}
_ => {
let error = format!("Unexpected scheduler flow {flow:?}");
logger::error!(%error);
Err(report!(errors::ProcessTrackerError::UnexpectedFlow).attach_printable(error))
}
}?;
let field_value_pairs = pt_batch.to_redis_field_value_pairs()?;
match state
.stream_append_entry(
&pt_batch.stream_name,
&RedisEntryId::AutoGeneratedID,
field_value_pairs,
)
.await
.change_context(errors::ProcessTrackerError::BatchInsertionFailed)
{
Ok(x) => Ok(x),
Err(mut err) => {
let update_res = state
.process_tracker_update_process_status_by_ids(
pt_batch
.trackers
.iter()
.map(|process| process.id.clone())
.collect(),
storage::ProcessTrackerUpdate::StatusUpdate {
status: ProcessTrackerStatus::Processing,
business_status: None,
},
)
.await
.map_or_else(
|error| {
logger::error!(?error, "Error while updating process status");
Err(error.change_context(errors::ProcessTrackerError::ProcessUpdateFailed))
},
|count| {
logger::debug!("Updated status of {count} processes");
Ok(())
},
);
match update_res {
Ok(_) => (),
Err(inner_err) => {
err.extend_one(inner_err);
}
};
Err(err)
}
}
}
pub fn divide(
tasks: Vec<storage::ProcessTracker>,
conf: &SchedulerSettings,
) -> Vec<ProcessTrackerBatch> {
let now = common_utils::date_time::now();
let batch_size = conf.producer.batch_size;
divide_into_batches(batch_size, tasks, now, conf)
}
pub fn divide_into_batches(
batch_size: usize,
tasks: Vec<storage::ProcessTracker>,
batch_creation_time: time::PrimitiveDateTime,
conf: &SchedulerSettings,
) -> Vec<ProcessTrackerBatch> {
let batch_id = Uuid::new_v4().to_string();
tasks
.chunks(batch_size)
.fold(Vec::new(), |mut batches, item| {
let batch = ProcessTrackerBatch {
id: batch_id.clone(),
group_name: conf.consumer.consumer_group.clone(),
stream_name: conf.stream.clone(),
connection_name: String::new(),
created_time: batch_creation_time,
rule: String::new(), // is it required?
trackers: item.to_vec(),
};
batches.push(batch);
batches
})
}
pub async fn get_batches(
conn: &RedisConnectionPool,
stream_name: &str,
group_name: &str,
consumer_name: &str,
) -> CustomResult<Vec<ProcessTrackerBatch>, errors::ProcessTrackerError> {
let response = match conn
.stream_read_with_options(
stream_name,
RedisEntryId::UndeliveredEntryID,
// Update logic for collecting to Vec and flattening, if count > 1 is provided
Some(1),
None,
Some((group_name, consumer_name)),
)
.await
{
Ok(response) => response,
Err(error) => {
if let redis_interface::errors::RedisError::StreamEmptyOrNotAvailable =
error.current_context()
{
logger::debug!("No batches processed as stream is empty");
return Ok(Vec::new());
} else {
return Err(error.change_context(errors::ProcessTrackerError::BatchNotFound));
}
}
};
metrics::BATCHES_CONSUMED.add(1, &[]);
let (batches, entry_ids): (Vec<Vec<ProcessTrackerBatch>>, Vec<Vec<String>>) = response.into_values().map(|entries| {
entries.into_iter().try_fold(
(Vec::new(), Vec::new()),
|(mut batches, mut entry_ids), entry| {
// Redis entry ID
entry_ids.push(entry.0);
// Value HashMap
batches.push(ProcessTrackerBatch::from_redis_stream_entry(entry.1)?);
Ok((batches, entry_ids))
},
)
}).collect::<CustomResult<Vec<(Vec<ProcessTrackerBatch>, Vec<String>)>, errors::ProcessTrackerError>>()?
.into_iter()
.unzip();
// Flattening the Vec's since the count provided above is 1. This needs to be updated if a
// count greater than 1 is provided.
let batches = batches.into_iter().flatten().collect::<Vec<_>>();
let entry_ids = entry_ids.into_iter().flatten().collect::<Vec<_>>();
conn.stream_acknowledge_entries(&stream_name.into(), group_name, entry_ids.clone())
.await
.map_err(|error| {
logger::error!(?error, "Error acknowledging batch in stream");
error.change_context(errors::ProcessTrackerError::BatchUpdateFailed)
})?;
conn.stream_delete_entries(&stream_name.into(), entry_ids.clone())
.await
.map_err(|error| {
logger::error!(?error, "Error deleting batch from stream");
error.change_context(errors::ProcessTrackerError::BatchDeleteFailed)
})?;
Ok(batches)
}
pub fn get_process_tracker_id<'a>(
runner: storage::ProcessTrackerRunner,
task_name: &'a str,
txn_id: &'a str,
merchant_id: &'a common_utils::id_type::MerchantId,
) -> String {
format!(
"{runner}_{task_name}_{txn_id}_{}",
merchant_id.get_string_repr()
)
}
pub fn get_process_tracker_id_for_dispute_list<'a>(
runner: storage::ProcessTrackerRunner,
merchant_connector_account_id: &'a common_utils::id_type::MerchantConnectorAccountId,
created_from: time::PrimitiveDateTime,
merchant_id: &'a common_utils::id_type::MerchantId,
) -> String {
format!(
"{runner}_{:04}{}{:02}{:02}_{}_{}",
created_from.year(),
created_from.month(),
created_from.day(),
created_from.hour(),
merchant_connector_account_id.get_string_repr(),
merchant_id.get_string_repr()
)
}
pub fn get_time_from_delta(delta: Option<i32>) -> Option<time::PrimitiveDateTime> {
delta.map(|t| common_utils::date_time::now().saturating_add(time::Duration::seconds(t.into())))
}
#[instrument(skip_all)]
pub async fn consumer_operation_handler<E, T>(
state: T,
settings: sync::Arc<SchedulerSettings>,
error_handler_fun: E,
workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + Copy + std::fmt::Debug,
) where
// Error handler function
E: FnOnce(error_stack::Report<errors::ProcessTrackerError>),
T: SchedulerSessionState + Send + Sync + 'static,
{
match consumer::consumer_operations(&state, &settings, workflow_selector).await {
Ok(_) => (),
Err(err) => error_handler_fun(err),
}
}
pub fn add_histogram_metrics(
pickup_time: &time::PrimitiveDateTime,
task: &mut storage::ProcessTracker,
stream_name: &str,
) {
#[warn(clippy::option_map_unit_fn)]
if let Some((schedule_time, runner)) = task.schedule_time.as_ref().zip(task.runner.as_ref()) {
let pickup_schedule_delta = (*pickup_time - *schedule_time).as_seconds_f64();
logger::info!("Time delta for scheduled tasks: {pickup_schedule_delta} seconds");
let runner_name = runner.clone();
metrics::CONSUMER_OPS.record(
pickup_schedule_delta,
router_env::metric_attributes!((stream_name.to_owned(), runner_name)),
);
};
}
pub fn get_schedule_time(
mapping: process_data::ConnectorPTMapping,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Option<i32> {
let mapping = match mapping.custom_merchant_mapping.get(merchant_id) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
// For first try, get the `start_after` time
if retry_count == 0 {
Some(mapping.start_after)
} else {
get_delay(retry_count, &mapping.frequencies)
}
}
pub fn get_pm_schedule_time(
mapping: process_data::PaymentMethodsPTMapping,
pm: enums::PaymentMethod,
retry_count: i32,
) -> Option<i32> {
let mapping = match mapping.custom_pm_mapping.get(&pm) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
if retry_count == 0 {
Some(mapping.start_after)
} else {
get_delay(retry_count, &mapping.frequencies)
}
}
pub fn get_outgoing_webhook_retry_schedule_time(
mapping: process_data::OutgoingWebhookRetryProcessTrackerMapping,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Option<i32> {
let retry_mapping = match mapping.custom_merchant_mapping.get(merchant_id) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
// For first try, get the `start_after` time
if retry_count == 0 {
Some(retry_mapping.start_after)
} else {
get_delay(retry_count, &retry_mapping.frequencies)
}
}
pub fn get_pcr_payments_retry_schedule_time(
mapping: process_data::RevenueRecoveryPaymentProcessTrackerMapping,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Option<i32> {
let mapping = match mapping.custom_merchant_mapping.get(merchant_id) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
// TODO: check if the current scheduled time is not more than the configured timerange
// For first try, get the `start_after` time
if retry_count == 0 {
Some(mapping.start_after)
} else {
get_delay(retry_count, &mapping.frequencies)
}
}
pub fn get_subscription_invoice_sync_retry_schedule_time(
mapping: process_data::SubscriptionInvoiceSyncPTMapping,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Option<i32> {
let mapping = match mapping.custom_merchant_mapping.get(merchant_id) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
if retry_count == 0 {
Some(mapping.start_after)
} else {
get_delay(retry_count, &mapping.frequencies)
}
}
/// Get the delay based on the retry count
pub fn get_delay<'a>(
retry_count: i32,
frequencies: impl IntoIterator<Item = &'a (i32, i32)>,
) -> Option<i32> {
// Preferably, fix this by using unsigned ints
if retry_count <= 0 {
return None;
}
let mut cumulative_count = 0;
for &(frequency, count) in frequencies.into_iter() {
cumulative_count += count;
if cumulative_count >= retry_count {
return Some(frequency);
}
}
None
}
pub(crate) async fn lock_acquire_release<T, F, Fut>(
state: &T,
settings: &SchedulerSettings,
callback: F,
) -> CustomResult<(), errors::ProcessTrackerError>
where
F: Fn() -> Fut,
T: SchedulerInterface + Send + Sync + ?Sized,
Fut: futures::Future<Output = CustomResult<(), errors::ProcessTrackerError>>,
{
let tag = "PRODUCER_LOCK";
let lock_key = &settings.producer.lock_key;
let lock_val = "LOCKED";
let ttl = settings.producer.lock_ttl;
if state
.acquire_pt_lock(tag, lock_key, lock_val, ttl)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))?
{
let result = callback().await;
state
.release_pt_lock(tag, lock_key)
.await
.map_err(errors::ProcessTrackerError::ERedisError)?;
result
} else {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_delay() {
let frequency_count = vec![(300, 10), (600, 5), (1800, 3), (3600, 2)];
let retry_counts_and_expected_delays = [
(-4, None),
(-2, None),
(0, None),
(4, Some(300)),
(7, Some(300)),
(10, Some(300)),
(12, Some(600)),
(16, Some(1800)),
(18, Some(1800)),
(20, Some(3600)),
(24, None),
(30, None),
];
for (retry_count, expected_delay) in retry_counts_and_expected_delays {
let delay = get_delay(retry_count, &frequency_count);
assert_eq!(
delay, expected_delay,
"Delay and expected delay differ for `retry_count` = {retry_count}"
);
}
}
}
</file>
|
{
"crate": "scheduler",
"file": "crates/scheduler/src/utils.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3550
}
|
large_file_8062136796677729849
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: scheduler
File: crates/scheduler/src/db/process_tracker.rs
</path>
<file>
use common_utils::errors::CustomResult;
pub use diesel_models as storage;
use diesel_models::enums as storage_enums;
use error_stack::{report, ResultExt};
use storage_impl::{connection, errors, mock_db::MockDb};
use time::PrimitiveDateTime;
use crate::{metrics, scheduler::Store};
#[async_trait::async_trait]
pub trait ProcessTrackerInterface: Send + Sync + 'static {
async fn reinitialize_limbo_processes(
&self,
ids: Vec<String>,
schedule_time: PrimitiveDateTime,
) -> CustomResult<usize, errors::StorageError>;
async fn find_process_by_id(
&self,
id: &str,
) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError>;
async fn update_process(
&self,
this: storage::ProcessTracker,
process: storage::ProcessTrackerUpdate,
) -> CustomResult<storage::ProcessTracker, errors::StorageError>;
async fn process_tracker_update_process_status_by_ids(
&self,
task_ids: Vec<String>,
task_update: storage::ProcessTrackerUpdate,
) -> CustomResult<usize, errors::StorageError>;
async fn insert_process(
&self,
new: storage::ProcessTrackerNew,
) -> CustomResult<storage::ProcessTracker, errors::StorageError>;
async fn reset_process(
&self,
this: storage::ProcessTracker,
schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError>;
async fn retry_process(
&self,
this: storage::ProcessTracker,
schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError>;
async fn finish_process_with_business_status(
&self,
this: storage::ProcessTracker,
business_status: &'static str,
) -> CustomResult<(), errors::StorageError>;
async fn find_processes_by_time_status(
&self,
time_lower_limit: PrimitiveDateTime,
time_upper_limit: PrimitiveDateTime,
status: storage_enums::ProcessTrackerStatus,
limit: Option<i64>,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError>;
}
#[async_trait::async_trait]
impl ProcessTrackerInterface for Store {
async fn find_process_by_id(
&self,
id: &str,
) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::ProcessTracker::find_process_by_id(&conn, id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn reinitialize_limbo_processes(
&self,
ids: Vec<String>,
schedule_time: PrimitiveDateTime,
) -> CustomResult<usize, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::ProcessTracker::reinitialize_limbo_processes(&conn, ids, schedule_time)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_processes_by_time_status(
&self,
time_lower_limit: PrimitiveDateTime,
time_upper_limit: PrimitiveDateTime,
status: storage_enums::ProcessTrackerStatus,
limit: Option<i64>,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::ProcessTracker::find_processes_by_time_status(
&conn,
time_lower_limit,
time_upper_limit,
status,
limit,
common_types::consts::API_VERSION,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn insert_process(
&self,
new: storage::ProcessTrackerNew,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
new.insert_process(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn update_process(
&self,
this: storage::ProcessTracker,
process: storage::ProcessTrackerUpdate,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
this.update(&conn, process)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn reset_process(
&self,
this: storage::ProcessTracker,
schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
self.update_process(
this,
storage::ProcessTrackerUpdate::StatusRetryUpdate {
status: storage_enums::ProcessTrackerStatus::New,
retry_count: 0,
schedule_time,
},
)
.await?;
Ok(())
}
async fn retry_process(
&self,
this: storage::ProcessTracker,
schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
metrics::TASK_RETRIED.add(1, &[]);
let retry_count = this.retry_count + 1;
self.update_process(
this,
storage::ProcessTrackerUpdate::StatusRetryUpdate {
status: storage_enums::ProcessTrackerStatus::Pending,
retry_count,
schedule_time,
},
)
.await?;
Ok(())
}
async fn finish_process_with_business_status(
&self,
this: storage::ProcessTracker,
business_status: &'static str,
) -> CustomResult<(), errors::StorageError> {
self.update_process(
this,
storage::ProcessTrackerUpdate::StatusUpdate {
status: storage_enums::ProcessTrackerStatus::Finish,
business_status: Some(String::from(business_status)),
},
)
.await
.attach_printable("Failed to update business status of process")?;
metrics::TASK_FINISHED.add(1, &[]);
Ok(())
}
async fn process_tracker_update_process_status_by_ids(
&self,
task_ids: Vec<String>,
task_update: storage::ProcessTrackerUpdate,
) -> CustomResult<usize, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::ProcessTracker::update_process_status_by_ids(&conn, task_ids, task_update)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl ProcessTrackerInterface for MockDb {
async fn find_process_by_id(
&self,
id: &str,
) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError> {
let optional = self
.processes
.lock()
.await
.iter()
.find(|process| process.id == id)
.cloned();
Ok(optional)
}
async fn reinitialize_limbo_processes(
&self,
_ids: Vec<String>,
_schedule_time: PrimitiveDateTime,
) -> CustomResult<usize, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn find_processes_by_time_status(
&self,
_time_lower_limit: PrimitiveDateTime,
_time_upper_limit: PrimitiveDateTime,
_status: storage_enums::ProcessTrackerStatus,
_limit: Option<i64>,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn insert_process(
&self,
new: storage::ProcessTrackerNew,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
let mut processes = self.processes.lock().await;
let process = storage::ProcessTracker {
id: new.id,
name: new.name,
tag: new.tag,
runner: new.runner,
retry_count: new.retry_count,
schedule_time: new.schedule_time,
rule: new.rule,
tracking_data: new.tracking_data,
business_status: new.business_status,
status: new.status,
event: new.event,
created_at: new.created_at,
updated_at: new.updated_at,
version: new.version,
};
processes.push(process.clone());
Ok(process)
}
async fn update_process(
&self,
_this: storage::ProcessTracker,
_process: storage::ProcessTrackerUpdate,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn reset_process(
&self,
_this: storage::ProcessTracker,
_schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn retry_process(
&self,
_this: storage::ProcessTracker,
_schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn finish_process_with_business_status(
&self,
_this: storage::ProcessTracker,
_business_status: &'static str,
) -> CustomResult<(), errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn process_tracker_update_process_status_by_ids(
&self,
_task_ids: Vec<String>,
_task_update: storage::ProcessTrackerUpdate,
) -> CustomResult<usize, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
}
</file>
|
{
"crate": "scheduler",
"file": "crates/scheduler/src/db/process_tracker.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2177
}
|
large_file_-8386760533323133085
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: smithy-generator
File: crates/smithy-generator/build.rs
</path>
<file>
// crates/smithy-generator/build.rs
use std::{fs, path::Path};
use regex::Regex;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("cargo:rerun-if-changed=../");
run_build()
}
fn run_build() -> Result<(), Box<dyn std::error::Error>> {
let workspace_root = get_workspace_root()?;
let mut smithy_models = Vec::new();
// Scan all crates in the workspace for SmithyModel derives
let crates_dir = workspace_root.join("crates");
if let Ok(entries) = fs::read_dir(&crates_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
let crate_path = entry.path();
let crate_name = match crate_path.file_name() {
Some(name) => name.to_string_lossy(),
None => {
println!(
"cargo:warning=Skipping crate with invalid path: {}",
crate_path.display()
);
continue;
}
};
// Skip the smithy crate itself to avoid self-dependency
if crate_name == "smithy"
|| crate_name == "smithy-core"
|| crate_name == "smithy-generator"
{
continue;
}
if let Err(e) =
scan_crate_for_smithy_models(&crate_path, &crate_name, &mut smithy_models)
{
println!("cargo:warning=Failed to scan crate {}: {}", crate_name, e);
}
}
}
}
// Generate the registry file
generate_model_registry(&smithy_models)?;
Ok(())
}
fn get_workspace_root() -> Result<std::path::PathBuf, Box<dyn std::error::Error>> {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
.map_err(|_| "CARGO_MANIFEST_DIR environment variable not set")?;
let manifest_path = Path::new(&manifest_dir);
let parent1 = manifest_path
.parent()
.ok_or("Cannot get parent directory of CARGO_MANIFEST_DIR")?;
let workspace_root = parent1
.parent()
.ok_or("Cannot get workspace root directory")?;
Ok(workspace_root.to_path_buf())
}
fn scan_crate_for_smithy_models(
crate_path: &Path,
crate_name: &str,
models: &mut Vec<SmithyModelInfo>,
) -> Result<(), Box<dyn std::error::Error>> {
let src_path = crate_path.join("src");
if !src_path.exists() {
return Ok(());
}
scan_directory(&src_path, crate_name, "", models)?;
Ok(())
}
fn scan_directory(
dir: &Path,
crate_name: &str,
module_path: &str,
models: &mut Vec<SmithyModelInfo>,
) -> Result<(), Box<dyn std::error::Error>> {
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let dir_name = match path.file_name() {
Some(name) => name.to_string_lossy(),
None => {
println!(
"cargo:warning=Skipping directory with invalid name: {}",
path.display()
);
continue;
}
};
let new_module_path = if module_path.is_empty() {
dir_name.to_string()
} else {
format!("{}::{}", module_path, dir_name)
};
scan_directory(&path, crate_name, &new_module_path, models)?;
} else if path.extension().map(|ext| ext == "rs").unwrap_or(false) {
if let Err(e) = scan_rust_file(&path, crate_name, module_path, models) {
println!(
"cargo:warning=Failed to scan Rust file {}: {}",
path.display(),
e
);
}
}
}
}
Ok(())
}
fn scan_rust_file(
file_path: &Path,
crate_name: &str,
module_path: &str,
models: &mut Vec<SmithyModelInfo>,
) -> Result<(), Box<dyn std::error::Error>> {
if let Ok(content) = fs::read_to_string(file_path) {
// Enhanced regex that handles comments, doc comments, and multiple attributes
// between derive and struct/enum declarations
let re = Regex::new(r"(?ms)^#\[derive\(([^)]*(?:\([^)]*\))*[^)]*)\)\]\s*(?:(?:#\[[^\]]*\]\s*)|(?://[^\r\n]*\s*)|(?:///[^\r\n]*\s*)|(?:/\*.*?\*/\s*))*(?:pub\s+)?(?:struct|enum)\s+([A-Z][A-Za-z0-9_]*)\s*[<\{\(]")
.map_err(|e| format!("Failed to compile regex: {}", e))?;
for captures in re.captures_iter(&content) {
let derive_content = match captures.get(1) {
Some(capture) => capture.as_str(),
None => {
println!(
"cargo:warning=Missing derive content in regex capture for {}",
file_path.display()
);
continue;
}
};
let item_name = match captures.get(2) {
Some(capture) => capture.as_str(),
None => {
println!(
"cargo:warning=Missing item name in regex capture for {}",
file_path.display()
);
continue;
}
};
// Check if "SmithyModel" is present in the derive macro's content.
if derive_content.contains("SmithyModel") {
// Validate that the item name is a valid Rust identifier
if is_valid_rust_identifier(item_name) {
let full_module_path = create_module_path(file_path, crate_name, module_path)?;
models.push(SmithyModelInfo {
struct_name: item_name.to_string(),
module_path: full_module_path,
});
} else {
println!(
"cargo:warning=Skipping invalid identifier: {} in {}",
item_name,
file_path.display()
);
}
}
}
}
Ok(())
}
fn is_valid_rust_identifier(name: &str) -> bool {
if name.is_empty() {
return false;
}
// Rust identifiers must start with a letter or underscore
let first_char = match name.chars().next() {
Some(ch) => ch,
None => return false, // This shouldn't happen since we checked is_empty above, but being safe
};
if !first_char.is_ascii_alphabetic() && first_char != '_' {
return false;
}
// Must not be a Rust keyword
let keywords = [
"as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn",
"for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
"return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe",
"use", "where", "while", "async", "await", "dyn", "is", "abstract", "become", "box", "do",
"final", "macro", "override", "priv", "typeof", "unsized", "virtual", "yield", "try",
];
if keywords.contains(&name) {
return false;
}
// All other characters must be alphanumeric or underscore
name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}
fn create_module_path(
file_path: &Path,
crate_name: &str,
module_path: &str,
) -> Result<String, Box<dyn std::error::Error>> {
let file_name = file_path
.file_stem()
.and_then(|s| s.to_str())
.ok_or_else(|| {
format!(
"Cannot extract file name from path: {}",
file_path.display()
)
})?;
let crate_name_normalized = crate_name.replace('-', "_");
let result = if file_name == "lib" || file_name == "mod" {
if module_path.is_empty() {
crate_name_normalized
} else {
format!("{}::{}", crate_name_normalized, module_path)
}
} else if module_path.is_empty() {
format!("{}::{}", crate_name_normalized, file_name)
} else {
format!("{}::{}::{}", crate_name_normalized, module_path, file_name)
};
Ok(result)
}
#[derive(Debug)]
struct SmithyModelInfo {
struct_name: String,
module_path: String,
}
fn generate_model_registry(models: &[SmithyModelInfo]) -> Result<(), Box<dyn std::error::Error>> {
let out_dir = std::env::var("OUT_DIR").map_err(|_| "OUT_DIR environment variable not set")?;
let registry_path = Path::new(&out_dir).join("model_registry.rs");
let mut content = String::new();
content.push_str("// Auto-generated model registry\n");
content.push_str("// DO NOT EDIT - This file is generated by build.rs\n\n");
if !models.is_empty() {
content.push_str("use smithy_core::{SmithyModel, SmithyModelGenerator};\n\n");
// Generate imports
for model in models {
content.push_str(&format!(
"use {}::{};\n",
model.module_path, model.struct_name
));
}
content.push_str("\npub fn discover_smithy_models() -> Vec<SmithyModel> {\n");
content.push_str(" let mut models = Vec::new();\n\n");
// Generate model collection calls
for model in models {
content.push_str(&format!(
" models.push({}::generate_smithy_model());\n",
model.struct_name
));
}
content.push_str("\n models\n");
content.push_str("}\n");
} else {
// Generate empty function if no models found
content.push_str("use smithy_core::SmithyModel;\n\n");
content.push_str("pub fn discover_smithy_models() -> Vec<SmithyModel> {\n");
content.push_str(
" router_env::logger::info!(\"No SmithyModel structs found in workspace\");\n",
);
content.push_str(" Vec::new()\n");
content.push_str("}\n");
}
fs::write(®istry_path, content).map_err(|e| {
format!(
"Failed to write model registry to {}: {}",
registry_path.display(),
e
)
})?;
Ok(())
}
</file>
|
{
"crate": "smithy-generator",
"file": "crates/smithy-generator/build.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2355
}
|
large_file_-5769922065324029964
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: openapi
File: crates/openapi/src/openapi.rs
</path>
<file>
use crate::routes;
#[derive(utoipa::OpenApi)]
#[openapi(
info(
title = "Hyperswitch - API Documentation",
contact(
name = "Hyperswitch Support",
url = "https://hyperswitch.io",
email = "[email protected]"
),
// terms_of_service = "https://www.juspay.io/terms",
description = r#"
## Get started
Hyperswitch provides a collection of APIs that enable you to process and manage payments.
Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.
You can consume the APIs directly using your favorite HTTP/REST library.
We have a testing environment referred to "sandbox", which you can setup to test API calls without
affecting production data.
Currently, our sandbox environment is live while our production environment is under development
and will be available soon.
You can sign up on our Dashboard to get API keys to access Hyperswitch API.
### Environment
Use the following base URLs when making requests to the APIs:
| Environment | Base URL |
|---------------|------------------------------------|
| Sandbox | <https://sandbox.hyperswitch.io> |
| Production | <https://api.hyperswitch.io> |
## Authentication
When you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant
account, you are given a secret key (also referred as api-key) and a publishable key.
You may authenticate all API requests with Hyperswitch server by providing the appropriate key in
the request Authorization header.
| Key | Description |
|-----------------|-----------------------------------------------------------------------------------------------|
| api-key | Private key. Used to authenticate all API requests from your merchant server |
| publishable key | Unique identifier for your account. Used to authenticate API requests from your app's client |
Never share your secret api keys. Keep them guarded and secure.
"#,
),
servers(
(url = "https://sandbox.hyperswitch.io", description = "Sandbox Environment")
),
tags(
(name = "Merchant Account", description = "Create and manage merchant accounts"),
(name = "Profile", description = "Create and manage profiles"),
(name = "Merchant Connector Account", description = "Create and manage merchant connector accounts"),
(name = "Payments", description = "Create and manage one-time payments, recurring payments and mandates"),
(name = "Refunds", description = "Create and manage refunds for successful payments"),
(name = "Mandates", description = "Manage mandates"),
(name = "Customers", description = "Create and manage customers"),
(name = "Payment Methods", description = "Create and manage payment methods of customers"),
(name = "Disputes", description = "Manage disputes"),
(name = "API Key", description = "Create and manage API Keys"),
(name = "Payouts", description = "Create and manage payouts"),
(name = "payment link", description = "Create payment link"),
(name = "Routing", description = "Create and manage routing configurations"),
(name = "Event", description = "Manage events"),
(name = "Authentication", description = "Create and manage authentication"),
(name = "Subscriptions", description = "Subscription management and billing endpoints")
),
// The paths will be displayed in the same order as they are registered here
paths(
// Routes for payments
routes::payments::payments_create,
routes::payments::payments_update,
routes::payments::payments_confirm,
routes::payments::payments_retrieve,
routes::payments::payments_capture,
routes::payments::payments_connector_session,
routes::payments::payments_cancel,
routes::payments::payments_cancel_post_capture,
routes::payments::payments_extend_authorization,
routes::payments::payments_list,
routes::payments::payments_incremental_authorization,
routes::payment_link::payment_link_retrieve,
routes::payments::payments_external_authentication,
routes::payments::payments_complete_authorize,
routes::payments::payments_post_session_tokens,
routes::payments::payments_update_metadata,
routes::payments::payments_submit_eligibility,
// Routes for relay
routes::relay::relay,
routes::relay::relay_retrieve,
// Routes for refunds
routes::refunds::refunds_create,
routes::refunds::refunds_retrieve,
routes::refunds::refunds_update,
routes::refunds::refunds_list,
// Routes for Organization
routes::organization::organization_create,
routes::organization::organization_retrieve,
routes::organization::organization_update,
// Routes for merchant account
routes::merchant_account::merchant_account_create,
routes::merchant_account::retrieve_merchant_account,
routes::merchant_account::update_merchant_account,
routes::merchant_account::delete_merchant_account,
routes::merchant_account::merchant_account_kv_status,
// Routes for merchant connector account
routes::merchant_connector_account::connector_create,
routes::merchant_connector_account::connector_retrieve,
routes::merchant_connector_account::connector_list,
routes::merchant_connector_account::connector_update,
routes::merchant_connector_account::connector_delete,
//Routes for gsm
routes::gsm::create_gsm_rule,
routes::gsm::get_gsm_rule,
routes::gsm::update_gsm_rule,
routes::gsm::delete_gsm_rule,
// Routes for mandates
routes::mandates::get_mandate,
routes::mandates::revoke_mandate,
routes::mandates::customers_mandates_list,
//Routes for customers
routes::customers::customers_create,
routes::customers::customers_retrieve,
routes::customers::customers_list,
routes::customers::customers_update,
routes::customers::customers_delete,
//Routes for payment methods
routes::payment_method::create_payment_method_api,
routes::payment_method::list_payment_method_api,
routes::payment_method::list_customer_payment_method_api,
routes::payment_method::list_customer_payment_method_api_client,
routes::payment_method::default_payment_method_set_api,
routes::payment_method::payment_method_retrieve_api,
routes::payment_method::payment_method_update_api,
routes::payment_method::payment_method_delete_api,
// Routes for Profile
routes::profile::profile_create,
routes::profile::profile_list,
routes::profile::profile_retrieve,
routes::profile::profile_update,
routes::profile::profile_delete,
// Routes for disputes
routes::disputes::retrieve_dispute,
routes::disputes::retrieve_disputes_list,
// Routes for routing
routes::routing::routing_create_config,
routes::routing::routing_link_config,
routes::routing::routing_retrieve_config,
routes::routing::list_routing_configs,
routes::routing::routing_unlink_config,
routes::routing::routing_update_default_config,
routes::routing::routing_retrieve_default_config,
routes::routing::routing_retrieve_linked_config,
routes::routing::routing_retrieve_default_config_for_profiles,
routes::routing::routing_update_default_config_for_profile,
routes::routing::success_based_routing_update_configs,
routes::routing::toggle_success_based_routing,
routes::routing::toggle_elimination_routing,
routes::routing::contract_based_routing_setup_config,
routes::routing::contract_based_routing_update_configs,
routes::routing::call_decide_gateway_open_router,
routes::routing::call_update_gateway_score_open_router,
routes::routing::evaluate_routing_rule,
// Routes for blocklist
routes::blocklist::remove_entry_from_blocklist,
routes::blocklist::list_blocked_payment_methods,
routes::blocklist::add_entry_to_blocklist,
routes::blocklist::toggle_blocklist_guard,
// Routes for payouts
routes::payouts::payouts_create,
routes::payouts::payouts_retrieve,
routes::payouts::payouts_update,
routes::payouts::payouts_cancel,
routes::payouts::payouts_fulfill,
routes::payouts::payouts_list,
routes::payouts::payouts_confirm,
routes::payouts::payouts_list_filters,
routes::payouts::payouts_list_by_filter,
// Routes for api keys
routes::api_keys::api_key_create,
routes::api_keys::api_key_retrieve,
routes::api_keys::api_key_update,
routes::api_keys::api_key_revoke,
routes::api_keys::api_key_list,
// Routes for events
routes::webhook_events::list_initial_webhook_delivery_attempts,
routes::webhook_events::list_initial_webhook_delivery_attempts_with_jwtauth,
routes::webhook_events::list_webhook_delivery_attempts,
routes::webhook_events::retry_webhook_delivery_attempt,
// Routes for poll apis
routes::poll::retrieve_poll_status,
// Routes for profile acquirer account
routes::profile_acquirer::profile_acquirer_create,
routes::profile_acquirer::profile_acquirer_update,
// Routes for 3DS Decision Rule
routes::three_ds_decision_rule::three_ds_decision_rule_execute,
// Routes for authentication
routes::authentication::authentication_create,
// Routes for platform account
routes::platform::create_platform_account,
//Routes for subscriptions
routes::subscriptions::create_and_confirm_subscription,
routes::subscriptions::create_subscription,
routes::subscriptions::confirm_subscription,
routes::subscriptions::get_subscription,
routes::subscriptions::update_subscription,
routes::subscriptions::get_subscription_plans,
routes::subscriptions::get_estimate,
),
components(schemas(
common_utils::types::MinorUnit,
common_utils::types::StringMinorUnit,
common_utils::types::TimeRange,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
common_utils::payout_method_utils::AdditionalPayoutMethodData,
common_utils::payout_method_utils::CardAdditionalData,
common_utils::payout_method_utils::BankAdditionalData,
common_utils::payout_method_utils::WalletAdditionalData,
common_utils::payout_method_utils::BankRedirectAdditionalData,
common_utils::payout_method_utils::AchBankTransferAdditionalData,
common_utils::payout_method_utils::BacsBankTransferAdditionalData,
common_utils::payout_method_utils::SepaBankTransferAdditionalData,
common_utils::payout_method_utils::PixBankTransferAdditionalData,
common_utils::payout_method_utils::PaypalAdditionalData,
common_utils::payout_method_utils::InteracAdditionalData,
common_utils::payout_method_utils::VenmoAdditionalData,
common_utils::payout_method_utils::ApplePayDecryptAdditionalData,
common_types::payments::SplitPaymentsRequest,
common_types::payments::GpayTokenizationData,
common_types::payments::GPayPredecryptData,
common_types::payments::GpayEcryptedTokenizationData,
common_types::payments::ApplePayPaymentData,
common_types::payments::ApplePayPredecryptData,
common_types::payments::ApplePayCryptogramData,
common_types::payments::StripeSplitPaymentRequest,
common_types::domain::AdyenSplitData,
common_types::domain::AdyenSplitItem,
common_types::payments::AcceptanceType,
common_types::payments::CustomerAcceptance,
common_types::payments::OnlineMandate,
common_types::payments::XenditSplitRequest,
common_types::payments::XenditSplitRoute,
common_types::payments::XenditChargeResponseData,
common_types::payments::XenditMultipleSplitResponse,
common_types::payments::XenditMultipleSplitRequest,
common_types::domain::XenditSplitSubMerchantData,
common_utils::types::ChargeRefunds,
common_types::refunds::SplitRefund,
common_types::refunds::StripeSplitRefundRequest,
common_types::payments::ConnectorChargeResponseData,
common_types::payments::StripeChargeResponseData,
common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
common_types::three_ds_decision_rule_engine::ThreeDSDecision,
common_types::payments::MerchantCountryCode,
api_models::enums::PaymentChannel,
api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest,
api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteResponse,
api_models::three_ds_decision_rule::PaymentData,
api_models::three_ds_decision_rule::PaymentMethodMetaData,
api_models::three_ds_decision_rule::CustomerDeviceData,
api_models::three_ds_decision_rule::IssuerData,
api_models::three_ds_decision_rule::AcquirerData,
api_models::refunds::RefundRequest,
api_models::refunds::RefundType,
api_models::refunds::RefundResponse,
api_models::refunds::RefundStatus,
api_models::refunds::RefundUpdateRequest,
api_models::organization::OrganizationCreateRequest,
api_models::organization::OrganizationUpdateRequest,
api_models::organization::OrganizationResponse,
api_models::admin::MerchantAccountCreate,
api_models::admin::MerchantAccountUpdate,
api_models::admin::MerchantAccountDeleteResponse,
api_models::admin::MerchantConnectorDeleteResponse,
api_models::admin::MerchantConnectorResponse,
api_models::admin::MerchantConnectorListResponse,
api_models::admin::AuthenticationConnectorDetails,
api_models::admin::ExtendedCardInfoConfig,
api_models::admin::BusinessGenericLinkConfig,
api_models::admin::BusinessCollectLinkConfig,
api_models::admin::BusinessPayoutLinkConfig,
api_models::admin::CardTestingGuardConfig,
api_models::admin::CardTestingGuardStatus,
api_models::customers::CustomerRequest,
api_models::customers::CustomerUpdateRequest,
api_models::customers::CustomerDeleteResponse,
api_models::payment_methods::PaymentMethodCreate,
api_models::payment_methods::PaymentMethodResponse,
api_models::payment_methods::CustomerPaymentMethod,
common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
common_types::domain::AcquirerConfigMap,
common_types::domain::AcquirerConfig,
api_models::payment_methods::PaymentMethodListResponse,
api_models::payment_methods::ResponsePaymentMethodsEnabled,
api_models::payment_methods::ResponsePaymentMethodTypes,
api_models::payment_methods::PaymentExperienceTypes,
api_models::payment_methods::CardNetworkTypes,
api_models::payment_methods::BankDebitTypes,
api_models::payment_methods::BankTransferTypes,
api_models::payment_methods::CustomerPaymentMethodsListResponse,
api_models::payment_methods::PaymentMethodDeleteResponse,
api_models::payment_methods::PaymentMethodUpdate,
api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::CardDetail,
api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::poll::PollResponse,
api_models::poll::PollStatus,
api_models::customers::CustomerResponse,
api_models::admin::AcceptedCountries,
api_models::admin::AcceptedCurrencies,
api_models::enums::AdyenSplitType,
api_models::enums::PaymentType,
api_models::enums::MitCategory,
api_models::enums::ScaExemptionType,
api_models::enums::PaymentMethod,
api_models::enums::TriggeredBy,
api_models::enums::TokenDataType,
api_models::enums::PaymentMethodType,
api_models::enums::ConnectorType,
api_models::enums::PayoutConnectors,
api_models::enums::AuthenticationConnectors,
api_models::enums::Currency,
api_models::enums::DocumentKind,
api_models::enums::IntentStatus,
api_models::enums::CaptureMethod,
api_models::enums::FutureUsage,
api_models::enums::AuthenticationType,
api_models::enums::Connector,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodIssuerCode,
api_models::enums::TaxStatus,
api_models::enums::MandateStatus,
api_models::enums::PaymentExperience,
api_models::enums::BankNames,
api_models::enums::BankType,
api_models::enums::BankHolderType,
api_models::enums::CardNetwork,
api_models::enums::MerchantCategoryCode,
api_models::enums::DisputeStage,
api_models::enums::DisputeStatus,
api_models::enums::CountryAlpha2,
api_models::enums::Country,
api_models::enums::CountryAlpha3,
api_models::enums::FieldType,
api_models::enums::FrmAction,
api_models::enums::FrmPreferredFlowTypes,
api_models::enums::RetryAction,
api_models::enums::AttemptStatus,
api_models::enums::CaptureStatus,
api_models::enums::ReconStatus,
api_models::enums::ConnectorStatus,
api_models::enums::AuthorizationStatus,
api_models::enums::ElementPosition,
api_models::enums::ElementSize,
api_models::enums::SizeVariants,
api_models::enums::MerchantProductType,
api_models::enums::PaymentLinkDetailsLayout,
api_models::enums::PaymentMethodStatus,
api_models::enums::UIWidgetFormLayout,
api_models::enums::MerchantProductType,
api_models::enums::HyperswitchConnectorCategory,
api_models::enums::ConnectorIntegrationStatus,
api_models::enums::CardDiscovery,
api_models::enums::FeatureStatus,
api_models::enums::MerchantProductType,
api_models::enums::CtpServiceProvider,
api_models::enums::PaymentLinkSdkLabelType,
api_models::enums::OrganizationType,
api_models::enums::PaymentLinkShowSdkTerms,
api_models::enums::ExternalVaultEnabled,
api_models::enums::GooglePayCardFundingSource,
api_models::enums::VaultSdk,
api_models::admin::ExternalVaultConnectorDetails,
api_models::admin::MerchantConnectorCreate,
api_models::admin::AdditionalMerchantData,
api_models::admin::ConnectorWalletDetails,
api_models::admin::MerchantRecipientData,
api_models::admin::MerchantAccountData,
api_models::admin::MerchantConnectorUpdate,
api_models::admin::PrimaryBusinessDetails,
api_models::admin::FrmConfigs,
api_models::admin::FrmPaymentMethod,
api_models::admin::FrmPaymentMethodType,
api_models::admin::PaymentMethodsEnabled,
api_models::admin::MerchantConnectorDetailsWrap,
api_models::admin::MerchantConnectorDetails,
api_models::admin::MerchantConnectorWebhookDetails,
api_models::admin::ProfileCreate,
api_models::admin::ProfileResponse,
api_models::admin::BusinessPaymentLinkConfig,
api_models::admin::PaymentLinkBackgroundImageConfig,
api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
api_models::admin::PaymentLinkTransactionDetails,
api_models::admin::TransactionDetailsUiConfiguration,
api_models::disputes::DisputeResponse,
api_models::disputes::DisputeResponsePaymentsRetrieve,
api_models::gsm::GsmCreateRequest,
api_models::gsm::GsmRetrieveRequest,
api_models::gsm::GsmUpdateRequest,
api_models::gsm::GsmDeleteRequest,
api_models::gsm::GsmDeleteResponse,
api_models::gsm::GsmResponse,
api_models::enums::GsmDecision,
api_models::enums::GsmFeature,
common_types::domain::GsmFeatureData,
common_types::domain::RetryFeatureData,
api_models::payments::AddressDetails,
api_models::payments::BankDebitData,
api_models::payments::AliPayQr,
api_models::payments::AliPayRedirection,
api_models::payments::MomoRedirection,
api_models::payments::TouchNGoRedirection,
api_models::payments::GcashRedirection,
api_models::payments::KakaoPayRedirection,
api_models::payments::AliPayHkRedirection,
api_models::payments::GoPayRedirection,
api_models::payments::MbWayRedirection,
api_models::payments::MobilePayRedirection,
api_models::payments::WeChatPayRedirection,
api_models::payments::WeChatPayQr,
api_models::payments::BankDebitBilling,
api_models::payments::CryptoData,
api_models::payments::RewardData,
api_models::payments::UpiData,
api_models::payments::UpiCollectData,
api_models::payments::UpiIntentData,
api_models::payments::UpiQrData,
api_models::payments::VoucherData,
api_models::payments::BoletoVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::Address,
api_models::payments::VoucherData,
api_models::payments::JCSVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::BankRedirectData,
api_models::payments::RealTimePaymentData,
api_models::payments::BankRedirectBilling,
api_models::payments::BankRedirectBilling,
api_models::payments::ConnectorMetadata,
api_models::payments::FeatureMetadata,
api_models::payments::ApplepayConnectorMetadataRequest,
api_models::payments::SessionTokenInfo,
api_models::payments::PaymentProcessingDetailsAt,
api_models::payments::ApplepayInitiative,
api_models::payments::PaymentProcessingDetails,
api_models::payments::PaymentMethodDataResponseWithBilling,
api_models::payments::PaymentMethodDataResponse,
api_models::payments::CardResponse,
api_models::payments::PaylaterResponse,
api_models::payments::KlarnaSdkPaymentMethodResponse,
api_models::payments::SwishQrData,
api_models::payments::RevolutPayData,
api_models::payments::AirwallexData,
api_models::payments::BraintreeData,
api_models::payments::NoonData,
api_models::payments::OrderDetailsWithAmount,
api_models::payments::NextActionType,
api_models::payments::WalletData,
api_models::payments::NextActionData,
api_models::payments::PayLaterData,
api_models::payments::MandateData,
api_models::payments::PhoneDetails,
api_models::payments::PaymentMethodData,
api_models::payments::PaymentMethodDataRequest,
api_models::payments::MandateType,
api_models::payments::MandateAmountData,
api_models::payments::Card,
api_models::payments::CardRedirectData,
api_models::payments::CardToken,
api_models::payments::PaymentsRequest,
api_models::payments::PaymentsCreateRequest,
api_models::payments::PaymentsUpdateRequest,
api_models::payments::PaymentsConfirmRequest,
api_models::payments::PaymentsResponse,
api_models::payments::PaymentsCreateResponseOpenApi,
api_models::payments::PaymentsEligibilityRequest,
api_models::payments::PaymentsEligibilityResponse,
api_models::payments::PaymentsCreateResponseOpenApi,
api_models::errors::types::GenericErrorResponseOpenApi,
api_models::payments::PaymentRetrieveBody,
api_models::payments::PaymentsRetrieveRequest,
api_models::payments::PaymentsCaptureRequest,
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
api_models::payments::PazeWalletData,
api_models::payments::SessionToken,
api_models::payments::ApplePaySessionResponse,
api_models::payments::NullObject,
api_models::payments::ThirdPartySdkSessionResponse,
api_models::payments::NoThirdPartySdkSessionResponse,
api_models::payments::SecretInfoToInitiateSdk,
api_models::payments::ApplePayPaymentRequest,
api_models::payments::ApplePayBillingContactFields,
api_models::payments::ApplePayShippingContactFields,
api_models::payments::ApplePayRecurringPaymentRequest,
api_models::payments::ApplePayRegularBillingRequest,
api_models::payments::ApplePayPaymentTiming,
api_models::payments::RecurringPaymentIntervalUnit,
api_models::payments::ApplePayRecurringDetails,
api_models::payments::ApplePayRegularBillingDetails,
api_models::payments::ApplePayAddressParameters,
api_models::payments::AmountInfo,
api_models::payments::ClickToPaySessionResponse,
api_models::enums::ProductType,
api_models::enums::MerchantAccountType,
api_models::enums::MerchantAccountRequestType,
api_models::payments::GooglePayWalletData,
api_models::payments::PayPalWalletData,
api_models::payments::PaypalRedirection,
api_models::payments::GpayMerchantInfo,
api_models::payments::GpayAllowedPaymentMethods,
api_models::payments::GpayAllowedMethodsParameters,
api_models::payments::GpayTokenizationSpecification,
api_models::payments::GpayTokenParameters,
api_models::payments::GpayTransactionInfo,
api_models::payments::GpaySessionTokenResponse,
api_models::payments::GooglePayThirdPartySdkData,
api_models::payments::KlarnaSessionTokenResponse,
api_models::payments::PaypalSessionTokenResponse,
api_models::payments::PaypalFlow,
api_models::payments::PaypalTransactionInfo,
api_models::payments::ApplepaySessionTokenResponse,
api_models::payments::SdkNextAction,
api_models::payments::NextActionCall,
api_models::payments::SdkNextActionData,
api_models::payments::SamsungPayWalletData,
api_models::payments::WeChatPay,
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
api_models::payments::SamsungPayWalletCredentials,
api_models::payments::SamsungPayWebWalletData,
api_models::payments::SamsungPayAppWalletData,
api_models::payments::SamsungPayCardBrand,
api_models::payments::SamsungPayTokenData,
api_models::payments::ApplepayPaymentMethod,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentsCancelPostCaptureRequest,
api_models::payments::PaymentListConstraints,
api_models::payments::PaymentListResponse,
api_models::payments::CashappQr,
api_models::payments::BankTransferData,
api_models::payments::BankTransferNextStepsData,
api_models::payments::SepaAndBacsBillingDetails,
api_models::payments::AchBillingDetails,
api_models::payments::MultibancoBillingDetails,
api_models::payments::DokuBillingDetails,
api_models::payments::BankTransferInstructions,
api_models::payments::MobilePaymentNextStepData,
api_models::payments::MobilePaymentConsent,
api_models::payments::IframeData,
api_models::payments::ReceiverDetails,
api_models::payments::AchTransfer,
api_models::payments::MultibancoTransferInstructions,
api_models::payments::DokuBankTransferInstructions,
api_models::payments::AmazonPayRedirectData,
api_models::payments::SkrillData,
api_models::payments::PayseraData,
api_models::payments::ApplePayRedirectData,
api_models::payments::ApplePayThirdPartySdkData,
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::payments::GooglePaySessionResponse,
api_models::payments::PazeSessionTokenResponse,
api_models::payments::SamsungPaySessionTokenResponse,
api_models::payments::SamsungPayMerchantPaymentInformation,
api_models::payments::SamsungPayAmountDetails,
api_models::payments::SamsungPayAmountFormat,
api_models::payments::SamsungPayProtocolType,
api_models::payments::GpayShippingAddressParameters,
api_models::payments::GpayBillingAddressParameters,
api_models::payments::GpayBillingAddressFormat,
api_models::payments::NetworkDetails,
api_models::payments::SepaBankTransferInstructions,
api_models::payments::BacsBankTransferInstructions,
api_models::payments::RedirectResponse,
api_models::payments::RequestSurchargeDetails,
api_models::payments::PaymentAttemptResponse,
api_models::payments::CaptureResponse,
api_models::payments::PaymentsIncrementalAuthorizationRequest,
api_models::payments::IncrementalAuthorizationResponse,
api_models::payments::PaymentsCompleteAuthorizeRequest,
api_models::payments::PaymentsExternalAuthenticationRequest,
api_models::payments::PaymentsExternalAuthenticationResponse,
api_models::payments::SdkInformation,
api_models::payments::DeviceChannel,
api_models::payments::ThreeDsCompletionIndicator,
api_models::payments::MifinityData,
api_models::enums::TransactionStatus,
api_models::payments::BrowserInformation,
api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payments::ThreeDsData,
api_models::payments::ThreeDsMethodData,
api_models::payments::ThreeDsMethodKey,
api_models::payments::PollConfigResponse,
api_models::payments::PollConfig,
api_models::payments::ExternalAuthenticationDetailsResponse,
api_models::payments::ExtendedCardInfo,
api_models::payments::AmazonPaySessionTokenData,
api_models::payments::AmazonPayMerchantCredentials,
api_models::payments::AmazonPayWalletData,
api_models::payments::AmazonPaySessionTokenResponse,
api_models::payments::AmazonPayPaymentIntent,
api_models::payments::AmazonPayDeliveryOptions,
api_models::payments::AmazonPayDeliveryPrice,
api_models::payments::AmazonPayShippingMethod,
api_models::payment_methods::RequiredFieldInfo,
api_models::payment_methods::DefaultPaymentMethod,
api_models::payment_methods::MaskedBankDetails,
api_models::payment_methods::SurchargeDetailsResponse,
api_models::payment_methods::SurchargeResponse,
api_models::payment_methods::SurchargePercentage,
api_models::payment_methods::PaymentMethodCollectLinkRequest,
api_models::payment_methods::PaymentMethodCollectLinkResponse,
api_models::payment_methods::CardType,
api_models::payment_methods::CardNetworkTokenizeRequest,
api_models::payment_methods::CardNetworkTokenizeResponse,
api_models::payment_methods::TokenizeDataRequest,
api_models::payment_methods::TokenizeCardRequest,
api_models::payment_methods::TokenizePaymentMethodRequest,
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::relay::RelayRequest,
api_models::relay::RelayResponse,
api_models::enums::RelayType,
api_models::relay::RelayData,
api_models::relay::RelayRefundRequestData,
api_models::enums::RelayStatus,
api_models::relay::RelayError,
api_models::payments::AmountFilter,
api_models::mandates::MandateRevokedResponse,
api_models::mandates::MandateResponse,
api_models::mandates::MandateCardDetails,
api_models::mandates::RecurringDetails,
api_models::mandates::NetworkTransactionIdAndCardDetails,
api_models::mandates::ProcessorPaymentToken,
api_models::ephemeral_key::EphemeralKeyCreateResponse,
api_models::payments::CustomerDetails,
api_models::payments::GiftCardData,
api_models::payments::GiftCardDetails,
api_models::payments::BHNGiftCardDetails,
api_models::payments::MobilePaymentData,
api_models::payments::MobilePaymentResponse,
api_models::payments::Address,
api_models::payments::BankCodeResponse,
api_models::payouts::CardPayout,
api_models::payouts::Wallet,
api_models::payouts::Paypal,
api_models::payouts::BankRedirect,
api_models::payouts::Interac,
api_models::payouts::Venmo,
api_models::payouts::AchBankTransfer,
api_models::payouts::BacsBankTransfer,
api_models::payouts::SepaBankTransfer,
api_models::payouts::PixBankTransfer,
api_models::payouts::PayoutsCreateRequest,
api_models::payouts::PayoutUpdateRequest,
api_models::payouts::PayoutConfirmRequest,
api_models::payouts::PayoutCancelRequest,
api_models::payouts::PayoutFulfillRequest,
api_models::payouts::PayoutRetrieveRequest,
api_models::payouts::PayoutAttemptResponse,
api_models::payouts::PayoutCreateResponse,
api_models::payouts::PayoutListConstraints,
api_models::payouts::PayoutListFilters,
api_models::payouts::PayoutListFilterConstraints,
api_models::payouts::PayoutListResponse,
api_models::payouts::PayoutRetrieveBody,
api_models::payouts::PayoutMethodData,
api_models::payouts::PayoutMethodDataResponse,
api_models::payouts::PayoutLinkResponse,
api_models::payouts::Bank,
api_models::payouts::ApplePayDecrypt,
api_models::payouts::PayoutCreatePayoutLinkConfig,
api_models::enums::PayoutEntityType,
api_models::enums::PayoutSendPriority,
api_models::enums::PayoutStatus,
api_models::enums::PayoutType,
api_models::enums::TransactionType,
api_models::payments::FrmMessage,
api_models::webhooks::OutgoingWebhook,
api_models::webhooks::OutgoingWebhookContent,
api_models::enums::EventClass,
api_models::enums::EventType,
api_models::enums::DecoupledAuthenticationType,
api_models::enums::AuthenticationStatus,
api_models::admin::MerchantAccountResponse,
api_models::admin::MerchantConnectorId,
api_models::admin::MerchantDetails,
api_models::admin::ToggleKVRequest,
api_models::admin::ToggleKVResponse,
api_models::admin::WebhookDetails,
api_models::api_keys::ApiKeyExpiration,
api_models::api_keys::CreateApiKeyRequest,
api_models::api_keys::CreateApiKeyResponse,
api_models::api_keys::RetrieveApiKeyResponse,
api_models::api_keys::RevokeApiKeyResponse,
api_models::api_keys::UpdateApiKeyRequest,
api_models::payments::RetrievePaymentLinkRequest,
api_models::payments::PaymentLinkResponse,
api_models::payments::RetrievePaymentLinkResponse,
api_models::payments::PaymentLinkInitiateRequest,
api_models::payouts::PayoutLinkInitiateRequest,
api_models::payments::ExtendedCardInfoResponse,
api_models::payments::GooglePayAssuranceDetails,
api_models::routing::RoutingConfigRequest,
api_models::routing::RoutingDictionaryRecord,
api_models::routing::RoutingKind,
api_models::routing::RoutableConnectorChoice,
api_models::routing::DynamicRoutingFeatures,
api_models::routing::SuccessBasedRoutingConfig,
api_models::routing::DynamicRoutingConfigParams,
api_models::routing::CurrentBlockThreshold,
api_models::routing::SuccessBasedRoutingConfigBody,
api_models::routing::ContractBasedRoutingConfig,
api_models::routing::ContractBasedRoutingConfigBody,
api_models::routing::LabelInformation,
api_models::routing::ContractBasedTimeScale,
api_models::routing::LinkedRoutingConfigRetrieveResponse,
api_models::routing::RoutingRetrieveResponse,
api_models::routing::ProfileDefaultRoutingConfig,
api_models::routing::MerchantRoutingAlgorithm,
api_models::routing::RoutingAlgorithmKind,
api_models::routing::RoutingDictionary,
api_models::routing::RoutingAlgorithmWrapper,
api_models::routing::EliminationRoutingConfig,
api_models::open_router::DecisionEngineEliminationData,
api_models::routing::EliminationAnalyserConfig,
api_models::routing::DynamicRoutingAlgorithm,
api_models::routing::StaticRoutingAlgorithm,
api_models::routing::StraightThroughAlgorithm,
api_models::routing::ConnectorVolumeSplit,
api_models::routing::ConnectorSelection,
api_models::routing::SuccessRateSpecificityLevel,
api_models::routing::ToggleDynamicRoutingQuery,
api_models::routing::ToggleDynamicRoutingPath,
api_models::routing::ProgramThreeDsDecisionRule,
api_models::routing::RuleThreeDsDecisionRule,
api_models::routing::RoutingVolumeSplitResponse,
api_models::routing::ast::RoutableChoiceKind,
api_models::enums::RoutableConnectors,
api_models::routing::ast::ProgramConnectorSelection,
api_models::routing::ast::RuleConnectorSelection,
api_models::routing::ast::IfStatement,
api_models::routing::ast::Comparison,
api_models::routing::ast::ComparisonType,
api_models::routing::ast::ValueType,
api_models::routing::ast::MetadataValue,
api_models::routing::ast::NumberComparison,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payments::PaymentLinkStatus,
api_models::blocklist::BlocklistRequest,
api_models::blocklist::BlocklistResponse,
api_models::blocklist::ToggleBlocklistResponse,
api_models::blocklist::ListBlocklistQuery,
api_models::enums::BlocklistDataKind,
api_models::enums::ErrorCategory,
api_models::webhook_events::EventListConstraints,
api_models::webhook_events::EventListItemResponse,
api_models::webhook_events::EventRetrieveResponse,
api_models::webhook_events::OutgoingWebhookRequestContent,
api_models::webhook_events::OutgoingWebhookResponseContent,
api_models::webhook_events::TotalEventsResponse,
api_models::enums::WebhookDeliveryAttempt,
api_models::enums::PaymentChargeType,
api_models::enums::StripeChargeType,
api_models::payments::CustomerDetailsResponse,
api_models::payments::SdkType,
api_models::payments::OpenBankingData,
api_models::payments::OpenBankingSessionToken,
api_models::payments::BankDebitResponse,
api_models::payments::BankRedirectResponse,
api_models::payments::BankTransferResponse,
api_models::payments::CardRedirectResponse,
api_models::payments::CardTokenResponse,
api_models::payments::CryptoResponse,
api_models::payments::GiftCardResponse,
api_models::payments::OpenBankingResponse,
api_models::payments::RealTimePaymentDataResponse,
api_models::payments::UpiResponse,
api_models::payments::VoucherResponse,
api_models::payments::additional_info::CardTokenAdditionalData,
api_models::payments::additional_info::BankDebitAdditionalData,
api_models::payments::additional_info::AchBankDebitAdditionalData,
api_models::payments::additional_info::BacsBankDebitAdditionalData,
api_models::payments::additional_info::BecsBankDebitAdditionalData,
api_models::payments::additional_info::SepaBankDebitAdditionalData,
api_models::payments::additional_info::BankRedirectDetails,
api_models::payments::additional_info::BancontactBankRedirectAdditionalData,
api_models::payments::additional_info::BlikBankRedirectAdditionalData,
api_models::payments::additional_info::GiropayBankRedirectAdditionalData,
api_models::payments::additional_info::BankTransferAdditionalData,
api_models::payments::additional_info::PixBankTransferAdditionalData,
api_models::payments::additional_info::LocalBankTransferAdditionalData,
api_models::payments::additional_info::GiftCardAdditionalData,
api_models::payments::additional_info::GivexGiftCardAdditionalData,
api_models::payments::additional_info::UpiAdditionalData,
api_models::payments::additional_info::UpiCollectAdditionalData,
api_models::payments::additional_info::WalletAdditionalDataForCard,
api_models::payments::PaymentsDynamicTaxCalculationRequest,
api_models::payments::WalletResponse,
api_models::payments::WalletResponseData,
api_models::payments::PaymentsDynamicTaxCalculationResponse,
api_models::payments::DisplayAmountOnSdk,
api_models::payments::PaymentsPostSessionTokensRequest,
api_models::payments::PaymentsPostSessionTokensResponse,
api_models::payments::PaymentsUpdateMetadataRequest,
api_models::payments::PaymentsUpdateMetadataResponse,
api_models::payments::CtpServiceDetails,
api_models::payments::AdyenConnectorMetadata,
api_models::payments::AdyenTestingData,
api_models::feature_matrix::FeatureMatrixListResponse,
api_models::feature_matrix::FeatureMatrixRequest,
api_models::feature_matrix::ConnectorFeatureMatrixResponse,
api_models::feature_matrix::PaymentMethodSpecificFeatures,
api_models::feature_matrix::CardSpecificFeatures,
api_models::feature_matrix::SupportedPaymentMethod,
api_models::open_router::DecisionEngineSuccessRateData,
api_models::open_router::DecisionEngineGatewayWiseExtraScore,
api_models::open_router::DecisionEngineSRSubLevelInputConfig,
api_models::open_router::DecisionEngineEliminationData,
api_models::profile_acquirer::ProfileAcquirerCreate,
api_models::profile_acquirer::ProfileAcquirerUpdate,
api_models::profile_acquirer::ProfileAcquirerResponse,
euclid::frontend::dir::enums::CustomerDevicePlatform,
euclid::frontend::dir::enums::CustomerDeviceType,
euclid::frontend::dir::enums::CustomerDeviceDisplaySize,
api_models::authentication::AuthenticationCreateRequest,
api_models::authentication::AuthenticationResponse,
api_models::authentication::AcquirerDetails,
api_models::authentication::NextAction,
common_utils::request::Method,
api_models::authentication::EligibilityResponseParams,
api_models::authentication::ThreeDsData,
api_models::authentication::AuthenticationEligibilityRequest,
api_models::authentication::AuthenticationEligibilityResponse,
api_models::authentication::AuthenticationSyncRequest,
api_models::authentication::AuthenticationSyncResponse,
api_models::open_router::OpenRouterDecideGatewayRequest,
api_models::open_router::DecideGatewayResponse,
api_models::open_router::UpdateScorePayload,
api_models::open_router::UpdateScoreResponse,
api_models::routing::RoutingEvaluateRequest,
api_models::routing::RoutingEvaluateResponse,
api_models::routing::ValueType,
api_models::routing::DeRoutableConnectorChoice,
api_models::routing::RoutableConnectorChoice,
api_models::open_router::PaymentInfo,
common_utils::id_type::PaymentId,
common_utils::id_type::ProfileId,
api_models::open_router::RankingAlgorithm,
api_models::open_router::TxnStatus,
api_models::open_router::PriorityLogicOutput,
api_models::open_router::PriorityLogicData,
api_models::user::PlatformAccountCreateRequest,
api_models::user::PlatformAccountCreateResponse,
common_utils::id_type::CustomerId,
common_utils::id_type::SubscriptionId,
common_utils::id_type::MerchantId,
common_utils::id_type::InvoiceId,
common_utils::id_type::MerchantConnectorAccountId,
api_models::enums::connector_enums::InvoiceStatus,
api_models::subscription::ClientSecret,
api_models::subscription::CreateAndConfirmSubscriptionRequest,
api_models::subscription::CreateSubscriptionRequest,
api_models::subscription::ConfirmSubscriptionRequest,
api_models::subscription::UpdateSubscriptionRequest,
api_models::subscription::SubscriptionResponse,
api_models::subscription::GetPlansResponse,
api_models::subscription::EstimateSubscriptionResponse,
api_models::subscription::GetPlansQuery,
api_models::subscription::EstimateSubscriptionQuery,
api_models::subscription::ConfirmSubscriptionPaymentDetails,
api_models::subscription::PaymentDetails,
api_models::subscription::CreateSubscriptionPaymentDetails,
api_models::subscription::SubscriptionLineItem,
api_models::subscription::SubscriptionPlanPrices,
api_models::subscription::PaymentResponseData,
api_models::subscription::Invoice,
api_models::subscription::SubscriptionStatus,
api_models::subscription::PeriodUnit,
)),
modifiers(&SecurityAddon)
)]
// Bypass clippy lint for not being constructed
#[allow(dead_code)]
pub(crate) struct ApiDoc;
struct SecurityAddon;
impl utoipa::Modify for SecurityAddon {
fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
use utoipa::openapi::security::{
ApiKey, ApiKeyValue, HttpAuthScheme, HttpBuilder, SecurityScheme,
};
if let Some(components) = openapi.components.as_mut() {
components.add_security_schemes_from_iter([
(
"api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Use the API key created under your merchant account from the HyperSwitch dashboard. API key is used to authenticate API requests from your merchant server only. Don't expose this key on a website or embed it in a mobile application."
))),
),
(
"admin_api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Admin API keys allow you to perform some privileged actions such as \
creating a merchant account and Merchant Connector account."
))),
),
(
"publishable_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Publishable keys are a type of keys that can be public and have limited \
scope of usage."
))),
),
(
"ephemeral_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Ephemeral keys provide temporary access to singular data, such as access \
to a single customer object for a short period of time."
))),
),
(
"jwt_key",
SecurityScheme::Http(HttpBuilder::new().scheme(HttpAuthScheme::Bearer).bearer_format("JWT").build())
)
]);
}
}
}
</file>
|
{
"crate": "openapi",
"file": "crates/openapi/src/openapi.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10076
}
|
large_file_6463116702453840645
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: openapi
File: crates/openapi/src/openapi_v2.rs
</path>
<file>
use crate::routes;
#[derive(utoipa::OpenApi)]
#[openapi(
info(
title = "Hyperswitch - API Documentation",
contact(
name = "Hyperswitch Support",
url = "https://hyperswitch.io",
email = "[email protected]"
),
// terms_of_service = "https://www.juspay.io/terms",
description = r#"
## Get started
Hyperswitch provides a collection of APIs that enable you to process and manage payments.
Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.
You can consume the APIs directly using your favorite HTTP/REST library.
We have a testing environment referred to "sandbox", which you can setup to test API calls without
affecting production data.
Currently, our sandbox environment is live while our production environment is under development
and will be available soon.
You can sign up on our Dashboard to get API keys to access Hyperswitch API.
### Environment
Use the following base URLs when making requests to the APIs:
| Environment | Base URL |
|---------------|------------------------------------|
| Sandbox | <https://sandbox.hyperswitch.io> |
| Production | <https://api.hyperswitch.io> |
## Authentication
When you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant
account, you are given a secret key (also referred as api-key) and a publishable key.
You may authenticate all API requests with Hyperswitch server by providing the appropriate key in
the request Authorization header.
| Key | Description |
|-----------------|-----------------------------------------------------------------------------------------------|
| api-key | Private key. Used to authenticate all API requests from your merchant server |
| publishable key | Unique identifier for your account. Used to authenticate API requests from your app's client |
Never share your secret api keys. Keep them guarded and secure.
"#,
),
servers(
(url = "https://sandbox.hyperswitch.io", description = "Sandbox Environment")
),
tags(
(name = "Merchant Account", description = "Create and manage merchant accounts"),
(name = "Profile", description = "Create and manage profiles"),
(name = "Merchant Connector Account", description = "Create and manage merchant connector accounts"),
(name = "Payments", description = "Create and manage one-time payments, recurring payments and mandates"),
(name = "Refunds", description = "Create and manage refunds for successful payments"),
(name = "Mandates", description = "Manage mandates"),
(name = "Customers", description = "Create and manage customers"),
(name = "Payment Methods", description = "Create and manage payment methods of customers"),
(name = "Disputes", description = "Manage disputes"),
(name = "API Key", description = "Create and manage API Keys"),
(name = "Payouts", description = "Create and manage payouts"),
(name = "payment link", description = "Create payment link"),
(name = "Routing", description = "Create and manage routing configurations"),
(name = "Event", description = "Manage events"),
),
// The paths will be displayed in the same order as they are registered here
paths(
// Routes for Organization
routes::organization::organization_create,
routes::organization::organization_retrieve,
routes::organization::organization_update,
routes::organization::merchant_account_list,
// Routes for merchant connector account
routes::merchant_connector_account::connector_create,
routes::merchant_connector_account::connector_retrieve,
routes::merchant_connector_account::connector_update,
routes::merchant_connector_account::connector_delete,
// Routes for merchant account
routes::merchant_account::merchant_account_create,
routes::merchant_account::merchant_account_retrieve,
routes::merchant_account::merchant_account_update,
routes::merchant_account::profiles_list,
// Routes for profile
routes::profile::profile_create,
routes::profile::profile_retrieve,
routes::profile::profile_update,
routes::profile::connector_list,
// Routes for routing under profile
routes::profile::routing_link_config,
routes::profile::routing_unlink_config,
routes::profile::routing_update_default_config,
routes::profile::routing_retrieve_default_config,
routes::profile::routing_retrieve_linked_config,
// Routes for routing
routes::routing::routing_create_config,
routes::routing::routing_retrieve_config,
// Routes for api keys
routes::api_keys::api_key_create,
routes::api_keys::api_key_retrieve,
routes::api_keys::api_key_update,
routes::api_keys::api_key_revoke,
routes::api_keys::api_key_list,
//Routes for customers
routes::customers::customers_create,
routes::customers::customers_retrieve,
routes::customers::customers_update,
routes::customers::customers_delete,
routes::customers::customers_list,
//Routes for payments
routes::payments::payments_create_intent,
routes::payments::payments_get_intent,
routes::payments::payments_update_intent,
routes::payments::payments_confirm_intent,
routes::payments::payment_status,
routes::payments::payments_create_and_confirm_intent,
routes::payments::payments_connector_session,
routes::payments::list_payment_methods,
routes::payments::payments_list,
routes::payments::payment_check_gift_card_balance,
//Routes for payment methods
routes::payment_method::create_payment_method_api,
routes::payment_method::create_payment_method_intent_api,
routes::payment_method::confirm_payment_method_intent_api,
routes::payment_method::payment_method_update_api,
routes::payment_method::payment_method_retrieve_api,
routes::payment_method::payment_method_delete_api,
routes::payment_method::network_token_status_check_api,
routes::payment_method::list_customer_payment_method_api,
//Routes for payment method session
routes::payment_method::payment_method_session_create,
routes::payment_method::payment_method_session_retrieve,
routes::payment_method::payment_method_session_list_payment_methods,
routes::payment_method::payment_method_session_update_saved_payment_method,
routes::payment_method::payment_method_session_delete_saved_payment_method,
routes::payment_method::payment_method_session_confirm,
//Routes for refunds
routes::refunds::refunds_create,
routes::refunds::refunds_metadata_update,
routes::refunds::refunds_retrieve,
routes::refunds::refunds_list,
// Routes for Revenue Recovery flow under Process Tracker
routes::revenue_recovery::revenue_recovery_pt_retrieve_api,
// Routes for proxy
routes::proxy::proxy_core,
// Route for tokenization
routes::tokenization::create_token_vault_api,
routes::tokenization::delete_tokenized_data_api,
),
components(schemas(
common_utils::types::MinorUnit,
common_utils::types::StringMinorUnit,
common_utils::types::TimeRange,
common_utils::types::BrowserInformation,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
common_utils::payout_method_utils::AdditionalPayoutMethodData,
common_utils::payout_method_utils::CardAdditionalData,
common_utils::payout_method_utils::BankAdditionalData,
common_utils::payout_method_utils::WalletAdditionalData,
common_utils::payout_method_utils::BankRedirectAdditionalData,
common_utils::payout_method_utils::AchBankTransferAdditionalData,
common_utils::payout_method_utils::BacsBankTransferAdditionalData,
common_utils::payout_method_utils::SepaBankTransferAdditionalData,
common_utils::payout_method_utils::PixBankTransferAdditionalData,
common_utils::payout_method_utils::PaypalAdditionalData,
common_utils::payout_method_utils::InteracAdditionalData,
common_utils::payout_method_utils::VenmoAdditionalData,
common_utils::payout_method_utils::ApplePayDecryptAdditionalData,
common_types::payments::SplitPaymentsRequest,
common_types::payments::GpayTokenizationData,
common_types::payments::GPayPredecryptData,
common_types::payments::GpayEcryptedTokenizationData,
common_types::payments::ApplePayPaymentData,
common_types::payments::ApplePayPredecryptData,
common_types::payments::ApplePayCryptogramData,
common_types::payments::ApplePayPaymentData,
common_types::payments::StripeSplitPaymentRequest,
common_types::domain::AdyenSplitData,
common_types::payments::AcceptanceType,
common_types::payments::CustomerAcceptance,
common_types::payments::OnlineMandate,
common_types::payments::XenditSplitRequest,
common_types::payments::XenditSplitRoute,
common_types::payments::XenditChargeResponseData,
common_types::payments::XenditMultipleSplitResponse,
common_types::payments::XenditMultipleSplitRequest,
common_types::domain::XenditSplitSubMerchantData,
common_types::domain::AdyenSplitItem,
common_types::domain::MerchantConnectorAuthDetails,
common_types::refunds::StripeSplitRefundRequest,
common_utils::types::ChargeRefunds,
common_types::payment_methods::PaymentMethodsEnabled,
common_types::payment_methods::PspTokenization,
common_types::payment_methods::NetworkTokenization,
common_types::refunds::SplitRefund,
common_types::payments::ConnectorChargeResponseData,
common_types::payments::StripeChargeResponseData,
common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
common_types::three_ds_decision_rule_engine::ThreeDSDecision,
common_types::payments::MerchantCountryCode,
common_utils::request::Method,
api_models::errors::types::GenericErrorResponseOpenApi,
api_models::refunds::RefundsCreateRequest,
api_models::refunds::RefundErrorDetails,
api_models::refunds::RefundType,
api_models::refunds::RefundResponse,
api_models::refunds::RefundStatus,
api_models::refunds::RefundMetadataUpdateRequest,
api_models::organization::OrganizationCreateRequest,
api_models::organization::OrganizationUpdateRequest,
api_models::organization::OrganizationResponse,
api_models::admin::MerchantAccountCreateWithoutOrgId,
api_models::admin::MerchantAccountUpdate,
api_models::admin::MerchantAccountDeleteResponse,
api_models::admin::MerchantConnectorDeleteResponse,
api_models::admin::MerchantConnectorResponse,
api_models::admin::MerchantConnectorListResponse,
api_models::admin::AuthenticationConnectorDetails,
api_models::admin::ExternalVaultConnectorDetails,
api_models::admin::ExtendedCardInfoConfig,
api_models::admin::BusinessGenericLinkConfig,
api_models::admin::BusinessCollectLinkConfig,
api_models::admin::BusinessPayoutLinkConfig,
api_models::admin::MerchantConnectorAccountFeatureMetadata,
api_models::admin::RevenueRecoveryMetadata,
api_models::customers::CustomerRequest,
api_models::customers::CustomerUpdateRequest,
api_models::customers::CustomerDeleteResponse,
api_models::ephemeral_key::ResourceId,
api_models::payment_methods::PaymentMethodCreate,
api_models::payment_methods::PaymentMethodIntentCreate,
api_models::payment_methods::PaymentMethodIntentConfirm,
api_models::payment_methods::AuthenticationDetails,
api_models::payment_methods::PaymentMethodResponse,
api_models::payment_methods::PaymentMethodResponseData,
api_models::payment_methods::CustomerPaymentMethodResponseItem,
api_models::payment_methods::PaymentMethodResponseItem,
api_models::payment_methods::ListMethodsForPaymentMethodsRequest,
api_models::payment_methods::PaymentMethodListResponseForSession,
api_models::payment_methods::CustomerPaymentMethodsListResponse,
api_models::payment_methods::ResponsePaymentMethodsEnabled,
api_models::payment_methods::PaymentMethodSubtypeSpecificData,
api_models::payment_methods::ResponsePaymentMethodTypes,
api_models::payment_methods::PaymentExperienceTypes,
api_models::payment_methods::CardNetworkTypes,
api_models::payment_methods::BankDebitTypes,
api_models::payment_methods::BankTransferTypes,
api_models::payment_methods::PaymentMethodDeleteResponse,
api_models::payment_methods::PaymentMethodUpdate,
api_models::payment_methods::PaymentMethodUpdateData,
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::ProxyCardDetails,
api_models::payment_methods::CardDetail,
api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::CardType,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payment_methods::CardType,
api_models::payment_methods::PaymentMethodListData,
api_models::payment_methods::NetworkTokenStatusCheckResponse,
api_models::payment_methods::NetworkTokenStatusCheckSuccessResponse,
api_models::payment_methods::NetworkTokenStatusCheckFailureResponse,
api_models::enums::TokenStatus,
api_models::poll::PollResponse,
api_models::poll::PollStatus,
api_models::customers::CustomerResponse,
api_models::admin::AcceptedCountries,
api_models::admin::AcceptedCurrencies,
api_models::enums::AdyenSplitType,
api_models::enums::ProductType,
api_models::enums::PaymentType,
api_models::enums::ScaExemptionType,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodType,
api_models::enums::ConnectorType,
api_models::enums::PayoutConnectors,
api_models::enums::AuthenticationConnectors,
api_models::enums::VaultSdk,
api_models::enums::Currency,
api_models::enums::DocumentKind,
api_models::enums::IntentStatus,
api_models::enums::CaptureMethod,
api_models::enums::FutureUsage,
api_models::enums::AuthenticationType,
api_models::enums::Connector,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodIssuerCode,
api_models::enums::MandateStatus,
api_models::enums::MerchantProductType,
api_models::enums::PaymentExperience,
api_models::enums::BankNames,
api_models::enums::BankType,
api_models::enums::BankHolderType,
api_models::enums::CardNetwork,
api_models::enums::MerchantCategoryCode,
api_models::enums::TokenDataType,
api_models::enums::DisputeStage,
api_models::enums::DisputeStatus,
api_models::enums::CountryAlpha2,
api_models::enums::CountryAlpha3,
api_models::enums::FieldType,
api_models::enums::FrmAction,
api_models::enums::FrmPreferredFlowTypes,
api_models::enums::RetryAction,
api_models::enums::AttemptStatus,
api_models::enums::CaptureStatus,
api_models::enums::ReconStatus,
api_models::enums::ConnectorStatus,
api_models::enums::AuthorizationStatus,
api_models::enums::ElementPosition,
api_models::enums::ElementSize,
api_models::enums::TaxStatus,
api_models::enums::SizeVariants,
api_models::enums::MerchantProductType,
api_models::enums::PaymentLinkDetailsLayout,
api_models::enums::PaymentMethodStatus,
api_models::enums::HyperswitchConnectorCategory,
api_models::enums::ConnectorIntegrationStatus,
api_models::enums::FeatureStatus,
api_models::enums::OrderFulfillmentTimeOrigin,
api_models::enums::UIWidgetFormLayout,
api_models::enums::MerchantProductType,
api_models::enums::CtpServiceProvider,
api_models::enums::PaymentLinkSdkLabelType,
api_models::enums::PaymentLinkShowSdkTerms,
api_models::enums::OrganizationType,
api_models::enums::GooglePayCardFundingSource,
api_models::admin::MerchantConnectorCreate,
api_models::admin::AdditionalMerchantData,
api_models::admin::CardTestingGuardConfig,
api_models::admin::CardTestingGuardStatus,
api_models::admin::ConnectorWalletDetails,
api_models::admin::MerchantRecipientData,
api_models::admin::MerchantAccountData,
api_models::admin::MerchantConnectorUpdate,
api_models::admin::PrimaryBusinessDetails,
api_models::admin::FrmConfigs,
api_models::admin::FrmPaymentMethod,
api_models::admin::FrmPaymentMethodType,
api_models::admin::MerchantConnectorDetailsWrap,
api_models::admin::MerchantConnectorDetails,
api_models::admin::MerchantConnectorWebhookDetails,
api_models::admin::ProfileCreate,
api_models::admin::ProfileResponse,
api_models::admin::BusinessPaymentLinkConfig,
api_models::admin::PaymentLinkBackgroundImageConfig,
api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
api_models::admin::PaymentLinkTransactionDetails,
api_models::admin::TransactionDetailsUiConfiguration,
api_models::disputes::DisputeResponse,
api_models::disputes::DisputeResponsePaymentsRetrieve,
api_models::gsm::GsmCreateRequest,
api_models::gsm::GsmRetrieveRequest,
api_models::gsm::GsmUpdateRequest,
api_models::gsm::GsmDeleteRequest,
api_models::gsm::GsmDeleteResponse,
api_models::gsm::GsmResponse,
api_models::enums::GsmDecision,
api_models::enums::GsmFeature,
common_types::domain::GsmFeatureData,
common_types::domain::RetryFeatureData,
api_models::payments::NullObject,
api_models::payments::AddressDetails,
api_models::payments::BankDebitData,
api_models::payments::AliPayQr,
api_models::payments::PaymentAttemptFeatureMetadata,
api_models::payments::PaymentAttemptRevenueRecoveryData,
api_models::payments::BillingConnectorPaymentMethodDetails,
api_models::payments::RecordAttemptErrorDetails,
api_models::payments::BillingConnectorAdditionalCardInfo,
api_models::payments::AliPayRedirection,
api_models::payments::MomoRedirection,
api_models::payments::TouchNGoRedirection,
api_models::payments::GcashRedirection,
api_models::payments::KakaoPayRedirection,
api_models::payments::AliPayHkRedirection,
api_models::payments::GoPayRedirection,
api_models::payments::MbWayRedirection,
api_models::payments::MobilePayRedirection,
api_models::payments::WeChatPayRedirection,
api_models::payments::WeChatPayQr,
api_models::payments::BankDebitBilling,
api_models::payments::CryptoData,
api_models::payments::RewardData,
api_models::payments::UpiData,
api_models::payments::UpiCollectData,
api_models::payments::UpiIntentData,
api_models::payments::UpiQrData,
api_models::payments::VoucherData,
api_models::payments::BoletoVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::Address,
api_models::payments::VoucherData,
api_models::payments::JCSVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::BankRedirectData,
api_models::payments::RealTimePaymentData,
api_models::payments::BankRedirectBilling,
api_models::payments::BankRedirectBilling,
api_models::payments::ConnectorMetadata,
api_models::payments::FeatureMetadata,
api_models::payments::SdkType,
api_models::payments::ApplepayConnectorMetadataRequest,
api_models::payments::SessionTokenInfo,
api_models::payments::PaymentProcessingDetailsAt,
api_models::payments::ApplepayInitiative,
api_models::payments::PaymentProcessingDetails,
api_models::payments::PaymentMethodDataResponseWithBilling,
api_models::payments::PaymentMethodDataResponse,
api_models::payments::CardResponse,
api_models::payments::PaylaterResponse,
api_models::payments::KlarnaSdkPaymentMethodResponse,
api_models::payments::SwishQrData,
api_models::payments::RevolutPayData,
api_models::payments::AirwallexData,
api_models::payments::BraintreeData,
api_models::payments::NoonData,
api_models::payments::OrderDetailsWithAmount,
api_models::payments::NextActionType,
api_models::payments::WalletData,
api_models::payments::NextActionData,
api_models::payments::PayLaterData,
api_models::payments::MandateData,
api_models::payments::PhoneDetails,
api_models::payments::PaymentMethodData,
api_models::payments::PaymentMethodDataRequest,
api_models::payments::SplitPaymentMethodDataRequest,
api_models::payments::MandateType,
api_models::payments::MandateAmountData,
api_models::payments::Card,
api_models::payments::CardRedirectData,
api_models::payments::CardToken,
api_models::payments::ConnectorTokenDetails,
api_models::payments::PaymentsRequest,
api_models::payments::PaymentsResponse,
api_models::payments::PaymentsListResponseItem,
api_models::payments::PaymentsRetrieveRequest,
api_models::payments::PaymentsStatusRequest,
api_models::payments::PaymentsCaptureRequest,
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
api_models::payments::PaymentsCreateIntentRequest,
api_models::payments::PaymentsUpdateIntentRequest,
api_models::payments::PaymentsIntentResponse,
api_models::payments::PaymentAttemptListRequest,
api_models::payments::PaymentAttemptListResponse,
api_models::payments::PazeWalletData,
api_models::payments::AmountDetails,
api_models::payments::AmountDetailsUpdate,
api_models::payments::SessionToken,
api_models::payments::VaultSessionDetails,
api_models::payments::VgsSessionDetails,
api_models::payments::HyperswitchVaultSessionDetails,
api_models::payments::ApplePaySessionResponse,
api_models::payments::ThirdPartySdkSessionResponse,
api_models::payments::NoThirdPartySdkSessionResponse,
api_models::payments::SecretInfoToInitiateSdk,
api_models::payments::ApplePayPaymentRequest,
api_models::payments::ApplePayBillingContactFields,
api_models::payments::ApplePayShippingContactFields,
api_models::payments::ApplePayAddressParameters,
api_models::payments::ApplePayRecurringPaymentRequest,
api_models::payments::ApplePayRegularBillingRequest,
api_models::payments::ApplePayPaymentTiming,
api_models::payments::RecurringPaymentIntervalUnit,
api_models::payments::ApplePayRecurringDetails,
api_models::payments::ApplePayRegularBillingDetails,
api_models::payments::AmountInfo,
api_models::payments::GooglePayWalletData,
api_models::payments::PayPalWalletData,
api_models::payments::PaypalRedirection,
api_models::payments::GpayMerchantInfo,
api_models::payments::GpayAllowedPaymentMethods,
api_models::payments::GpayAllowedMethodsParameters,
api_models::payments::GpayTokenizationSpecification,
api_models::payments::GpayTokenParameters,
api_models::payments::GpayTransactionInfo,
api_models::payments::GpaySessionTokenResponse,
api_models::payments::GooglePayThirdPartySdkData,
api_models::payments::KlarnaSessionTokenResponse,
api_models::payments::PaypalSessionTokenResponse,
api_models::payments::PaypalFlow,
api_models::payments::PaypalTransactionInfo,
api_models::payments::ApplepaySessionTokenResponse,
api_models::payments::SdkNextAction,
api_models::payments::NextActionCall,
api_models::payments::SdkNextActionData,
api_models::payments::SamsungPayWalletData,
api_models::payments::WeChatPay,
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
api_models::payments::ApplepayPaymentMethod,
api_models::payments::PazeSessionTokenResponse,
api_models::payments::SamsungPaySessionTokenResponse,
api_models::payments::SamsungPayMerchantPaymentInformation,
api_models::payments::SamsungPayAmountDetails,
api_models::payments::SamsungPayAmountFormat,
api_models::payments::SamsungPayProtocolType,
api_models::payments::SamsungPayWalletCredentials,
api_models::payments::SamsungPayWebWalletData,
api_models::payments::SamsungPayAppWalletData,
api_models::payments::SamsungPayCardBrand,
api_models::payments::SamsungPayTokenData,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentListResponse,
api_models::payments::CashappQr,
api_models::payments::BankTransferData,
api_models::payments::BankTransferNextStepsData,
api_models::payments::SepaAndBacsBillingDetails,
api_models::payments::AchBillingDetails,
api_models::payments::MultibancoBillingDetails,
api_models::payments::DokuBillingDetails,
api_models::payments::BankTransferInstructions,
api_models::payments::MobilePaymentNextStepData,
api_models::payments::MobilePaymentConsent,
api_models::payments::IframeData,
api_models::payments::ReceiverDetails,
api_models::payments::AchTransfer,
api_models::payments::MultibancoTransferInstructions,
api_models::payments::DokuBankTransferInstructions,
api_models::payments::AmazonPayRedirectData,
api_models::payments::SkrillData,
api_models::payments::PayseraData,
api_models::payments::ApplePayRedirectData,
api_models::payments::ApplePayThirdPartySdkData,
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::mandates::NetworkTransactionIdAndCardDetails,
api_models::payments::GooglePaySessionResponse,
api_models::payments::GpayShippingAddressParameters,
api_models::payments::GpayBillingAddressParameters,
api_models::payments::GpayBillingAddressFormat,
api_models::payments::SepaBankTransferInstructions,
api_models::payments::BacsBankTransferInstructions,
api_models::payments::RedirectResponse,
api_models::payments::RequestSurchargeDetails,
api_models::payments::PaymentRevenueRecoveryMetadata,
api_models::payments::BillingConnectorPaymentDetails,
api_models::payments::GiftCardBalanceCheckResponse,
api_models::payments::PaymentsGiftCardBalanceCheckRequest,
api_models::enums::PaymentConnectorTransmission,
api_models::enums::TriggeredBy,
api_models::payments::PaymentAttemptResponse,
api_models::payments::PaymentAttemptRecordResponse,
api_models::payments::PaymentAttemptAmountDetails,
api_models::payments::CaptureResponse,
api_models::payments::PaymentsIncrementalAuthorizationRequest,
api_models::payments::IncrementalAuthorizationResponse,
api_models::payments::PaymentsCompleteAuthorizeRequest,
api_models::payments::PaymentsExternalAuthenticationRequest,
api_models::payments::PaymentsExternalAuthenticationResponse,
api_models::payments::SdkInformation,
api_models::payments::DeviceChannel,
api_models::payments::ThreeDsCompletionIndicator,
api_models::payments::MifinityData,
api_models::payments::ClickToPaySessionResponse,
api_models::enums::TransactionStatus,
api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payments::ThreeDsData,
api_models::payments::ThreeDsMethodData,
api_models::payments::ThreeDsMethodKey,
api_models::payments::PollConfigResponse,
api_models::payments::PollConfig,
api_models::payments::ExternalAuthenticationDetailsResponse,
api_models::payments::ExtendedCardInfo,
api_models::payments::PaymentsConfirmIntentRequest,
api_models::payments::AmountDetailsResponse,
api_models::payments::BankCodeResponse,
api_models::payments::Order,
api_models::payments::SortOn,
api_models::payments::SortBy,
api_models::payments::PaymentMethodListResponseForPayments,
api_models::payments::ResponsePaymentMethodTypesForPayments,
api_models::payment_methods::CardNetworkTokenizeRequest,
api_models::payment_methods::CardNetworkTokenizeResponse,
api_models::payment_methods::CardType,
api_models::payments::AmazonPaySessionTokenData,
api_models::payments::AmazonPayMerchantCredentials,
api_models::payments::AmazonPayWalletData,
api_models::payments::AmazonPaySessionTokenResponse,
api_models::payments::AmazonPayPaymentIntent,
api_models::payments::AmazonPayDeliveryOptions,
api_models::payments::AmazonPayDeliveryPrice,
api_models::payments::AmazonPayShippingMethod,
api_models::payment_methods::RequiredFieldInfo,
api_models::payment_methods::MaskedBankDetails,
api_models::payment_methods::SurchargeDetailsResponse,
api_models::payment_methods::SurchargeResponse,
api_models::payment_methods::SurchargePercentage,
api_models::payment_methods::PaymentMethodCollectLinkRequest,
api_models::payment_methods::PaymentMethodCollectLinkResponse,
api_models::payment_methods::PaymentMethodSubtypeSpecificData,
api_models::payment_methods::PaymentMethodSessionRequest,
api_models::payment_methods::PaymentMethodSessionResponse,
api_models::payment_methods::PaymentMethodsSessionUpdateRequest,
api_models::payment_methods::NetworkTokenResponse,
api_models::payment_methods::NetworkTokenDetailsPaymentMethod,
api_models::payment_methods::NetworkTokenDetailsResponse,
api_models::payment_methods::TokenDataResponse,
api_models::payment_methods::TokenDetailsResponse,
api_models::payment_methods::TokenizeCardRequest,
api_models::payment_methods::TokenizeDataRequest,
api_models::payment_methods::TokenizePaymentMethodRequest,
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::payments::AmountFilter,
api_models::mandates::MandateRevokedResponse,
api_models::mandates::MandateResponse,
api_models::mandates::MandateCardDetails,
api_models::mandates::RecurringDetails,
api_models::mandates::ProcessorPaymentToken,
api_models::ephemeral_key::ClientSecretResponse,
api_models::payments::CustomerDetails,
api_models::payments::GiftCardData,
api_models::payments::GiftCardDetails,
api_models::payments::BHNGiftCardDetails,
api_models::payments::MobilePaymentData,
api_models::payments::MobilePaymentResponse,
api_models::payments::Address,
api_models::payouts::CardPayout,
api_models::payouts::Wallet,
api_models::payouts::Paypal,
api_models::payouts::BankRedirect,
api_models::payouts::Interac,
api_models::payouts::Venmo,
api_models::payouts::AchBankTransfer,
api_models::payouts::BacsBankTransfer,
api_models::payouts::SepaBankTransfer,
api_models::payouts::PixBankTransfer,
api_models::payouts::PayoutRequest,
api_models::payouts::PayoutAttemptResponse,
api_models::payouts::PayoutActionRequest,
api_models::payouts::PayoutCreateRequest,
api_models::payouts::PayoutCreateResponse,
api_models::payouts::PayoutListConstraints,
api_models::payouts::PayoutListFilterConstraints,
api_models::payouts::PayoutListResponse,
api_models::payouts::PayoutRetrieveBody,
api_models::payouts::PayoutRetrieveRequest,
api_models::payouts::PayoutMethodData,
api_models::payouts::PayoutMethodDataResponse,
api_models::payouts::PayoutLinkResponse,
api_models::payouts::Bank,
api_models::payouts::ApplePayDecrypt,
api_models::payouts::PayoutCreatePayoutLinkConfig,
api_models::enums::PayoutEntityType,
api_models::enums::PayoutSendPriority,
api_models::enums::PayoutStatus,
api_models::enums::PayoutType,
api_models::enums::TransactionType,
api_models::enums::PresenceOfCustomerDuringPayment,
api_models::enums::MitExemptionRequest,
api_models::enums::EnablePaymentLinkRequest,
api_models::enums::RequestIncrementalAuthorization,
api_models::enums::SplitTxnsEnabled,
api_models::enums::External3dsAuthenticationRequest,
api_models::enums::TaxCalculationOverride,
api_models::enums::SurchargeCalculationOverride,
api_models::payments::FrmMessage,
api_models::webhooks::OutgoingWebhook,
api_models::webhooks::OutgoingWebhookContent,
api_models::enums::EventClass,
api_models::enums::EventType,
api_models::enums::DecoupledAuthenticationType,
api_models::enums::AuthenticationStatus,
api_models::enums::UpdateActiveAttempt,
api_models::admin::MerchantAccountResponse,
api_models::admin::MerchantConnectorId,
api_models::admin::MerchantDetails,
api_models::admin::ToggleKVRequest,
api_models::admin::ToggleKVResponse,
api_models::admin::WebhookDetails,
api_models::api_keys::ApiKeyExpiration,
api_models::api_keys::CreateApiKeyRequest,
api_models::api_keys::CreateApiKeyResponse,
api_models::api_keys::RetrieveApiKeyResponse,
api_models::api_keys::RevokeApiKeyResponse,
api_models::api_keys::UpdateApiKeyRequest,
api_models::payments::RetrievePaymentLinkRequest,
api_models::payments::PaymentLinkResponse,
api_models::payments::RetrievePaymentLinkResponse,
api_models::payments::PaymentLinkInitiateRequest,
api_models::payouts::PayoutLinkInitiateRequest,
api_models::payments::ExtendedCardInfoResponse,
api_models::payments::GooglePayAssuranceDetails,
api_models::routing::RoutingConfigRequest,
api_models::routing::RoutingDictionaryRecord,
api_models::routing::RoutingKind,
api_models::routing::RoutableConnectorChoice,
api_models::routing::LinkedRoutingConfigRetrieveResponse,
api_models::routing::RoutingRetrieveResponse,
api_models::routing::ProfileDefaultRoutingConfig,
api_models::routing::MerchantRoutingAlgorithm,
api_models::routing::RoutingAlgorithmKind,
api_models::routing::RoutingDictionary,
api_models::routing::DynamicRoutingConfigParams,
api_models::routing::SuccessBasedRoutingConfig,
api_models::routing::SuccessRateSpecificityLevel,
api_models::routing::CurrentBlockThreshold,
api_models::open_router::DecisionEngineSuccessRateData,
api_models::routing::ContractBasedTimeScale,
api_models::routing::LabelInformation,
api_models::routing::ContractBasedRoutingConfig,
api_models::routing::ContractBasedRoutingConfigBody,
api_models::open_router::DecisionEngineGatewayWiseExtraScore,
api_models::open_router::DecisionEngineSRSubLevelInputConfig,
api_models::open_router::DecisionEngineEliminationData,
api_models::routing::SuccessBasedRoutingConfigBody,
api_models::routing::RoutingAlgorithmWrapper,
api_models::routing::EliminationRoutingConfig,
api_models::open_router::DecisionEngineEliminationData,
api_models::routing::EliminationAnalyserConfig,
api_models::routing::DynamicRoutingAlgorithm,
api_models::routing::StaticRoutingAlgorithm,
api_models::routing::StraightThroughAlgorithm,
api_models::routing::ConnectorVolumeSplit,
api_models::routing::ConnectorSelection,
api_models::routing::ast::RoutableChoiceKind,
api_models::routing::ProgramThreeDsDecisionRule,
api_models::routing::RuleThreeDsDecisionRule,
api_models::enums::RoutableConnectors,
api_models::routing::ast::ProgramConnectorSelection,
api_models::routing::ast::RuleConnectorSelection,
api_models::routing::ast::IfStatement,
api_models::routing::ast::Comparison,
api_models::routing::ast::ComparisonType,
api_models::routing::ast::ValueType,
api_models::routing::ast::MetadataValue,
api_models::routing::ast::NumberComparison,
api_models::routing::RoutingAlgorithmId,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payments::PaymentLinkStatus,
api_models::blocklist::BlocklistRequest,
api_models::blocklist::BlocklistResponse,
api_models::blocklist::ToggleBlocklistResponse,
api_models::blocklist::ListBlocklistQuery,
api_models::enums::BlocklistDataKind,
api_models::enums::ErrorCategory,
api_models::webhook_events::EventListItemResponse,
api_models::webhook_events::EventRetrieveResponse,
api_models::webhook_events::OutgoingWebhookRequestContent,
api_models::webhook_events::OutgoingWebhookResponseContent,
api_models::enums::WebhookDeliveryAttempt,
api_models::enums::PaymentChargeType,
api_models::enums::StripeChargeType,
api_models::payments::CustomerDetailsResponse,
api_models::payments::OpenBankingData,
api_models::payments::OpenBankingSessionToken,
api_models::payments::BankDebitResponse,
api_models::payments::BankRedirectResponse,
api_models::payments::BankTransferResponse,
api_models::payments::CardRedirectResponse,
api_models::payments::CardTokenResponse,
api_models::payments::CryptoResponse,
api_models::payments::GiftCardResponse,
api_models::payments::OpenBankingResponse,
api_models::payments::RealTimePaymentDataResponse,
api_models::payments::UpiResponse,
api_models::payments::VoucherResponse,
api_models::payments::additional_info::CardTokenAdditionalData,
api_models::payments::additional_info::BankDebitAdditionalData,
api_models::payments::additional_info::AchBankDebitAdditionalData,
api_models::payments::additional_info::BacsBankDebitAdditionalData,
api_models::payments::additional_info::BecsBankDebitAdditionalData,
api_models::payments::additional_info::SepaBankDebitAdditionalData,
api_models::payments::additional_info::BankRedirectDetails,
api_models::payments::additional_info::BancontactBankRedirectAdditionalData,
api_models::payments::additional_info::BlikBankRedirectAdditionalData,
api_models::payments::additional_info::GiropayBankRedirectAdditionalData,
api_models::payments::additional_info::BankTransferAdditionalData,
api_models::payments::additional_info::PixBankTransferAdditionalData,
api_models::payments::additional_info::LocalBankTransferAdditionalData,
api_models::payments::additional_info::GiftCardAdditionalData,
api_models::payments::additional_info::GivexGiftCardAdditionalData,
api_models::payments::additional_info::UpiAdditionalData,
api_models::payments::additional_info::UpiCollectAdditionalData,
api_models::payments::additional_info::WalletAdditionalDataForCard,
api_models::payments::WalletResponse,
api_models::payments::WalletResponseData,
api_models::payments::PaymentsDynamicTaxCalculationRequest,
api_models::payments::PaymentsDynamicTaxCalculationResponse,
api_models::payments::DisplayAmountOnSdk,
api_models::payments::ErrorDetails,
api_models::payments::CtpServiceDetails,
api_models::payments::AdyenConnectorMetadata,
api_models::payments::AdyenTestingData,
api_models::feature_matrix::FeatureMatrixListResponse,
api_models::feature_matrix::FeatureMatrixRequest,
api_models::feature_matrix::ConnectorFeatureMatrixResponse,
api_models::feature_matrix::PaymentMethodSpecificFeatures,
api_models::feature_matrix::CardSpecificFeatures,
api_models::feature_matrix::SupportedPaymentMethod,
api_models::payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod,
api_models::payment_methods::PaymentMethodSessionDeleteSavedPaymentMethod,
common_utils::types::BrowserInformation,
api_models::enums::TokenizationType,
api_models::enums::NetworkTokenizationToggle,
api_models::payments::PaymentAmountDetailsResponse,
api_models::payment_methods::PaymentMethodSessionConfirmRequest,
api_models::payment_methods::PaymentMethodSessionResponse,
api_models::payment_methods::AuthenticationDetails,
api_models::process_tracker::revenue_recovery::RevenueRecoveryResponse,
api_models::enums::RevenueRecoveryAlgorithmType,
api_models::enums::ProcessTrackerStatus,
api_models::proxy::ProxyRequest,
api_models::proxy::ProxyResponse,
api_models::proxy::TokenType,
routes::payments::ForceSync,
api_models::tokenization::GenericTokenizationRequest,
api_models::tokenization::GenericTokenizationResponse,
api_models::tokenization::DeleteTokenDataRequest,
api_models::tokenization::DeleteTokenDataResponse,
)),
modifiers(&SecurityAddon)
)]
// Bypass clippy lint for not being constructed
#[allow(dead_code)]
pub(crate) struct ApiDoc;
struct SecurityAddon;
impl utoipa::Modify for SecurityAddon {
fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
use utoipa::openapi::security::{ApiKey, ApiKeyValue, SecurityScheme};
if let Some(components) = openapi.components.as_mut() {
components.add_security_schemes_from_iter([
(
"api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Use the API key created under your merchant account from the HyperSwitch dashboard. API key is used to authenticate API requests from your merchant server only. Don't expose this key on a website or embed it in a mobile application."
))),
),
(
"admin_api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Admin API keys allow you to perform some privileged actions such as \
creating a merchant account and Connector account."
))),
),
(
"publishable_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Publishable keys are a type of keys that can be public and have limited \
scope of usage."
))),
),
(
"ephemeral_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Ephemeral keys provide temporary access to singular data, such as access \
to a single customer object for a short period of time."
))),
),
]);
}
}
}
</file>
|
{
"crate": "openapi",
"file": "crates/openapi/src/openapi_v2.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 9321
}
|
large_file_4201290751811159500
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: openapi
File: crates/openapi/src/routes/refunds.rs
</path>
<file>
/// Refunds - Create
///
/// Creates a refund against an already processed payment. In case of some processors, you can even opt to refund only a partial amount multiple times until the original charge amount has been refunded
#[utoipa::path(
post,
path = "/refunds",
request_body(
content = RefundRequest,
examples(
(
"Create an instant refund to refund the whole amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant"
})
)
),
(
"Create an instant refund to refund partial amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant",
"amount": 654
})
)
),
(
"Create an instant refund with reason" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant",
"amount": 6540,
"reason": "Customer returned product"
})
)
),
)
),
responses(
(status = 200, description = "Refund created", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Create a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_create() {}
/// Refunds - Retrieve
///
/// Retrieves a Refund. This may be used to get the status of a previously initiated refund
#[utoipa::path(
get,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_retrieve() {}
/// Refunds - Retrieve (POST)
///
/// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/refunds/sync",
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
pub async fn refunds_retrieve_with_body() {}
/// Refunds - Update
///
/// Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields
#[utoipa::path(
post,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
request_body(
content = RefundUpdateRequest,
examples(
(
"Update refund reason" = (
value = json!({
"reason": "Paid by mistake"
})
)
),
)
),
responses(
(status = 200, description = "Refund updated", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Update a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_update() {}
/// Refunds - List
///
/// Lists all the refunds associated with the merchant, or for a specific payment if payment_id is provided
#[utoipa::path(
post,
path = "/refunds/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub fn refunds_list() {}
/// Refunds - List For the Given profiles
///
/// Lists all the refunds associated with the merchant or a payment_id if payment_id is not provided
#[utoipa::path(
post,
path = "/refunds/profile/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds for the given Profiles",
security(("api_key" = []))
)]
pub fn refunds_list_profile() {}
/// Refunds - Filter
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[utoipa::path(
post,
path = "/refunds/filter",
request_body=TimeRange,
responses(
(status = 200, description = "List of filters", body = RefundListMetaData),
),
tag = "Refunds",
operation_id = "List all filters for Refunds",
security(("api_key" = []))
)]
pub async fn refunds_filter_list() {}
/// Refunds - Create
///
/// Creates a refund against an already processed payment. In case of some processors, you can even opt to refund only a partial amount multiple times until the original charge amount has been refunded
#[utoipa::path(
post,
path = "/v2/refunds",
request_body(
content = RefundsCreateRequest,
examples(
(
"Create an instant refund to refund the whole amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant"
})
)
),
(
"Create an instant refund to refund partial amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant",
"amount": 654
})
)
),
(
"Create an instant refund with reason" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant",
"amount": 6540,
"reason": "Customer returned product"
})
)
),
)
),
responses(
(status = 200, description = "Refund created", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Create a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_create() {}
/// Refunds - Metadata Update
///
/// Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields
#[utoipa::path(
put,
path = "/v2/refunds/{id}/update-metadata",
params(
("id" = String, Path, description = "The identifier for refund")
),
request_body(
content = RefundMetadataUpdateRequest,
examples(
(
"Update refund reason" = (
value = json!({
"reason": "Paid by mistake"
})
)
)
)
),
responses(
(status = 200, description = "Refund updated", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Update Refund Metadata and Reason",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_metadata_update() {}
/// Refunds - Retrieve
///
/// Retrieves a Refund. This may be used to get the status of a previously initiated refund
#[utoipa::path(
get,
path = "/v2/refunds/{id}",
params(
("id" = String, Path, description = "The identifier for refund")
),
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_retrieve() {}
/// Refunds - List
///
/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
#[utoipa::path(
post,
path = "/v2/refunds/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub fn refunds_list() {}
</file>
|
{
"crate": "openapi",
"file": "crates/openapi/src/routes/refunds.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2097
}
|
large_file_2652651925533406841
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: openapi
File: crates/openapi/src/routes/merchant_account.rs
</path>
<file>
#[cfg(feature = "v1")]
/// Merchant Account - Create
///
/// Create a new account for a *merchant* and the *merchant* could be a seller or retailer or client who likes to receive and send payments.
#[utoipa::path(
post,
path = "/accounts",
request_body(
content = MerchantAccountCreate,
examples(
(
"Create a merchant account with minimal fields" = (
value = json!({"merchant_id": "merchant_abc"})
)
),
(
"Create a merchant account with webhook url" = (
value = json!({
"merchant_id": "merchant_abc",
"webhook_details" : {
"webhook_url": "https://webhook.site/a5c54f75-1f7e-4545-b781-af525b7e37a0"
}
})
)
),
(
"Create a merchant account with return url" = (
value = json!({"merchant_id": "merchant_abc",
"return_url": "https://example.com"})
)
)
)
),
responses(
(status = 200, description = "Merchant Account Created", body = MerchantAccountResponse),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "Create a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_create() {}
#[cfg(feature = "v2")]
/// Merchant Account - Create
///
/// Create a new account for a *merchant* and the *merchant* could be a seller or retailer or client who likes to receive and send payments.
///
/// Before creating the merchant account, it is mandatory to create an organization.
#[utoipa::path(
post,
path = "/v2/merchant-accounts",
params(
(
"X-Organization-Id" = String, Header,
description = "Organization ID for which the merchant account has to be created.",
example = json!({"X-Organization-Id": "org_abcdefghijklmnop"})
),
),
request_body(
content = MerchantAccountCreate,
examples(
(
"Create a merchant account with minimal fields" = (
value = json!({
"merchant_name": "Cloth Store",
})
)
),
(
"Create a merchant account with merchant details" = (
value = json!({
"merchant_name": "Cloth Store",
"merchant_details": {
"primary_contact_person": "John Doe",
"primary_email": "[email protected]"
}
})
)
),
(
"Create a merchant account with metadata" = (
value = json!({
"merchant_name": "Cloth Store",
"metadata": {
"key_1": "John Doe",
"key_2": "Trends"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Account Created", body = MerchantAccountResponse),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "Create a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_create() {}
#[cfg(feature = "v1")]
/// Merchant Account - Retrieve
///
/// Retrieve a *merchant* account details.
#[utoipa::path(
get,
path = "/accounts/{account_id}",
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Retrieved", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Retrieve a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn retrieve_merchant_account() {}
#[cfg(feature = "v2")]
/// Merchant Account - Retrieve
///
/// Retrieve a *merchant* account details.
#[utoipa::path(
get,
path = "/v2/merchant-accounts/{id}",
params (("id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Retrieved", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Retrieve a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_retrieve() {}
#[cfg(feature = "v1")]
/// Merchant Account - Update
///
/// Updates details of an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc
#[utoipa::path(
post,
path = "/accounts/{account_id}",
request_body (
content = MerchantAccountUpdate,
examples(
(
"Update merchant name" = (
value = json!({
"merchant_id": "merchant_abc",
"merchant_name": "merchant_name"
})
)
),
("Update webhook url" = (
value = json!({
"merchant_id": "merchant_abc",
"webhook_details": {
"webhook_url": "https://webhook.site/a5c54f75-1f7e-4545-b781-af525b7e37a0"
}
})
)
),
("Update return url" = (
value = json!({
"merchant_id": "merchant_abc",
"return_url": "https://example.com"
})
)))),
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Updated", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Update a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn update_merchant_account() {}
#[cfg(feature = "v2")]
/// Merchant Account - Update
///
/// Updates details of an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc
#[utoipa::path(
put,
path = "/v2/merchant-accounts/{id}",
request_body (
content = MerchantAccountUpdate,
examples(
(
"Update merchant name" = (
value = json!({
"merchant_id": "merchant_abc",
"merchant_name": "merchant_name"
})
)
),
("Update Merchant Details" = (
value = json!({
"merchant_details": {
"primary_contact_person": "John Doe",
"primary_email": "[email protected]"
}
})
)
),
)),
params (("id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Updated", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Update a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_update() {}
#[cfg(feature = "v1")]
/// Merchant Account - Delete
///
/// Delete a *merchant* account
#[utoipa::path(
delete,
path = "/accounts/{account_id}",
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Deleted", body = MerchantAccountDeleteResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Delete a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn delete_merchant_account() {}
#[cfg(feature = "v1")]
/// Merchant Account - KV Status
///
/// Toggle KV mode for the Merchant Account
#[utoipa::path(
post,
path = "/accounts/{account_id}/kv",
request_body (
content = ToggleKVRequest,
examples (
("Enable KV for Merchant" = (
value = json!({
"kv_enabled": "true"
})
)),
("Disable KV for Merchant" = (
value = json!({
"kv_enabled": "false"
})
)))
),
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "KV mode is enabled/disabled for Merchant Account", body = ToggleKVResponse),
(status = 400, description = "Invalid data"),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Enable/Disable KV for a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_kv_status() {}
/// Merchant Connector - List
///
/// List Merchant Connector Details for the merchant
#[utoipa::path(
get,
path = "/accounts/{account_id}/profile/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "List all Merchant Connectors for The given Profile",
security(("admin_api_key" = []))
)]
pub async fn payment_connector_list_profile() {}
#[cfg(feature = "v2")]
/// Merchant Account - Profile List
///
/// List profiles for an Merchant
#[utoipa::path(
get,
path = "/v2/merchant-accounts/{id}/profiles",
params (("id" = String, Path, description = "The unique identifier for the Merchant")),
responses(
(status = 200, description = "profile list retrieved successfully", body = Vec<ProfileResponse>),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "List Profiles",
security(("admin_api_key" = []))
)]
pub async fn profiles_list() {}
</file>
|
{
"crate": "openapi",
"file": "crates/openapi/src/routes/merchant_account.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2347
}
|
large_file_8311590646376279773
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: openapi
File: crates/openapi/src/routes/profile.rs
</path>
<file>
// ******************************************** V1 profile routes ******************************************** //
#[cfg(feature = "v1")]
/// Profile - Create
///
/// Creates a new *profile* for a merchant
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile",
params (
("account_id" = String, Path, description = "The unique identifier for the merchant account")
),
request_body(
content = ProfileCreate,
examples(
(
"Create a profile with minimal fields" = (
value = json!({})
)
),
(
"Create a profile with profile name" = (
value = json!({
"profile_name": "shoe_business"
})
)
)
)
),
responses(
(status = 200, description = "Profile Created", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Create A Profile",
security(("api_key" = []))
)]
pub async fn profile_create() {}
#[cfg(feature = "v1")]
/// Profile - Update
///
/// Update the *profile*
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
request_body(
content = ProfileCreate,
examples(
(
"Update profile with profile name fields" = (
value = json!({
"profile_name" : "shoe_business"
})
)
)
)),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Update a Profile",
security(("api_key" = []))
)]
pub async fn profile_update() {}
#[cfg(feature = "v1")]
/// Profile - Retrieve
///
/// Retrieve existing *profile*
#[utoipa::path(
get,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Retrieve a Profile",
security(("api_key" = []))
)]
pub async fn profile_retrieve() {}
// ******************************************** Common profile routes ******************************************** //
/// Profile - Delete
///
/// Delete the *profile*
#[utoipa::path(
delete,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
responses(
(status = 200, description = "Profiles Deleted", body = bool),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Delete the Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_delete() {}
/// Profile - List
///
/// Lists all the *profiles* under a merchant
#[utoipa::path(
get,
path = "/account/{account_id}/business_profile",
params (
("account_id" = String, Path, description = "Merchant Identifier"),
),
responses(
(status = 200, description = "Profiles Retrieved", body = Vec<ProfileResponse>)
),
tag = "Profile",
operation_id = "List Profiles",
security(("api_key" = []))
)]
pub async fn profile_list() {}
// ******************************************** V2 profile routes ******************************************** //
#[cfg(feature = "v2")]
/// Profile - Create
///
/// Creates a new *profile* for a merchant
#[utoipa::path(
post,
path = "/v2/profiles",
params(
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
request_body(
content = ProfileCreate,
examples(
(
"Create a profile with profile name" = (
value = json!({
"profile_name": "shoe_business"
})
)
)
)
),
responses(
(status = 200, description = "Account Created", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Create A Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_create() {}
#[cfg(feature = "v2")]
/// Profile - Update
///
/// Update the *profile*
#[utoipa::path(
put,
path = "/v2/profiles/{id}",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
request_body(
content = ProfileCreate,
examples(
(
"Update profile with profile name fields" = (
value = json!({
"profile_name" : "shoe_business"
})
)
)
)),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Update a Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_update() {}
#[cfg(feature = "v2")]
/// Profile - Activate routing algorithm
///
/// Activates a routing algorithm under a profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/activate-routing-algorithm",
request_body ( content = RoutingAlgorithmId,
examples( (
"Activate a routing algorithm" = (
value = json!({
"routing_algorithm_id": "routing_algorithm_123"
})
)
))),
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Routing Algorithm is activated", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Bad request")
),
tag = "Profile",
operation_id = "Activates a routing algorithm under a profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_link_config() {}
#[cfg(feature = "v2")]
/// Profile - Deactivate routing algorithm
///
/// Deactivates a routing algorithm under a profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/deactivate-routing-algorithm",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully deactivated routing config", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 403, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Profile",
operation_id = " Deactivates a routing algorithm under a profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_unlink_config() {}
#[cfg(feature = "v2")]
/// Profile - Update Default Fallback Routing Algorithm
///
/// Update the default fallback routing algorithm for the profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/fallback-routing",
request_body = Vec<RoutableConnectorChoice>,
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully updated the default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Profile",
operation_id = "Update the default fallback routing algorithm for the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve
///
/// Retrieve existing *profile*
#[utoipa::path(
get,
path = "/v2/profiles/{id}",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Retrieve a Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_retrieve() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve Active Routing Algorithm
///_
/// Retrieve active routing algorithm under the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/routing-algorithm",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
("limit" = Option<u16>, Query, description = "The number of records of the algorithms to be returned"),
("offset" = Option<u8>, Query, description = "The record offset of the algorithm from which to start gathering the results")),
responses(
(status = 200, description = "Successfully retrieved active config", body = LinkedRoutingConfigRetrieveResponse),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Profile",
operation_id = "Retrieve the active routing algorithm under the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_linked_config() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve Default Fallback Routing Algorithm
///
/// Retrieve the default fallback routing algorithm for the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/fallback-routing",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully retrieved default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error")
),
tag = "Profile",
operation_id = "Retrieve the default fallback routing algorithm for the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config() {}
/// Profile - Connector Accounts List
///
/// List Connector Accounts for the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/connector-accounts",
params(
("id" = String, Path, description = "The unique identifier for the business profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Business Profile",
operation_id = "List all Merchant Connectors for Profile",
security(("admin_api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn connector_list() {}
</file>
|
{
"crate": "openapi",
"file": "crates/openapi/src/routes/profile.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2908
}
|
large_file_-7952969877195407061
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: openapi
File: crates/openapi/src/routes/payment_method.rs
</path>
<file>
/// PaymentMethods - Create
///
/// Creates and stores a payment method against a customer.
/// In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/payment_methods",
request_body (
content = PaymentMethodCreate,
examples (( "Save a card" =(
value =json!( {
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4242424242424242",
"card_exp_month": "11",
"card_exp_year": "25",
"card_holder_name": "John Doe"
},
"customer_id": "{{customer_id}}"
})
)))
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data")
),
tag = "Payment Methods",
operation_id = "Create a Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn create_payment_method_api() {}
/// List payment methods for a Merchant
///
/// Lists the applicable payment methods for a particular Merchant ID.
/// Use the client secret and publishable key authorization to list all relevant payment methods of the merchant for the payment corresponding to the client secret.
#[utoipa::path(
get,
path = "/account/payment_methods",
params (
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = PaymentMethodListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Merchant",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn list_payment_method_api() {}
/// List payment methods for a Customer
///
/// Lists all the applicable payment methods for a particular Customer ID.
#[utoipa::path(
get,
path = "/customers/{customer_id}/payment_methods",
params (
("customer_id" = String, Path, description = "The unique identifier for the customer account"),
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn list_customer_payment_method_api() {}
/// List customer saved payment methods for a Payment
///
/// Lists all the applicable payment methods for a particular payment tied to the `client_secret`.
#[utoipa::path(
get,
path = "/customers/payment_methods",
params (
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List Customer Payment Methods via Client Secret",
security(("publishable_key" = []))
)]
pub async fn list_customer_payment_method_api_client() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Retrieve a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
/// This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.
#[utoipa::path(
post,
path = "/payment_methods/{method_id}/update",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
request_body = PaymentMethodUpdate,
responses(
(status = 200, description = "Payment Method updated", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Update a Payment method",
security(("api_key" = []), ("publishable_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method deleted", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Delete a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_delete_api() {}
/// Payment Method - Set Default Payment Method for Customer
///
/// Set the Payment Method as Default for the Customer.
#[utoipa::path(
post,
path = "/{customer_id}/payment_methods/{payment_method_id}/default",
params (
("customer_id" = String,Path, description ="The unique identifier for the Customer"),
("payment_method_id" = String,Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ),
(status = 400, description = "Payment Method has already been set as default for that customer"),
(status = 404, description = "Payment Method not found for the customer")
),
tag = "Payment Methods",
operation_id = "Set the Payment Method as Default",
security(("ephemeral_key" = []))
)]
pub async fn default_payment_method_set_api() {}
/// Payment Method - Create Intent
///
/// Creates a payment method for customer with billing information and other metadata.
#[utoipa::path(
post,
path = "/v2/payment-methods/create-intent",
request_body(
content = PaymentMethodIntentCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_intent_api() {}
/// Payment Method - Confirm Intent
///
/// Update a payment method with customer's payment method related information.
#[utoipa::path(
post,
path = "/v2/payment-methods/{id}/confirm-intent",
request_body(
content = PaymentMethodIntentConfirm,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Confirmed", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Confirm Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn confirm_payment_method_intent_api() {}
/// Payment Method - Create
///
/// Creates and stores a payment method against a customer. In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/v2/payment-methods",
request_body(
content = PaymentMethodCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_api() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Retrieve Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
#[utoipa::path(
patch,
path = "/v2/payment-methods/{id}/update-saved-payment-method",
request_body(
content = PaymentMethodUpdate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Update", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Update Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Delete Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_delete_api() {}
/// Payment Method - Check Network Token Status
///
/// Check the status of a network token for a saved payment method
#[utoipa::path(
get,
path = "/v2/payment-methods/{payment_method_id}/check-network-token-status",
params (
("payment_method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Network Token Status Retrieved", body = NetworkTokenStatusCheckResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Check Network Token Status",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn network_token_status_check_api() {}
/// Payment Method - List Customer Saved Payment Methods
///
/// List the payment methods saved for a customer
#[utoipa::path(
get,
path = "/v2/customers/{id}/saved-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the customer"),
),
responses(
(status = 200, description = "Payment Methods Retrieved", body = CustomerPaymentMethodsListResponse),
(status = 404, description = "Customer Not Found"),
),
tag = "Payment Methods",
operation_id = "List Customer Saved Payment Methods",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn list_customer_payment_method_api() {}
/// Payment Method Session - Create
///
/// Create a payment method session for a customer
/// This is used to list the saved payment methods for the customer
/// The customer can also add a new payment method using this session
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/payment-method-sessions",
request_body(
content = PaymentMethodSessionRequest,
examples (( "Create a payment method session with customer_id" = (
value =json!( {
"customer_id": "12345_cus_abcdefghijklmnopqrstuvwxyz"
})
)))
),
responses(
(status = 200, description = "Create the payment method session", body = PaymentMethodSessionResponse),
(status = 400, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Create a payment method session",
security(("api_key" = []))
)]
pub fn payment_method_session_create() {}
/// Payment Method Session - Retrieve
///
/// Retrieve the payment method session
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-sessions/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodSessionResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Retrieve the payment method session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_retrieve() {}
/// Payment Method Session - List Payment Methods
///
/// List payment methods for the given payment method session.
/// This endpoint lists the enabled payment methods for the profile and the saved payment methods of the customer.
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-sessions/{id}/list-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodListResponseForSession),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "List Payment methods for a Payment Method Session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_list_payment_methods() {}
/// Payment Method Session - Update a saved payment method
///
/// Update a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
put,
path = "/v2/payment-method-sessions/{id}/update-saved-payment-method",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionUpdateSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
"payment_method_data": {
"card": {
"card_holder_name": "Narayan Bhat"
}
}
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Update a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_update_saved_payment_method() {}
/// Payment Method Session - Delete a saved payment method
///
/// Delete a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/payment-method-sessions/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionDeleteSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodDeleteResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Delete a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_delete_saved_payment_method() {}
/// Card network tokenization - Create using raw card data
///
/// Create a card network token for a customer and store it as a payment method.
/// This API expects raw card details for creating a network token with the card networks.
#[utoipa::path(
post,
path = "/payment_methods/tokenize-card",
request_body = CardNetworkTokenizeRequest,
responses(
(status = 200, description = "Payment Method Created", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_api() {}
/// Card network tokenization - Create using existing payment method
///
/// Create a card network token for a customer for an existing payment method.
/// This API expects an existing payment method ID for a card.
#[utoipa::path(
post,
path = "/payment_methods/{id}/tokenize-card",
request_body = CardNetworkTokenizeRequest,
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Updated", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token using Payment Method ID",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_using_pm_api() {}
/// Payment Method Session - Confirm a payment method session
///
/// **Confirms a payment method session object with the payment method data**
#[utoipa::path(
post,
path = "/v2/payment-method-sessions/{id}/confirm",
params (("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentMethodSessionConfirmRequest,
examples(
(
"Confirm the payment method session with card details" = (
value = json!({
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment Method created", body = PaymentMethodResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payment Method Session",
operation_id = "Confirm the payment method session",
security(("publishable_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payment_method_session_confirm() {}
</file>
|
{
"crate": "openapi",
"file": "crates/openapi/src/routes/payment_method.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5235
}
|
large_file_-6601358676291604532
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: openapi
File: crates/openapi/src/routes/merchant_connector_account.rs
</path>
<file>
/// Merchant Connector - Create
///
/// Creates a new Merchant Connector for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.
#[cfg(feature = "v1")]
#[utoipa::path(
post,
path = "/account/{account_id}/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account")
),
request_body(
content = MerchantConnectorCreate,
examples(
(
"Create a merchant connector account with minimal fields" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
(
"Create a merchant connector account under a specific profile" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
},
"profile_id": "{{profile_id}}"
})
)
),
(
"Create a merchant account with custom connector label" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_label": "EU_adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Connector Created", body = MerchantConnectorResponse),
(status = 400, description = "Missing Mandatory fields"),
),
tag = "Merchant Connector Account",
operation_id = "Create a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_create() {}
/// Connector Account - Create
///
/// Creates a new Connector Account for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/connector-accounts",
request_body(
content = MerchantConnectorCreate,
examples(
(
"Create a merchant connector account with minimal fields" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
(
"Create a merchant connector account under a specific profile" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
},
"profile_id": "{{profile_id}}"
})
)
),
(
"Create a merchant account with custom connector label" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_label": "EU_adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Connector Created", body = MerchantConnectorResponse),
(status = 400, description = "Missing Mandatory fields"),
),
tag = "Merchant Connector Account",
operation_id = "Create a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_create() {}
/// Merchant Connector - Retrieve
///
/// Retrieves details of a Connector account
#[cfg(feature = "v1")]
#[utoipa::path(
get,
path = "/account/{account_id}/connectors/{merchant_connector_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("merchant_connector_id" = String, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Retrieve a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_retrieve() {}
/// Connector Account - Retrieve
///
/// Retrieves details of a Connector account
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/connector-accounts/{id}",
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Retrieve a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_retrieve() {}
/// Merchant Connector - List
///
/// List Merchant Connector Details for the merchant
#[utoipa::path(
get,
path = "/account/{account_id}/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorListResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "List all Merchant Connectors",
security(("api_key" = []))
)]
pub async fn connector_list() {}
/// Merchant Connector - Update
///
/// To update an existing Merchant Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector
#[cfg(feature = "v1")]
#[utoipa::path(
post,
path = "/account/{account_id}/connectors/{merchant_connector_id}",
request_body(
content = MerchantConnectorUpdate,
examples(
(
"Enable card payment method" = (
value = json! ({
"connector_type": "payment_processor",
"payment_methods_enabled": [
{
"payment_method": "card"
}
]
})
)
),
(
"Update webhook secret" = (
value = json! ({
"connector_webhook_details": {
"merchant_secret": "{{webhook_secret}}"
}
})
)
)
),
),
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("merchant_connector_id" = String, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Updated", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Update a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_update() {}
/// Connector Account - Update
///
/// To update an existing Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector
#[cfg(feature = "v2")]
#[utoipa::path(
put,
path = "/v2/connector-accounts/{id}",
request_body(
content = MerchantConnectorUpdate,
examples(
(
"Enable card payment method" = (
value = json! ({
"connector_type": "payment_processor",
"payment_methods_enabled": [
{
"payment_method": "card"
}
]
})
)
),
(
"Update webhook secret" = (
value = json! ({
"connector_webhook_details": {
"merchant_secret": "{{webhook_secret}}"
}
})
)
)
),
),
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Updated", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Update a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_update() {}
/// Merchant Connector - Delete
///
/// Delete or Detach a Merchant Connector from Merchant Account
#[cfg(feature = "v1")]
#[utoipa::path(
delete,
path = "/account/{account_id}/connectors/{merchant_connector_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("merchant_connector_id" = String, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Deleted", body = MerchantConnectorDeleteResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Delete a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_delete() {}
/// Merchant Connector - Delete
///
/// Delete or Detach a Merchant Connector from Merchant Account
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/connector-accounts/{id}",
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Deleted", body = MerchantConnectorDeleteResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Delete a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_delete() {}
</file>
|
{
"crate": "openapi",
"file": "crates/openapi/src/routes/merchant_connector_account.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2456
}
|
large_file_-1764488516704337907
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: openapi
File: crates/openapi/src/routes/payments.rs
</path>
<file>
/// Payments - Create
///
/// Creates a payment resource, which represents a customer's intent to pay.
/// This endpoint is the starting point for various payment flows:
///
#[utoipa::path(
post,
path = "/payments",
request_body(
content = PaymentsCreateRequest,
examples(
(
"01. Create a payment with minimal fields" = (
value = json!({"amount": 6540,"currency": "USD"})
)
),
(
"02. Create a payment with customer details and metadata" = (
value = json!({
"amount": 6540,
"currency": "USD",
"payment_id": "abcdefghijklmnopqrstuvwxyz",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"phone": "9123456789",
"email": "[email protected]"
},
"description": "Its my first payment request",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "some-value",
"udf2": "some-value"
}
})
)
),
(
"03. Create a 3DS payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"authentication_type": "three_ds"
})
)
),
(
"04. Create a manual capture payment (basic)" = (
value = json!({
"amount": 6540,
"currency": "USD",
"capture_method": "manual"
})
)
),
(
"05. Create a setup mandate payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer123",
"authentication_type": "no_three_ds",
"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"
}
},
"setup_future_usage": "off_session",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"single_use": {
"amount": 6540,
"currency": "USD"
}
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
})
)
),
(
"06. Create a recurring payment with mandate_id" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer",
"authentication_type": "no_three_ds",
"mandate_id": "{{mandate_id}}",
"off_session": true
})
)
),
(
"07. Create a payment and save the card" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer123",
"authentication_type": "no_three_ds",
"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"
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"setup_future_usage": "off_session"
})
)
),
(
"08. Create a payment using an already saved card's token" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"client_secret": "{{client_secret}}",
"payment_method": "card",
"payment_token": "{{payment_token}}",
"card_cvc": "123"
})
)
),
(
"09. Create a payment with billing details" = (
value = json!({
"amount": 6540,
"currency": "USD",
"customer": {
"id": "cus_abcdefgh"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
}
})
)
),
(
"10. Create a Stripe Split Payments CIT call" = (
value = json!({
"amount": 200,
"currency": "USD",
"profile_id": "pro_abcdefghijklmnop",
"confirm": true,
"capture_method": "automatic",
"amount_to_capture": 200,
"customer_id": "StripeCustomer123",
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"authentication_type": "no_three_ds",
"return_url": "https://hyperswitch.io",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "09",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9999999999",
"country_code": "+91"
}
},
"split_payments": {
"stripe_split_payment": {
"charge_type": "direct",
"application_fees": 100,
"transfer_account_id": "acct_123456789"
}
}
})
)
),
(
"11. Create a Stripe Split Payments MIT call" = (
value = json!({
"amount": 200,
"currency": "USD",
"profile_id": "pro_abcdefghijklmnop",
"customer_id": "StripeCustomer123",
"description": "Subsequent Mandate Test Payment (MIT from New CIT Demo)",
"confirm": true,
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_123456789"
},
"split_payments": {
"stripe_split_payment": {
"charge_type": "direct",
"application_fees": 11,
"transfer_account_id": "acct_123456789"
}
}
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsCreateResponseOpenApi,
examples(
("01. Response for minimal payment creation (requires payment method)" = (
value = json!({
"payment_id": "pay_syxxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"client_secret": "pay_syxxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:00:00Z",
"amount_capturable": 6540,
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:15:00Z"
})
)),
("02. Response for payment with customer details (requires payment method)" = (
value = json!({
"payment_id": "pay_custmeta_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "[email protected]",
"phone": "9123456789"
},
"description": "Its my first payment request",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "some-value",
"udf2": "some-value"
},
"client_secret": "pay_custmeta_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:05:00Z",
"ephemeral_key": {
"customer_id": "cus_abcdefgh",
"secret": "epk_ephemeralxxxxxxxxxxxx"
},
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:20:00Z"
})
)),
("03. Response for 3DS payment creation (requires payment method)" = (
value = json!({
"payment_id": "pay_3ds_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"authentication_type": "three_ds",
"client_secret": "pay_3ds_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:10:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:25:00Z"
})
)),
("04. Response for basic manual capture payment (requires payment method)" = (
value = json!({
"payment_id": "pay_manualcap_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"capture_method": "manual",
"client_secret": "pay_manualcap_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:15:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:30:00Z"
})
)),
("05. Response for successful setup mandate payment" = (
value = json!({
"payment_id": "pay_mandatesetup_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer123",
"mandate_id": "man_xxxxxxxxxxxx",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" }
},
"mandate_type": { "single_use": { "amount": 6540, "currency": "USD" } }
},
"setup_future_usage": "on_session",
"payment_method": "card",
"payment_method_data": {
"card": { "last4": "4242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }
},
"authentication_type": "no_three_ds",
"client_secret": "pay_mandatesetup_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:20:00Z",
"ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("06. Response for successful recurring payment with mandate_id" = (
value = json!({
"payment_id": "pay_recurring_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer",
"mandate_id": "{{mandate_id}}",
"off_session": true,
"payment_method": "card",
"authentication_type": "no_three_ds",
"client_secret": "pay_recurring_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:22:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("07. Response for successful payment with card saved" = (
value = json!({
"payment_id": "pay_savecard_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer123",
"setup_future_usage": "on_session",
"payment_method": "card",
"payment_method_data": {
"card": { "last4": "4242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }
},
"authentication_type": "no_three_ds",
"client_secret": "pay_savecard_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:25:00Z",
"ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx",
"payment_token": null // Assuming payment_token is for subsequent use, not in this response.
})
)),
("08. Response for successful payment using saved card token" = (
value = json!({
"payment_id": "pay_token_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"payment_method": "card",
"payment_token": "{{payment_token}}",
"client_secret": "pay_token_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:27:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("09. Response for payment with billing details (requires payment method)" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "[email protected]",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
)),
("10. Response for the CIT call for Stripe Split Payments" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 200,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"payment_method_id": "pm_123456789",
"connector_mandate_id": "pm_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "[email protected]",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
)),
("11. Response for the MIT call for Stripe Split Payments" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 200,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"payment_method_id": "pm_123456789",
"connector_mandate_id": "pm_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "[email protected]",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
))
)
),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi),
),
tag = "Payments",
operation_id = "Create a Payment",
security(("api_key" = [])),
)]
pub fn payments_create() {}
/// Payments - Retrieve
///
/// Retrieves a Payment. This API can also be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/payments/{payment_id}",
params(
("payment_id" = String, Path, description = "The identifier for payment"),
("force_sync" = Option<bool>, Query, description = "Decider to enable or disable the connector call for retrieve request"),
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("expand_attempts" = Option<bool>, Query, description = "If enabled provides list of attempts linked to payment intent"),
("expand_captures" = Option<bool>, Query, description = "If enabled provides list of captures linked to latest attempt"),
),
responses(
(status = 200, description = "Gets the payment with final status", body = PaymentsResponse),
(status = 404, description = "No payment found")
),
tag = "Payments",
operation_id = "Retrieve a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_retrieve() {}
/// Payments - Update
///
/// To update the properties of a *PaymentIntent* object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created
#[utoipa::path(
post,
path = "/payments/{payment_id}",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body(
content = PaymentsUpdateRequest,
examples(
(
"Update the payment amount" = (
value = json!({
"amount": 7654,
}
)
)
),
(
"Update the shipping address" = (
value = json!(
{
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
},
}
)
)
)
)
),
responses(
(status = 200, description = "Payment updated", body = PaymentsCreateResponseOpenApi),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Update a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_update() {}
/// Payments - Confirm
///
/// Confirms a payment intent that was previously created with `confirm: false`. This action attempts to authorize the payment with the payment processor.
///
/// Expected status transitions after confirmation:
/// - `succeeded`: If authorization is successful and `capture_method` is `automatic`.
/// - `requires_capture`: If authorization is successful and `capture_method` is `manual`.
/// - `failed`: If authorization fails.
#[utoipa::path(
post,
path = "/payments/{payment_id}/confirm",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body(
content = PaymentsConfirmRequest,
examples(
(
"Confirm a payment with payment method data" = (
value = json!({
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
}
)
)
)
)
),
responses(
(status = 200, description = "Payment confirmed", body = PaymentsCreateResponseOpenApi),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Confirm a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_confirm() {}
/// Payments - Capture
///
/// Captures the funds for a previously authorized payment intent where `capture_method` was set to `manual` and the payment is in a `requires_capture` state.
///
/// Upon successful capture, the payment status usually transitions to `succeeded`.
/// The `amount_to_capture` can be specified in the request body; it must be less than or equal to the payment's `amount_capturable`. If omitted, the full capturable amount is captured.
///
/// A payment must be in a capturable state (e.g., `requires_capture`). Attempting to capture an already `succeeded` (and fully captured) payment or one in an invalid state will lead to an error.
///
#[utoipa::path(
post,
path = "/payments/{payment_id}/capture",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body (
content = PaymentsCaptureRequest,
examples(
(
"Capture the full amount" = (
value = json!({})
)
),
(
"Capture partial amount" = (
value = json!({"amount_to_capture": 654})
)
),
)
),
responses(
(status = 200, description = "Payment captured", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Capture a Payment",
security(("api_key" = []))
)]
pub fn payments_capture() {}
#[cfg(feature = "v1")]
/// Payments - Session token
///
/// Creates a session object or a session token for wallets like Apple Pay, Google Pay, etc. These tokens are used by Hyperswitch's SDK to initiate these wallets' SDK.
#[utoipa::path(
post,
path = "/payments/session_tokens",
request_body=PaymentsSessionRequest,
responses(
(status = 200, description = "Payment session object created or session token was retrieved from wallets", body = PaymentsSessionResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create Session tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_connector_session() {}
#[cfg(feature = "v2")]
/// Payments - Session token
///
/// Creates a session object or a session token for wallets like Apple Pay, Google Pay, etc. These tokens are used by Hyperswitch's SDK to initiate these wallets' SDK.
#[utoipa::path(
post,
path = "/v2/payments/{payment_id}/create-external-sdk-tokens",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsSessionRequest,
responses(
(status = 200, description = "Payment session object created or session token was retrieved from wallets", body = PaymentsSessionResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create V2 Session tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_connector_session() {}
/// Payments - Cancel
///
/// A Payment could can be cancelled when it is in one of these statuses: `requires_payment_method`, `requires_capture`, `requires_confirmation`, `requires_customer_action`.
#[utoipa::path(
post,
path = "/payments/{payment_id}/cancel",
request_body (
content = PaymentsCancelRequest,
examples(
(
"Cancel the payment with minimal fields" = (
value = json!({})
)
),
(
"Cancel the payment with cancellation reason" = (
value = json!({"cancellation_reason": "requested_by_customer"})
)
),
)
),
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payment canceled"),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Cancel a Payment",
security(("api_key" = []))
)]
pub fn payments_cancel() {}
/// Payments - Cancel Post Capture
///
/// A Payment could can be cancelled when it is in one of these statuses: `succeeded`, `partially_captured`, `partially_captured_and_capturable`.
#[utoipa::path(
post,
path = "/payments/{payment_id}/cancel_post_capture",
request_body (
content = PaymentsCancelPostCaptureRequest,
examples(
(
"Cancel the payment post capture with minimal fields" = (
value = json!({})
)
),
(
"Cancel the payment post capture with cancellation reason" = (
value = json!({"cancellation_reason": "requested_by_customer"})
)
),
)
),
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payment canceled post capture"),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Cancel a Payment Post Capture",
security(("api_key" = []))
)]
pub fn payments_cancel_post_capture() {}
/// Payments - List
///
/// To list the *payments*
#[cfg(feature = "v1")]
#[utoipa::path(
get,
path = "/payments/list",
params(
("customer_id" = Option<String>, Query, description = "The identifier for the customer"),
("starting_after" = Option<String>, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = Option<String>, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = Option<i64>, Query, description = "Limit on the number of objects to return"),
("created" = Option<PrimitiveDateTime>, Query, description = "The time at which payment is created"),
("created_lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the payment created time"),
("created_gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the payment created time"),
("created_lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the payment created time"),
("created_gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the payment created time")
),
responses(
(status = 200, description = "Successfully retrieved a payment list", body = Vec<PaymentListResponse>),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments",
security(("api_key" = []))
)]
pub fn payments_list() {}
/// Profile level Payments - List
///
/// To list the payments
#[utoipa::path(
get,
path = "/payments/list",
params(
("customer_id" = String, Query, description = "The identifier for the customer"),
("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = i64, Query, description = "Limit on the number of objects to return"),
("created" = PrimitiveDateTime, Query, description = "The time at which payment is created"),
("created_lt" = PrimitiveDateTime, Query, description = "Time less than the payment created time"),
("created_gt" = PrimitiveDateTime, Query, description = "Time greater than the payment created time"),
("created_lte" = PrimitiveDateTime, Query, description = "Time less than or equals to the payment created time"),
("created_gte" = PrimitiveDateTime, Query, description = "Time greater than or equals to the payment created time")
),
responses(
(status = 200, description = "Received payment list"),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments for the Profile",
security(("api_key" = []))
)]
pub async fn profile_payments_list() {}
/// Payments - Incremental Authorization
///
/// Authorized amount for a payment can be incremented if it is in status: requires_capture
#[utoipa::path(
post,
path = "/payments/{payment_id}/incremental_authorization",
request_body=PaymentsIncrementalAuthorizationRequest,
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payment authorized amount incremented", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Increment authorized amount for a Payment",
security(("api_key" = []))
)]
pub fn payments_incremental_authorization() {}
/// Payments - Extended Authorization
///
/// Extended authorization is available for payments currently in the `requires_capture` status
/// Call this endpoint to increase the authorization validity period
#[utoipa::path(
post,
path = "/payments/{payment_id}/extend_authorization",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Extended authorization for the payment"),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Extend authorization period for a Payment",
security(("api_key" = []))
)]
pub fn payments_extend_authorization() {}
/// Payments - External 3DS Authentication
///
/// External 3DS Authentication is performed and returns the AuthenticationResponse
#[utoipa::path(
post,
path = "/payments/{payment_id}/3ds/authentication",
request_body=PaymentsExternalAuthenticationRequest,
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Authentication created", body = PaymentsExternalAuthenticationResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Initiate external authentication for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_external_authentication() {}
/// Payments - Complete Authorize
#[utoipa::path(
post,
path = "/payments/{payment_id}/complete_authorize",
request_body=PaymentsCompleteAuthorizeRequest,
params(
("payment_id" =String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payments Complete Authorize Success", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Complete Authorize a Payment",
security(("publishable_key" = []))
)]
pub fn payments_complete_authorize() {}
/// Dynamic Tax Calculation
#[utoipa::path(
post,
path = "/payments/{payment_id}/calculate_tax",
request_body=PaymentsDynamicTaxCalculationRequest,
responses(
(status = 200, description = "Tax Calculation is done", body = PaymentsDynamicTaxCalculationResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create Tax Calculation for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_dynamic_tax_calculation() {}
/// Payments - Post Session Tokens
#[utoipa::path(
post,
path = "/payments/{payment_id}/post_session_tokens",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsPostSessionTokensRequest,
responses(
(status = 200, description = "Post Session Token is done", body = PaymentsPostSessionTokensResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create Post Session Tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_post_session_tokens() {}
/// Payments - Update Metadata
#[utoipa::path(
post,
path = "/payments/{payment_id}/update_metadata",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsUpdateMetadataRequest,
responses(
(status = 200, description = "Metadata updated successfully", body = PaymentsUpdateMetadataResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Update Metadata for a Payment",
security(("api_key" = []))
)]
pub fn payments_update_metadata() {}
/// Payments - Submit Eligibility Data
#[utoipa::path(
post,
path = "/payments/{payment_id}/eligibility",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsEligibilityRequest,
responses(
(status = 200, description = "Eligbility submit is successful", body = PaymentsEligibilityResponse),
(status = 400, description = "Bad Request", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Submit Eligibility data for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_submit_eligibility() {}
/// Payments - Create Intent
///
/// **Creates a payment intent object when amount_details are passed.**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the first call, and use the 'client secret' returned in this API along with your 'publishable key' to make subsequent API calls from your client.
#[utoipa::path(
post,
path = "/v2/payments/create-intent",
request_body(
content = PaymentsCreateIntentRequest,
examples(
(
"Create a payment intent with minimal fields" = (
value = json!({"amount_details": {"order_amount": 6540, "currency": "USD"}})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsIntentResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create a Payment Intent",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_create_intent() {}
/// Payments - Get Intent
///
/// **Get a payment intent object when id is passed in path**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
get,
path = "/v2/payments/{id}/get-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent")),
responses(
(status = 200, description = "Payment Intent", body = PaymentsIntentResponse),
(status = 404, description = "Payment Intent not found")
),
tag = "Payments",
operation_id = "Get the Payment Intent details",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_get_intent() {}
/// Payments - Update Intent
///
/// **Update a payment intent object**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
put,
path = "/v2/payments/{id}/update-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
),
request_body(
content = PaymentsUpdateIntentRequest,
examples(
(
"Update a payment intent with minimal fields" = (
value = json!({"amount_details": {"order_amount": 6540, "currency": "USD"}})
)
),
),
),
responses(
(status = 200, description = "Payment Intent Updated", body = PaymentsIntentResponse),
(status = 404, description = "Payment Intent Not Found")
),
tag = "Payments",
operation_id = "Update a Payment Intent",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_update_intent() {}
/// Payments - Confirm Intent
///
/// **Confirms a payment intent object with the payment method data**
///
/// .
#[utoipa::path(
post,
path = "/v2/payments/{id}/confirm-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentsConfirmIntentRequest,
examples(
(
"Confirm the payment intent with card details" = (
value = json!({
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Confirm Payment Intent",
security(("publishable_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_confirm_intent() {}
/// Payments - Get
///
/// Retrieves a Payment. This API can also be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/v2/payments/{id}",
params(
("id" = String, Path, description = "The global payment id"),
("force_sync" = ForceSync, Query, description = "A boolean to indicate whether to force sync the payment status. Value can be true or false")
),
responses(
(status = 200, description = "Gets the payment with final status", body = PaymentsResponse),
(status = 404, description = "No payment found with the given id")
),
tag = "Payments",
operation_id = "Retrieve a Payment",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub fn payment_status() {}
/// Payments - Create and Confirm Intent
///
/// **Creates and confirms a payment intent object when the amount and payment method information are passed.**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
post,
path = "/v2/payments",
params (
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentsRequest,
examples(
(
"Create and confirm the payment intent with amount and card details" = (
value = json!({
"amount_details": {
"order_amount": 6540,
"currency": "USD"
},
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create and Confirm Payment Intent",
security(("api_key" = [])),
)]
pub fn payments_create_and_confirm_intent() {}
#[derive(utoipa::ToSchema)]
#[schema(rename_all = "lowercase")]
pub(crate) enum ForceSync {
/// Force sync with the connector / processor to update the status
True,
/// Do not force sync with the connector / processor. Get the status which is available in the database
False,
}
/// Payments - Payment Methods List
///
/// List the payment methods eligible for a payment. This endpoint also returns the saved payment methods for the customer when the customer_id is passed when creating the payment
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payments/{id}/payment-methods",
params(
("id" = String, Path, description = "The global payment id"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
),
responses(
(status = 200, description = "Get the payment methods", body = PaymentMethodListResponseForPayments),
(status = 404, description = "No payment found with the given id")
),
tag = "Payments",
operation_id = "Retrieve Payment methods for a Payment",
security(("publishable_key" = []))
)]
pub fn list_payment_methods() {}
/// Payments - List
///
/// To list the *payments*
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payments/list",
params(api_models::payments::PaymentListConstraints),
responses(
(status = 200, description = "Successfully retrieved a payment list", body = PaymentListResponse),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments",
security(("api_key" = []), ("jwt_key" = []))
)]
pub fn payments_list() {}
/// Payments - Gift Card Balance Check
///
/// Check the balance of the provided gift card. This endpoint also returns whether the gift card balance is enough to cover the entire amount or another payment method is needed
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payments/{id}/check-gift-card-balance",
params(
("id" = String, Path, description = "The global payment id"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
),
request_body(
content = PaymentsGiftCardBalanceCheckRequest,
),
responses(
(status = 200, description = "Get the Gift Card Balance", body = GiftCardBalanceCheckResponse),
),
tag = "Payments",
operation_id = "Retrieve Gift Card Balance",
security(("publishable_key" = []))
)]
pub fn payment_check_gift_card_balance() {}
</file>
|
{
"crate": "openapi",
"file": "crates/openapi/src/routes/payments.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 12010
}
|
large_file_-6009197486689556579
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: openapi
File: crates/openapi/src/routes/routing.rs
</path>
<file>
#[cfg(feature = "v1")]
/// Routing - Create
///
/// Create a routing config
#[utoipa::path(
post,
path = "/routing",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Routing config created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Create a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_create_config() {}
#[cfg(feature = "v2")]
/// Routing - Create
///
/// Create a routing algorithm
#[utoipa::path(
post,
path = "/v2/routing-algorithms",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Create a routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_create_config() {}
#[cfg(feature = "v1")]
/// Routing - Activate config
///
/// Activate a routing config
#[utoipa::path(
post,
path = "/routing/{routing_algorithm_id}/activate",
params(
("routing_algorithm_id" = String, Path, description = "The unique identifier for a config"),
),
responses(
(status = 200, description = "Routing config activated", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Bad request")
),
tag = "Routing",
operation_id = "Activate a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_link_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve
///
/// Retrieve a routing algorithm
#[utoipa::path(
get,
path = "/routing/{routing_algorithm_id}",
params(
("routing_algorithm_id" = String, Path, description = "The unique identifier for a config"),
),
responses(
(status = 200, description = "Successfully fetched routing config", body = MerchantRoutingAlgorithm),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_config() {}
#[cfg(feature = "v2")]
/// Routing - Retrieve
///
/// Retrieve a routing algorithm with its algorithm id
#[utoipa::path(
get,
path = "/v2/routing-algorithms/{id}",
params(
("id" = String, Path, description = "The unique identifier for a routing algorithm"),
),
responses(
(status = 200, description = "Successfully fetched routing algorithm", body = MerchantRoutingAlgorithm),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve a routing algorithm with its algorithm id",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_config() {}
#[cfg(feature = "v1")]
/// Routing - List
///
/// List all routing configs
#[utoipa::path(
get,
path = "/routing",
params(
("limit" = Option<u16>, Query, description = "The number of records to be returned"),
("offset" = Option<u8>, Query, description = "The record offset from which to start gathering of results"),
("profile_id" = Option<String>, Query, description = "The unique identifier for a merchant profile"),
),
responses(
(status = 200, description = "Successfully fetched routing configs", body = RoutingKind),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing")
),
tag = "Routing",
operation_id = "List routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn list_routing_configs() {}
#[cfg(feature = "v1")]
/// Routing - Deactivate
///
/// Deactivates a routing config
#[utoipa::path(
post,
path = "/routing/deactivate",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Successfully deactivated routing config", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 403, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Routing",
operation_id = "Deactivate a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_unlink_config() {}
#[cfg(feature = "v1")]
/// Routing - Update Default Config
///
/// Update default fallback config
#[utoipa::path(
post,
path = "/routing/default",
request_body = Vec<RoutableConnectorChoice>,
responses(
(status = 200, description = "Successfully updated default config", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Routing",
operation_id = "Update default fallback config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Default Config
///
/// Retrieve default fallback config
#[utoipa::path(
get,
path = "/routing/default",
responses(
(status = 200, description = "Successfully retrieved default config", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error")
),
tag = "Routing",
operation_id = "Retrieve default fallback config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Config
///
/// Retrieve active config
#[utoipa::path(
get,
path = "/routing/active",
params(
("profile_id" = Option<String>, Query, description = "The unique identifier for a merchant profile"),
),
responses(
(status = 200, description = "Successfully retrieved active config", body = LinkedRoutingConfigRetrieveResponse),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve active config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_linked_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Default For Profile
///
/// Retrieve default config for profiles
#[utoipa::path(
get,
path = "/routing/default/profile",
responses(
(status = 200, description = "Successfully retrieved default config", body = ProfileDefaultRoutingConfig),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing")
),
tag = "Routing",
operation_id = "Retrieve default configs for all profiles",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config_for_profiles() {}
#[cfg(feature = "v1")]
/// Routing - Update Default For Profile
///
/// Update default config for profiles
#[utoipa::path(
post,
path = "/routing/default/profile/{profile_id}",
request_body = Vec<RoutableConnectorChoice>,
params(
("profile_id" = String, Path, description = "The unique identifier for a profile"),
),
responses(
(status = 200, description = "Successfully updated default config for profile", body = ProfileDefaultRoutingConfig),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update default configs for all profiles",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config_for_profile() {}
#[cfg(feature = "v1")]
/// Routing - Toggle success based dynamic routing for profile
///
/// Create a success based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for success based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle success based dynamic routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn toggle_success_based_routing() {}
#[cfg(feature = "v1")]
/// Routing - Update success based dynamic routing config for profile
///
/// Update success based dynamic routing algorithm
#[utoipa::path(
patch,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/config/{algorithm_id}",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("algorithm_id" = String, Path, description = "Success based routing algorithm id which was last activated to update the config"),
),
request_body = SuccessBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
(status = 400, description = "Update body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update success based dynamic routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn success_based_routing_update_configs() {}
#[cfg(feature = "v1")]
/// Routing - Toggle elimination routing for profile
///
/// Create a elimination based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/elimination/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for elimination based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle elimination routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn toggle_elimination_routing() {}
#[cfg(feature = "v1")]
/// Routing - Toggle Contract routing for profile
///
/// Create a Contract based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/contracts/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for contract based routing"),
),
request_body = ContractBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle contract routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn contract_based_routing_setup_config() {}
#[cfg(feature = "v1")]
/// Routing - Update contract based dynamic routing config for profile
///
/// Update contract based dynamic routing algorithm
#[utoipa::path(
patch,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/contracts/config/{algorithm_id}",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("algorithm_id" = String, Path, description = "Contract based routing algorithm id which was last activated to update the config"),
),
request_body = ContractBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
(status = 400, description = "Update body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update contract based dynamic routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn contract_based_routing_update_configs() {}
#[cfg(feature = "v1")]
/// Routing - Evaluate
///
/// Evaluate routing rules
#[utoipa::path(
post,
path = "/routing/evaluate",
request_body = OpenRouterDecideGatewayRequest,
responses(
(status = 200, description = "Routing rules evaluated successfully", body = DecideGatewayResponse),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Evaluate routing rules",
security(("api_key" = []))
)]
pub async fn call_decide_gateway_open_router() {}
#[cfg(feature = "v1")]
/// Routing - Feedback
///
/// Update gateway scores for dynamic routing
#[utoipa::path(
post,
path = "/routing/feedback",
request_body = UpdateScorePayload,
responses(
(status = 200, description = "Gateway score updated successfully", body = UpdateScoreResponse),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update gateway scores",
security(("api_key" = []))
)]
pub async fn call_update_gateway_score_open_router() {}
#[cfg(feature = "v1")]
/// Routing - Rule Evaluate
///
/// Evaluate routing rules
#[utoipa::path(
post,
path = "/routing/rule/evaluate",
request_body = RoutingEvaluateRequest,
responses(
(status = 200, description = "Routing rules evaluated successfully", body = RoutingEvaluateResponse),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Evaluate routing rules (alternative)",
security(("api_key" = []))
)]
pub async fn evaluate_routing_rule() {}
</file>
|
{
"crate": "openapi",
"file": "crates/openapi/src/routes/routing.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4179
}
|
large_file_-7877708696261474779
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: drainer
File: crates/drainer/src/handler.rs
</path>
<file>
use std::{
collections::HashMap,
sync::{atomic, Arc},
};
use common_utils::id_type;
use router_env::tracing::Instrument;
use tokio::{
sync::{mpsc, oneshot},
time::{self, Duration},
};
use crate::{
errors, instrument, logger, metrics, query::ExecuteQuery, tracing, utils, DrainerSettings,
Store, StreamData,
};
/// Handler handles the spawning and closing of drainer
/// Arc is used to enable creating a listener for graceful shutdown
#[derive(Clone)]
pub struct Handler {
inner: Arc<HandlerInner>,
}
impl std::ops::Deref for Handler {
type Target = HandlerInner;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
pub struct HandlerInner {
shutdown_interval: Duration,
loop_interval: Duration,
active_tasks: Arc<atomic::AtomicU64>,
conf: DrainerSettings,
stores: HashMap<id_type::TenantId, Arc<Store>>,
running: Arc<atomic::AtomicBool>,
}
impl Handler {
pub fn from_conf(
conf: DrainerSettings,
stores: HashMap<id_type::TenantId, Arc<Store>>,
) -> Self {
let shutdown_interval = Duration::from_millis(conf.shutdown_interval.into());
let loop_interval = Duration::from_millis(conf.loop_interval.into());
let active_tasks = Arc::new(atomic::AtomicU64::new(0));
let running = Arc::new(atomic::AtomicBool::new(true));
let handler = HandlerInner {
shutdown_interval,
loop_interval,
active_tasks,
conf,
stores,
running,
};
Self {
inner: Arc::new(handler),
}
}
pub fn close(&self) {
self.running.store(false, atomic::Ordering::SeqCst);
}
pub async fn spawn(&self) -> errors::DrainerResult<()> {
let mut stream_index: u8 = 0;
let jobs_picked = Arc::new(atomic::AtomicU8::new(0));
while self.running.load(atomic::Ordering::SeqCst) {
metrics::DRAINER_HEALTH.add(1, &[]);
for store in self.stores.values() {
if store.is_stream_available(stream_index).await {
let _task_handle = tokio::spawn(
drainer_handler(
store.clone(),
stream_index,
self.conf.max_read_count,
self.active_tasks.clone(),
jobs_picked.clone(),
)
.in_current_span(),
);
}
}
stream_index = utils::increment_stream_index(
(stream_index, jobs_picked.clone()),
self.conf.num_partitions,
)
.await;
time::sleep(self.loop_interval).await;
}
Ok(())
}
pub(crate) async fn shutdown_listener(&self, mut rx: mpsc::Receiver<()>) {
while let Some(_c) = rx.recv().await {
logger::info!("Awaiting shutdown!");
metrics::SHUTDOWN_SIGNAL_RECEIVED.add(1, &[]);
let shutdown_started = time::Instant::now();
rx.close();
//Check until the active tasks are zero. This does not include the tasks in the stream.
while self.active_tasks.load(atomic::Ordering::SeqCst) != 0 {
time::sleep(self.shutdown_interval).await;
}
logger::info!("Terminating drainer");
metrics::SUCCESSFUL_SHUTDOWN.add(1, &[]);
let shutdown_ended = shutdown_started.elapsed().as_secs_f64() * 1000f64;
metrics::CLEANUP_TIME.record(shutdown_ended, &[]);
self.close();
}
logger::info!(
tasks_remaining = self.active_tasks.load(atomic::Ordering::SeqCst),
"Drainer shutdown successfully"
)
}
pub fn spawn_error_handlers(&self, tx: mpsc::Sender<()>) -> errors::DrainerResult<()> {
let (redis_error_tx, redis_error_rx) = oneshot::channel();
let redis_conn_clone = self
.stores
.values()
.next()
.map(|store| store.redis_conn.clone());
match redis_conn_clone {
None => {
logger::error!("No redis connection found");
Err(
errors::DrainerError::UnexpectedError("No redis connection found".to_string())
.into(),
)
}
Some(redis_conn_clone) => {
// Spawn a task to monitor if redis is down or not
let _task_handle = tokio::spawn(
async move { redis_conn_clone.on_error(redis_error_tx).await }
.in_current_span(),
);
//Spawns a task to send shutdown signal if redis goes down
let _task_handle =
tokio::spawn(redis_error_receiver(redis_error_rx, tx).in_current_span());
Ok(())
}
}
}
}
pub async fn redis_error_receiver(rx: oneshot::Receiver<()>, shutdown_channel: mpsc::Sender<()>) {
match rx.await {
Ok(_) => {
logger::error!("The redis server failed");
let _ = shutdown_channel.send(()).await.map_err(|err| {
logger::error!("Failed to send signal to the shutdown channel {err}")
});
}
Err(err) => {
logger::error!("Channel receiver error {err}");
}
}
}
#[router_env::instrument(skip_all)]
async fn drainer_handler(
store: Arc<Store>,
stream_index: u8,
max_read_count: u64,
active_tasks: Arc<atomic::AtomicU64>,
jobs_picked: Arc<atomic::AtomicU8>,
) -> errors::DrainerResult<()> {
active_tasks.fetch_add(1, atomic::Ordering::Release);
let stream_name = store.get_drainer_stream_name(stream_index);
let drainer_result = Box::pin(drainer(
store.clone(),
max_read_count,
stream_name.as_str(),
jobs_picked,
))
.await;
if let Err(error) = drainer_result {
logger::error!(?error)
}
let flag_stream_name = store.get_stream_key_flag(stream_index);
let output = store.make_stream_available(flag_stream_name.as_str()).await;
active_tasks.fetch_sub(1, atomic::Ordering::Release);
output.inspect_err(|err| logger::error!(operation = "unlock_stream", err=?err))
}
#[instrument(skip_all, fields(global_id, request_id, session_id))]
async fn drainer(
store: Arc<Store>,
max_read_count: u64,
stream_name: &str,
jobs_picked: Arc<atomic::AtomicU8>,
) -> errors::DrainerResult<()> {
let stream_read = match store.read_from_stream(stream_name, max_read_count).await {
Ok(result) => {
jobs_picked.fetch_add(1, atomic::Ordering::SeqCst);
result
}
Err(error) => {
if let errors::DrainerError::RedisError(redis_err) = error.current_context() {
if let redis_interface::errors::RedisError::StreamEmptyOrNotAvailable =
redis_err.current_context()
{
metrics::STREAM_EMPTY.add(1, &[]);
return Ok(());
} else {
return Err(error);
}
} else {
return Err(error);
}
}
};
// parse_stream_entries returns error if no entries is found, handle it
let entries = utils::parse_stream_entries(
&stream_read,
store.redis_conn.add_prefix(stream_name).as_str(),
)?;
let read_count = entries.len();
metrics::JOBS_PICKED_PER_STREAM.add(
u64::try_from(read_count).unwrap_or(u64::MIN),
router_env::metric_attributes!(("stream", stream_name.to_owned())),
);
let session_id = common_utils::generate_id_with_default_len("drainer_session");
let mut last_processed_id = String::new();
for (entry_id, entry) in entries.clone() {
let data = match StreamData::from_hashmap(entry) {
Ok(data) => data,
Err(err) => {
logger::error!(operation = "deserialization", err=?err);
metrics::STREAM_PARSE_FAIL.add(
1,
router_env::metric_attributes!(("operation", "deserialization")),
);
// break from the loop in case of a deser error
break;
}
};
tracing::Span::current().record("request_id", data.request_id);
tracing::Span::current().record("global_id", data.global_id);
tracing::Span::current().record("session_id", &session_id);
match data.typed_sql.execute_query(&store, data.pushed_at).await {
Ok(_) => {
last_processed_id = entry_id;
}
Err(err) => match err.current_context() {
// In case of Uniqueviolation we can't really do anything to fix it so just clear
// it from the stream
diesel_models::errors::DatabaseError::UniqueViolation => {
last_processed_id = entry_id;
}
// break from the loop in case of an error in query
_ => break,
},
}
if store.use_legacy_version() {
store
.delete_from_stream(stream_name, &last_processed_id)
.await?;
}
}
if !(last_processed_id.is_empty() || store.use_legacy_version()) {
let entries_trimmed = store
.trim_from_stream(stream_name, &last_processed_id)
.await?;
if read_count != entries_trimmed {
logger::error!(
read_entries = %read_count,
trimmed_entries = %entries_trimmed,
?entries,
"Assertion Failed no. of entries read from the stream doesn't match no. of entries trimmed"
);
}
} else {
logger::error!(read_entries = %read_count,?entries,"No streams were processed in this session");
}
Ok(())
}
</file>
|
{
"crate": "drainer",
"file": "crates/drainer/src/handler.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2163
}
|
large_file_-603103686016914947
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: drainer
File: crates/drainer/src/health_check.rs
</path>
<file>
use std::{collections::HashMap, sync::Arc};
use actix_web::{web, Scope};
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
use common_utils::{errors::CustomResult, id_type};
use diesel_models::{Config, ConfigNew};
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
use crate::{
connection::pg_connection,
errors::HealthCheckError,
services::{self, log_and_return_error_response, Store},
Settings,
};
pub const TEST_STREAM_NAME: &str = "TEST_STREAM_0";
pub const TEST_STREAM_DATA: &[(&str, &str)] = &[("data", "sample_data")];
pub struct Health;
impl Health {
pub fn server(conf: Settings, stores: HashMap<id_type::TenantId, Arc<Store>>) -> Scope {
web::scope("health")
.app_data(web::Data::new(conf))
.app_data(web::Data::new(stores))
.service(web::resource("").route(web::get().to(health)))
.service(web::resource("/ready").route(web::get().to(deep_health_check)))
}
}
#[instrument(skip_all)]
pub async fn health() -> impl actix_web::Responder {
logger::info!("Drainer health was called");
actix_web::HttpResponse::Ok().body("Drainer health is good")
}
#[instrument(skip_all)]
pub async fn deep_health_check(
conf: web::Data<Settings>,
stores: web::Data<HashMap<String, Arc<Store>>>,
) -> impl actix_web::Responder {
let mut deep_health_res = HashMap::new();
for (tenant, store) in stores.iter() {
logger::info!("Tenant: {:?}", tenant);
let response = match deep_health_check_func(conf.clone(), store).await {
Ok(response) => serde_json::to_string(&response)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
Err(err) => return log_and_return_error_response(err),
};
deep_health_res.insert(tenant.clone(), response);
}
services::http_response_json(
serde_json::to_string(&deep_health_res)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
)
}
#[instrument(skip_all)]
pub async fn deep_health_check_func(
conf: web::Data<Settings>,
store: &Arc<Store>,
) -> Result<DrainerHealthCheckResponse, error_stack::Report<HealthCheckError>> {
logger::info!("Deep health check was called");
logger::debug!("Database health check begin");
let db_status = store
.health_check_db()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(HealthCheckError::DbError { message })
})?;
logger::debug!("Database health check end");
logger::debug!("Redis health check begin");
let redis_status = store
.health_check_redis(&conf.into_inner())
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(HealthCheckError::RedisError { message })
})?;
logger::debug!("Redis health check end");
Ok(DrainerHealthCheckResponse {
database: db_status,
redis: redis_status,
})
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DrainerHealthCheckResponse {
pub database: bool,
pub redis: bool,
}
#[async_trait::async_trait]
pub trait HealthCheckInterface {
async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError>;
async fn health_check_redis(&self, conf: &Settings) -> CustomResult<(), HealthCheckRedisError>;
}
#[async_trait::async_trait]
impl HealthCheckInterface for Store {
async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError> {
let conn = pg_connection(&self.master_pool).await;
conn
.transaction_async(|conn| {
Box::pin(async move {
let query =
diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1"));
let _x: i32 = query.get_result_async(&conn).await.map_err(|err| {
logger::error!(read_err=?err,"Error while reading element in the database");
HealthCheckDBError::DbReadError
})?;
logger::debug!("Database read was successful");
let config = ConfigNew {
key: "test_key".to_string(),
config: "test_value".to_string(),
};
config.insert(&conn).await.map_err(|err| {
logger::error!(write_err=?err,"Error while writing to database");
HealthCheckDBError::DbWriteError
})?;
logger::debug!("Database write was successful");
Config::delete_by_key(&conn, "test_key").await.map_err(|err| {
logger::error!(delete_err=?err,"Error while deleting element in the database");
HealthCheckDBError::DbDeleteError
})?;
logger::debug!("Database delete was successful");
Ok::<_, HealthCheckDBError>(())
})
})
.await?;
Ok(())
}
async fn health_check_redis(
&self,
_conf: &Settings,
) -> CustomResult<(), HealthCheckRedisError> {
let redis_conn = self.redis_conn.clone();
redis_conn
.serialize_and_set_key_with_expiry(&"test_key".into(), "test_value", 30)
.await
.change_context(HealthCheckRedisError::SetFailed)?;
logger::debug!("Redis set_key was successful");
redis_conn
.get_key::<()>(&"test_key".into())
.await
.change_context(HealthCheckRedisError::GetFailed)?;
logger::debug!("Redis get_key was successful");
redis_conn
.delete_key(&"test_key".into())
.await
.change_context(HealthCheckRedisError::DeleteFailed)?;
logger::debug!("Redis delete_key was successful");
redis_conn
.stream_append_entry(
&TEST_STREAM_NAME.into(),
&redis_interface::RedisEntryId::AutoGeneratedID,
TEST_STREAM_DATA.to_vec(),
)
.await
.change_context(HealthCheckRedisError::StreamAppendFailed)?;
logger::debug!("Stream append succeeded");
let output = redis_conn
.stream_read_entries(TEST_STREAM_NAME, "0-0", Some(10))
.await
.change_context(HealthCheckRedisError::StreamReadFailed)?;
logger::debug!("Stream read succeeded");
let (_, id_to_trim) = output
.get(&redis_conn.add_prefix(TEST_STREAM_NAME))
.and_then(|entries| {
entries
.last()
.map(|last_entry| (entries, last_entry.0.clone()))
})
.ok_or(error_stack::report!(
HealthCheckRedisError::StreamReadFailed
))?;
logger::debug!("Stream parse succeeded");
redis_conn
.stream_trim_entries(
&TEST_STREAM_NAME.into(),
(
redis_interface::StreamCapKind::MinID,
redis_interface::StreamCapTrim::Exact,
id_to_trim,
),
)
.await
.change_context(HealthCheckRedisError::StreamTrimFailed)?;
logger::debug!("Stream trim succeeded");
Ok(())
}
}
#[allow(clippy::enum_variant_names)]
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckDBError {
#[error("Error while connecting to database")]
DbError,
#[error("Error while writing to database")]
DbWriteError,
#[error("Error while reading element in the database")]
DbReadError,
#[error("Error while deleting element in the database")]
DbDeleteError,
#[error("Unpredictable error occurred")]
UnknownError,
#[error("Error in database transaction")]
TransactionError,
}
impl From<diesel::result::Error> for HealthCheckDBError {
fn from(error: diesel::result::Error) -> Self {
match error {
diesel::result::Error::DatabaseError(_, _) => Self::DbError,
diesel::result::Error::RollbackErrorOnCommit { .. }
| diesel::result::Error::RollbackTransaction
| diesel::result::Error::AlreadyInTransaction
| diesel::result::Error::NotInTransaction
| diesel::result::Error::BrokenTransactionManager => Self::TransactionError,
_ => Self::UnknownError,
}
}
}
#[allow(clippy::enum_variant_names)]
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckRedisError {
#[error("Failed to set key value in Redis")]
SetFailed,
#[error("Failed to get key value in Redis")]
GetFailed,
#[error("Failed to delete key value in Redis")]
DeleteFailed,
#[error("Failed to append data to the stream in Redis")]
StreamAppendFailed,
#[error("Failed to read data from the stream in Redis")]
StreamReadFailed,
#[error("Failed to trim data from the stream in Redis")]
StreamTrimFailed,
}
</file>
|
{
"crate": "drainer",
"file": "crates/drainer/src/health_check.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2002
}
|
large_file_1592024571730120703
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: drainer
File: crates/drainer/src/settings.rs
</path>
<file>
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(())
}
}
</file>
|
{
"crate": "drainer",
"file": "crates/drainer/src/settings.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2456
}
|
large_file_-5265215407443085952
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: router_derive
File: crates/router_derive/src/lib.rs
</path>
<file>
//! 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", "[email protected]"),
/// ]
/// ```
#[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()
}
</file>
|
{
"crate": "router_derive",
"file": "crates/router_derive/src/lib.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6413
}
|
large_file_-2567559567598527228
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: router_derive
File: crates/router_derive/src/macros/operation.rs
</path>
<file>
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))
}
</file>
|
{
"crate": "router_derive",
"file": "crates/router_derive/src/macros/operation.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3620
}
|
large_file_3659026752147940299
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: router_derive
File: crates/router_derive/src/macros/api_error.rs
</path>
<file>
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),*
}
}
}
}
}
</file>
|
{
"crate": "router_derive",
"file": "crates/router_derive/src/macros/api_error.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2061
}
|
large_file_4762529979031473426
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: router_derive
File: crates/router_derive/src/macros/to_encryptable.rs
</path>
<file>
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)
}
</file>
|
{
"crate": "router_derive",
"file": "crates/router_derive/src/macros/to_encryptable.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2534
}
|
large_file_-7702817966989584714
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: subscriptions
File: crates/subscriptions/src/core.rs
</path>
<file>
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
}
</file>
|
{
"crate": "subscriptions",
"file": "crates/subscriptions/src/core.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3695
}
|
large_file_7476554935071832742
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: subscriptions
File: crates/subscriptions/src/core/subscription_handler.rs
</path>
<file>
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(),
})
}
}
</file>
|
{
"crate": "subscriptions",
"file": "crates/subscriptions/src/core/subscription_handler.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3255
}
|
large_file_-5669622173618730792
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: subscriptions
File: crates/subscriptions/src/core/billing_processor_handler.rs
</path>
<file>
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()),
})
}
}
</file>
|
{
"crate": "subscriptions",
"file": "crates/subscriptions/src/core/billing_processor_handler.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3245
}
|
large_file_-4072988522604291158
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: subscriptions
File: crates/subscriptions/src/core/invoice_handler.rs
</path>
<file>
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
}
}
</file>
|
{
"crate": "subscriptions",
"file": "crates/subscriptions/src/core/invoice_handler.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2800
}
|
large_file_2803099352476462625
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: subscriptions
File: crates/subscriptions/src/workflows/invoice_sync.rs
</path>
<file>
#[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(())
}
</file>
|
{
"crate": "subscriptions",
"file": "crates/subscriptions/src/workflows/invoice_sync.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2936
}
|
large_file_-456760102552710053
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid
File: crates/euclid/src/types.rs
</path>
<file>
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));
}
}
</file>
|
{
"crate": "euclid",
"file": "crates/euclid/src/types.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2925
}
|
large_file_-6503093219100428495
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid
File: crates/euclid/src/frontend/dir.rs
</path>
<file>
//! 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())
}
}
</file>
|
{
"crate": "euclid",
"file": "crates/euclid/src/frontend/dir.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8720
}
|
large_file_-1258935865641444195
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid
File: crates/euclid/src/frontend/dir/lowering.rs
</path>
<file>
//! 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,
})
}
</file>
|
{
"crate": "euclid",
"file": "crates/euclid/src/frontend/dir/lowering.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4076
}
|
large_file_-22513705170064438
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid
File: crates/euclid/src/frontend/dir/transformers.rs
</path>
<file>
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))
}
}
}
}
</file>
|
{
"crate": "euclid",
"file": "crates/euclid/src/frontend/dir/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3371
}
|
large_file_-2297294288728066872
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid
File: crates/euclid/src/frontend/dir/enums.rs
</path>
<file>
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);
</file>
|
{
"crate": "euclid",
"file": "crates/euclid/src/frontend/dir/enums.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2713
}
|
large_file_-6958029755577970509
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid
File: crates/euclid/src/frontend/ast/lowering.rs
</path>
<file>
//! 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,
})
}
</file>
|
{
"crate": "euclid",
"file": "crates/euclid/src/frontend/ast/lowering.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3093
}
|
large_file_-6390005602179573540
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid
File: crates/euclid/src/frontend/ast/parser.rs
</path>
<file>
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)
}
</file>
|
{
"crate": "euclid",
"file": "crates/euclid/src/frontend/ast/parser.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3334
}
|
large_file_-76436871777835289
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid
File: crates/euclid/src/backend/vir_interpreter.rs
</path>
<file>
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"
);
}
}
</file>
|
{
"crate": "euclid",
"file": "crates/euclid/src/backend/vir_interpreter.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5226
}
|
large_file_-6150709879261161321
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid
File: crates/euclid/src/dssa/state_machine.rs
</path>
<file>
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);
}
}
</file>
|
{
"crate": "euclid",
"file": "crates/euclid/src/dssa/state_machine.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4762
}
|
large_file_1531638626601300734
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid
File: crates/euclid/src/dssa/analyzer.rs
</path>
<file>
//! 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,
}
));
}
}
</file>
|
{
"crate": "euclid",
"file": "crates/euclid/src/dssa/analyzer.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3243
}
|
large_file_-1428653642450571325
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: euclid
File: crates/euclid/src/dssa/graph.rs
</path>
<file>
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());
}
}
</file>
|
{
"crate": "euclid",
"file": "crates/euclid/src/dssa/graph.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8102
}
|
large_file_-3005268635341052044
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/open_router.rs
</path>
<file>
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,
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/open_router.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3056
}
|
large_file_-1629339103106385462
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/refunds.rs
</path>
<file>
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,
}
}
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/refunds.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5297
}
|
large_file_-778769020338337654
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/payouts.rs
</path>
<file>
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 = "[email protected]")]
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 = "[email protected]")]
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 = "[email protected]")]
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 = "[email protected]")]
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)
}
}
}
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/payouts.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10977
}
|
large_file_-6753154131888779635
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/disputes.rs
</path>
<file>
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()
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/disputes.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2334
}
|
large_file_-8082235002951741661
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/subscription.rs
</path>
<file>
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 {}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/subscription.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3937
}
|
large_file_-4770102092032661458
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/enums.rs
</path>
<file>
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,
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/enums.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3876
}
|
large_file_1310438236659273899
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/user.rs
</path>
<file>
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,
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/user.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3025
}
|
large_file_-6425851190154873989
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/webhooks.rs
</path>
<file>
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
)
}
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/webhooks.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4107
}
|
large_file_5335492258483812064
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/api_keys.rs
</path>
<file>
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);
}
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/api_keys.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2766
}
|
large_file_-1289461149319140746
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/analytics.rs
</path>
<file>
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>,
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/analytics.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3973
}
|
large_file_5955364270849422652
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/customers.rs
</path>
<file>
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 = "[email protected]")]
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 = "[email protected]")]
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 = "[email protected]")]
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 = "[email protected]")]
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 = "[email protected]")]
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 = "[email protected]")]
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,
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/customers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4810
}
|
large_file_-7799971875699614573
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/authentication.rs
</path>
<file>
use common_enums::{enums, AuthenticationConnectors};
#[cfg(feature = "v1")]
use common_utils::errors::{self, CustomResult};
use common_utils::{
events::{ApiEventMetric, ApiEventsType},
id_type,
};
#[cfg(feature = "v1")]
use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
#[cfg(feature = "v1")]
use crate::payments::{Address, BrowserInformation, PaymentMethodData};
use crate::payments::{CustomerDetails, DeviceChannel, SdkInformation, ThreeDsCompletionIndicator};
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationCreateRequest {
/// The unique identifier for this authentication.
#[schema(value_type = Option<String>, example = "auth_mbabizu24mvu3mela5njyhpit4")]
pub authentication_id: Option<id_type::AuthenticationId>,
/// The business profile that is associated with this authentication
#[schema(value_type = Option<String>)]
pub profile_id: Option<id_type::ProfileId>,
/// Customer details.
#[schema(value_type = Option<CustomerDetails>)]
pub customer: Option<CustomerDetails>,
/// The amount for the transaction, required.
#[schema(value_type = MinorUnit, example = 1000)]
pub amount: common_utils::types::MinorUnit,
/// The connector to be used for authentication, if known.
#[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")]
pub authentication_connector: Option<AuthenticationConnectors>,
/// The currency for the transaction, required.
#[schema(value_type = Currency)]
pub currency: common_enums::Currency,
/// The URL to which the user should be redirected after authentication.
#[schema(value_type = Option<String>, example = "https://example.com/redirect")]
pub return_url: Option<String>,
/// Force 3DS challenge.
#[serde(default)]
pub force_3ds_challenge: Option<bool>,
/// Choose what kind of sca exemption is required for this payment
#[schema(value_type = Option<ScaExemptionType>)]
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
/// Profile Acquirer ID get from profile acquirer configuration
#[schema(value_type = Option<String>)]
pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,
/// Acquirer details information
#[schema(value_type = Option<AcquirerDetails>)]
pub acquirer_details: Option<AcquirerDetails>,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AcquirerDetails {
/// The bin of the card.
#[schema(value_type = Option<String>, example = "123456")]
pub acquirer_bin: Option<String>,
/// The merchant id of the card.
#[schema(value_type = Option<String>, example = "merchant_abc")]
pub acquirer_merchant_id: Option<String>,
/// The country code of the card.
#[schema(value_type = Option<String>, example = "US/34456")]
pub merchant_country_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationResponse {
/// The unique identifier for this authentication.
#[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")]
pub authentication_id: id_type::AuthenticationId,
/// This is an identifier for the merchant account. This is inferred from the API key
/// provided during the request
#[schema(value_type = String, example = "merchant_abc")]
pub merchant_id: id_type::MerchantId,
/// The current status of the authentication (e.g., Started).
#[schema(value_type = AuthenticationStatus)]
pub status: common_enums::AuthenticationStatus,
/// The client secret for this authentication, to be used for client-side operations.
#[schema(value_type = Option<String>, example = "auth_mbabizu24mvu3mela5njyhpit4_secret_el9ksDkiB8hi6j9N78yo")]
pub client_secret: Option<masking::Secret<String>>,
/// The amount for the transaction.
#[schema(value_type = MinorUnit, example = 1000)]
pub amount: common_utils::types::MinorUnit,
/// The currency for the transaction.
#[schema(value_type = Currency)]
pub currency: enums::Currency,
/// The connector to be used for authentication, if known.
#[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")]
pub authentication_connector: Option<AuthenticationConnectors>,
/// Whether 3DS challenge was forced.
pub force_3ds_challenge: Option<bool>,
/// The URL to which the user should be redirected after authentication, if provided.
pub return_url: Option<String>,
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
#[schema(example = "E0001")]
pub error_code: Option<String>,
/// If there was an error while calling the connector the error message is received here
#[schema(example = "Failed while verifying the card")]
pub error_message: Option<String>,
/// The business profile that is associated with this payment
#[schema(value_type = Option<String>)]
pub profile_id: Option<id_type::ProfileId>,
/// Choose what kind of sca exemption is required for this payment
#[schema(value_type = Option<ScaExemptionType>)]
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
/// Acquirer details information
#[schema(value_type = Option<AcquirerDetails>)]
pub acquirer_details: Option<AcquirerDetails>,
/// Profile Acquirer ID get from profile acquirer configuration
#[schema(value_type = Option<String>)]
pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,
}
impl ApiEventMetric for AuthenticationCreateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
self.authentication_id
.as_ref()
.map(|id| ApiEventsType::Authentication {
authentication_id: id.clone(),
})
}
}
impl ApiEventMetric for AuthenticationResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationEligibilityRequest {
/// Payment method-specific data such as card details, wallet info, etc.
/// This holds the raw information required to process the payment method.
#[schema(value_type = PaymentMethodData)]
pub payment_method_data: PaymentMethodData,
/// Enum representing the type of payment method being used
/// (e.g., Card, Wallet, UPI, BankTransfer, etc.).
#[schema(value_type = PaymentMethod)]
pub payment_method: common_enums::PaymentMethod,
/// Can be used to specify the Payment Method Type
#[schema(value_type = Option<PaymentMethodType>, example = "debit")]
pub payment_method_type: Option<enums::PaymentMethodType>,
/// Optional secret value used to identify and authorize the client making the request.
/// This can help ensure that the payment session is secure and valid.
#[schema(value_type = Option<String>)]
pub client_secret: Option<masking::Secret<String>>,
/// Optional identifier for the business profile associated with the payment.
/// This determines which configurations, rules, and branding are applied to the transaction.
#[schema(value_type = Option<String>)]
pub profile_id: Option<id_type::ProfileId>,
/// Optional billing address of the customer.
/// This can be used for fraud detection, authentication, or compliance purposes.
#[schema(value_type = Option<Address>)]
pub billing: Option<Address>,
/// Optional shipping address of the customer.
/// This can be useful for logistics, verification, or additional risk checks.
#[schema(value_type = Option<Address>)]
pub shipping: Option<Address>,
/// Optional information about the customer's browser (user-agent, language, etc.).
/// This is typically used to support 3DS authentication flows and improve risk assessment.
#[schema(value_type = Option<BrowserInformation>)]
pub browser_information: Option<BrowserInformation>,
/// Optional email address of the customer.
/// Used for customer identification, communication, and possibly for 3DS or fraud checks.
#[schema(value_type = Option<String>)]
pub email: Option<common_utils::pii::Email>,
}
#[cfg(feature = "v1")]
impl AuthenticationEligibilityRequest {
pub fn get_next_action_api(
&self,
base_url: String,
authentication_id: String,
) -> CustomResult<NextAction, errors::ParsingError> {
let url = format!("{base_url}/authentication/{authentication_id}/authenticate");
Ok(NextAction {
url: url::Url::parse(&url).change_context(errors::ParsingError::UrlParsingError)?,
http_method: common_utils::request::Method::Post,
})
}
pub fn get_billing_address(&self) -> Option<Address> {
self.billing.clone()
}
pub fn get_shipping_address(&self) -> Option<Address> {
self.shipping.clone()
}
pub fn get_browser_information(&self) -> Option<BrowserInformation> {
self.browser_information.clone()
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, ToSchema)]
pub struct AuthenticationEligibilityResponse {
/// The unique identifier for this authentication.
#[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")]
pub authentication_id: id_type::AuthenticationId,
/// The URL to which the user should be redirected after authentication.
#[schema(value_type = NextAction)]
pub next_action: NextAction,
/// The current status of the authentication (e.g., Started).
#[schema(value_type = AuthenticationStatus)]
pub status: common_enums::AuthenticationStatus,
/// The 3DS data for this authentication.
#[schema(value_type = Option<EligibilityResponseParams>)]
pub eligibility_response_params: Option<EligibilityResponseParams>,
/// The metadata for this authentication.
#[schema(value_type = serde_json::Value)]
pub connector_metadata: Option<serde_json::Value>,
/// The unique identifier for this authentication.
#[schema(value_type = String)]
pub profile_id: id_type::ProfileId,
/// The error message for this authentication.
#[schema(value_type = Option<String>)]
pub error_message: Option<String>,
/// The error code for this authentication.
#[schema(value_type = Option<String>)]
pub error_code: Option<String>,
/// The connector used for this authentication.
#[schema(value_type = Option<AuthenticationConnectors>)]
pub authentication_connector: Option<AuthenticationConnectors>,
/// Billing address
#[schema(value_type = Option<Address>)]
pub billing: Option<Address>,
/// Shipping address
#[schema(value_type = Option<Address>)]
pub shipping: Option<Address>,
/// Browser information
#[schema(value_type = Option<BrowserInformation>)]
pub browser_information: Option<BrowserInformation>,
/// Email
#[schema(value_type = Option<String>)]
pub email: common_utils::crypto::OptionalEncryptableEmail,
/// Acquirer details information.
#[schema(value_type = Option<AcquirerDetails>)]
pub acquirer_details: Option<AcquirerDetails>,
}
#[derive(Debug, Serialize, ToSchema)]
pub enum EligibilityResponseParams {
ThreeDsData(ThreeDsData),
}
#[derive(Debug, Serialize, ToSchema)]
pub struct ThreeDsData {
/// The unique identifier for this authentication from the 3DS server.
#[schema(value_type = String)]
pub three_ds_server_transaction_id: Option<String>,
/// The maximum supported 3DS version.
#[schema(value_type = String)]
pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>,
/// The unique identifier for this authentication from the connector.
#[schema(value_type = String)]
pub connector_authentication_id: Option<String>,
/// The data required to perform the 3DS method.
#[schema(value_type = String)]
pub three_ds_method_data: Option<String>,
/// The URL to which the user should be redirected after authentication.
#[schema(value_type = String, example = "https://example.com/redirect")]
pub three_ds_method_url: Option<url::Url>,
/// The version of the message.
#[schema(value_type = String)]
pub message_version: Option<common_utils::types::SemanticVersion>,
/// The unique identifier for this authentication.
#[schema(value_type = String)]
pub directory_server_id: Option<String>,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct NextAction {
/// The URL for authenticatating the user.
#[schema(value_type = String)]
pub url: url::Url,
/// The HTTP method to use for the request.
#[schema(value_type = Method)]
pub http_method: common_utils::request::Method,
}
#[cfg(feature = "v1")]
impl ApiEventMetric for AuthenticationEligibilityRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for AuthenticationEligibilityResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationAuthenticateRequest {
/// Authentication ID for the authentication
#[serde(skip_deserializing)]
pub authentication_id: id_type::AuthenticationId,
/// Client secret for the authentication
#[schema(value_type = String)]
pub client_secret: Option<masking::Secret<String>>,
/// SDK Information if request is from SDK
pub sdk_information: Option<SdkInformation>,
/// Device Channel indicating whether request is coming from App or Browser
pub device_channel: DeviceChannel,
/// Indicates if 3DS method data was successfully completed or not
pub threeds_method_comp_ind: ThreeDsCompletionIndicator,
}
impl ApiEventMetric for AuthenticationAuthenticateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationAuthenticateResponse {
/// Indicates the transaction status
#[serde(rename = "trans_status")]
#[schema(value_type = Option<TransactionStatus>)]
pub transaction_status: Option<common_enums::TransactionStatus>,
/// Access Server URL to be used for challenge submission
pub acs_url: Option<url::Url>,
/// Challenge request which should be sent to acs_url
pub challenge_request: Option<String>,
/// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa)
pub acs_reference_number: Option<String>,
/// Unique identifier assigned by the ACS to identify a single transaction
pub acs_trans_id: Option<String>,
/// Unique identifier assigned by the 3DS Server to identify a single transaction
pub three_ds_server_transaction_id: Option<String>,
/// Contains the JWS object created by the ACS for the ARes(Authentication Response) message
pub acs_signed_content: Option<String>,
/// Three DS Requestor URL
pub three_ds_requestor_url: String,
/// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred
pub three_ds_requestor_app_url: Option<String>,
/// The error message for this authentication.
#[schema(value_type = String)]
pub error_message: Option<String>,
/// The error code for this authentication.
#[schema(value_type = String)]
pub error_code: Option<String>,
/// The authentication value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern.
#[schema(value_type = String)]
pub authentication_value: Option<masking::Secret<String>>,
/// The current status of the authentication (e.g., Started).
#[schema(value_type = AuthenticationStatus)]
pub status: common_enums::AuthenticationStatus,
/// The connector to be used for authentication, if known.
#[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")]
pub authentication_connector: Option<AuthenticationConnectors>,
/// The unique identifier for this authentication.
#[schema(value_type = AuthenticationId, example = "auth_mbabizu24mvu3mela5njyhpit4")]
pub authentication_id: id_type::AuthenticationId,
/// The ECI value for this authentication.
#[schema(value_type = String)]
pub eci: Option<String>,
/// Acquirer details information.
#[schema(value_type = Option<AcquirerDetails>)]
pub acquirer_details: Option<AcquirerDetails>,
}
impl ApiEventMetric for AuthenticationAuthenticateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct AuthenticationSyncResponse {
// Core Authentication Fields (from AuthenticationResponse)
/// The unique identifier for this authentication.
#[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")]
pub authentication_id: id_type::AuthenticationId,
/// This is an identifier for the merchant account.
#[schema(value_type = String, example = "merchant_abc")]
pub merchant_id: id_type::MerchantId,
/// The current status of the authentication.
#[schema(value_type = AuthenticationStatus)]
pub status: common_enums::AuthenticationStatus,
/// The client secret for this authentication.
#[schema(value_type = Option<String>)]
pub client_secret: Option<masking::Secret<String>>,
/// The amount for the transaction.
#[schema(value_type = MinorUnit, example = 1000)]
pub amount: common_utils::types::MinorUnit,
/// The currency for the transaction.
#[schema(value_type = Currency)]
pub currency: enums::Currency,
/// The connector used for authentication.
#[schema(value_type = Option<AuthenticationConnectors>)]
pub authentication_connector: Option<AuthenticationConnectors>,
/// Whether 3DS challenge was forced.
pub force_3ds_challenge: Option<bool>,
/// The URL to which the user should be redirected after authentication.
pub return_url: Option<String>,
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
/// The business profile that is associated with this authentication.
#[schema(value_type = String)]
pub profile_id: id_type::ProfileId,
/// SCA exemption type for this authentication.
#[schema(value_type = Option<ScaExemptionType>)]
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
/// Acquirer details information.
#[schema(value_type = Option<AcquirerDetails>)]
pub acquirer_details: Option<AcquirerDetails>,
/// The unique identifier from the 3DS server.
#[schema(value_type = Option<String>)]
pub threeds_server_transaction_id: Option<String>,
/// The maximum supported 3DS version.
#[schema(value_type = Option<String>)]
pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>,
/// The unique identifier from the connector.
#[schema(value_type = Option<String>)]
pub connector_authentication_id: Option<String>,
/// The data required to perform the 3DS method.
#[schema(value_type = Option<String>)]
pub three_ds_method_data: Option<String>,
/// The URL for the 3DS method.
#[schema(value_type = Option<String>)]
pub three_ds_method_url: Option<String>,
/// The version of the message.
#[schema(value_type = Option<String>)]
pub message_version: Option<common_utils::types::SemanticVersion>,
/// The metadata for this authentication.
#[schema(value_type = Option<serde_json::Value>)]
pub connector_metadata: Option<serde_json::Value>,
/// The unique identifier for the directory server.
#[schema(value_type = Option<String>)]
pub directory_server_id: Option<String>,
/// Billing address.
#[schema(value_type = Option<Address>)]
pub billing: Option<Address>,
/// Shipping address.
#[schema(value_type = Option<Address>)]
pub shipping: Option<Address>,
/// Browser information.
#[schema(value_type = Option<BrowserInformation>)]
pub browser_information: Option<BrowserInformation>,
/// Email.
#[schema(value_type = Option<String>)]
pub email: common_utils::crypto::OptionalEncryptableEmail,
/// Indicates the transaction status.
#[serde(rename = "trans_status")]
#[schema(value_type = Option<TransactionStatus>)]
pub transaction_status: Option<common_enums::TransactionStatus>,
/// Access Server URL for challenge submission.
pub acs_url: Option<String>,
/// Challenge request to be sent to acs_url.
pub challenge_request: Option<String>,
/// Unique identifier assigned by EMVCo.
pub acs_reference_number: Option<String>,
/// Unique identifier assigned by the ACS.
pub acs_trans_id: Option<String>,
/// JWS object created by the ACS for the ARes message.
pub acs_signed_content: Option<String>,
/// Three DS Requestor URL.
pub three_ds_requestor_url: Option<String>,
/// Merchant app URL for OOB authentication.
pub three_ds_requestor_app_url: Option<String>,
/// The authentication value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern.
#[schema(value_type = Option<String>)]
pub authentication_value: Option<masking::Secret<String>>,
/// ECI value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern.
pub eci: Option<String>,
// Common Error Fields (present in multiple responses)
/// Error message if any.
#[schema(value_type = Option<String>)]
pub error_message: Option<String>,
/// Error code if any.
#[schema(value_type = Option<String>)]
pub error_code: Option<String>,
/// Profile Acquirer ID
#[schema(value_type = Option<String>)]
pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,
}
#[cfg(feature = "v1")]
impl ApiEventMetric for AuthenticationSyncResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationSyncRequest {
/// The client secret for this authentication.
#[schema(value_type = String)]
pub client_secret: Option<masking::Secret<String>>,
/// Authentication ID for the authentication
#[serde(skip_deserializing)]
pub authentication_id: id_type::AuthenticationId,
}
impl ApiEventMetric for AuthenticationSyncRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuthenticationSyncPostUpdateRequest {
/// Authentication ID for the authentication
#[serde(skip_deserializing)]
pub authentication_id: id_type::AuthenticationId,
}
impl ApiEventMetric for AuthenticationSyncPostUpdateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Authentication {
authentication_id: self.authentication_id.clone(),
})
}
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/authentication.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5374
}
|
large_file_-3225915437652452223
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/routing.rs
</path>
<file>
use std::fmt::Debug;
use common_types::three_ds_decision_rule_engine::{ThreeDSDecision, ThreeDSDecisionRule};
use common_utils::{
errors::{ParsingError, ValidationError},
ext_traits::ValueExt,
pii,
};
use euclid::frontend::ast::Program;
pub use euclid::{
dssa::types::EuclidAnalysable,
frontend::{
ast,
dir::{DirKeyKind, EuclidDirFilter},
},
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{
enums::{RoutableConnectors, TransactionType},
open_router,
};
// Define constants for default values
const DEFAULT_LATENCY_THRESHOLD: f64 = 90.0;
const DEFAULT_BUCKET_SIZE: i32 = 200;
const DEFAULT_HEDGING_PERCENT: f64 = 5.0;
const DEFAULT_ELIMINATION_THRESHOLD: f64 = 0.35;
const DEFAULT_PAYMENT_METHOD: &str = "CARD";
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum ConnectorSelection {
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
}
impl ConnectorSelection {
pub fn get_connector_list(&self) -> Vec<RoutableConnectorChoice> {
match self {
Self::Priority(list) => list.clone(),
Self::VolumeSplit(splits) => {
splits.iter().map(|split| split.connector.clone()).collect()
}
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingConfigRequest {
pub name: String,
pub description: String,
pub algorithm: StaticRoutingAlgorithm,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingConfigRequest {
pub name: Option<String>,
pub description: Option<String>,
pub algorithm: Option<StaticRoutingAlgorithm>,
#[schema(value_type = Option<String>)]
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub transaction_type: Option<TransactionType>,
}
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct ProfileDefaultRoutingConfig {
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub connectors: Vec<RoutableConnectorChoice>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveQuery {
pub limit: Option<u16>,
pub offset: Option<u8>,
pub transaction_type: Option<TransactionType>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingActivatePayload {
pub transaction_type: Option<TransactionType>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveLinkQuery {
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub transaction_type: Option<TransactionType>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveLinkQueryWrapper {
pub routing_query: RoutingRetrieveQuery,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
/// Response of the retrieved routing configs for a merchant account
pub struct RoutingRetrieveResponse {
pub algorithm: Option<MerchantRoutingAlgorithm>,
}
#[derive(Debug, serde::Serialize, ToSchema)]
#[serde(untagged)]
pub enum LinkedRoutingConfigRetrieveResponse {
MerchantAccountBased(Box<RoutingRetrieveResponse>),
ProfileBased(Vec<RoutingDictionaryRecord>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
/// Routing Algorithm specific to merchants
pub struct MerchantRoutingAlgorithm {
#[schema(value_type = String)]
pub id: common_utils::id_type::RoutingId,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub name: String,
pub description: String,
pub algorithm: RoutingAlgorithmWrapper,
pub created_at: i64,
pub modified_at: i64,
pub algorithm_for: TransactionType,
}
impl EuclidDirFilter for ConnectorSelection {
const ALLOWED: &'static [DirKeyKind] = &[
DirKeyKind::PaymentMethod,
DirKeyKind::CardBin,
DirKeyKind::CardType,
DirKeyKind::CardNetwork,
DirKeyKind::PayLaterType,
DirKeyKind::WalletType,
DirKeyKind::UpiType,
DirKeyKind::BankRedirectType,
DirKeyKind::BankDebitType,
DirKeyKind::CryptoType,
DirKeyKind::MetaData,
DirKeyKind::PaymentAmount,
DirKeyKind::PaymentCurrency,
DirKeyKind::AuthenticationType,
DirKeyKind::MandateAcceptanceType,
DirKeyKind::MandateType,
DirKeyKind::PaymentType,
DirKeyKind::SetupFutureUsage,
DirKeyKind::CaptureMethod,
DirKeyKind::BillingCountry,
DirKeyKind::BusinessCountry,
DirKeyKind::BusinessLabel,
DirKeyKind::MetaData,
DirKeyKind::RewardType,
DirKeyKind::VoucherType,
DirKeyKind::CardRedirectType,
DirKeyKind::BankTransferType,
DirKeyKind::RealTimePaymentType,
];
}
impl EuclidAnalysable for ConnectorSelection {
fn get_dir_value_for_analysis(
&self,
rule_name: String,
) -> Vec<(euclid::frontend::dir::DirValue, euclid::types::Metadata)> {
self.get_connector_list()
.into_iter()
.map(|connector_choice| {
let connector_name = connector_choice.connector.to_string();
let mca_id = connector_choice.merchant_connector_id.clone();
(
euclid::frontend::dir::DirValue::Connector(Box::new(connector_choice.into())),
std::collections::HashMap::from_iter([(
"CONNECTOR_SELECTION".to_string(),
serde_json::json!({
"rule_name": rule_name,
"connector_name": connector_name,
"mca_id": mca_id,
}),
)]),
)
})
.collect()
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)]
pub struct ConnectorVolumeSplit {
pub connector: RoutableConnectorChoice,
pub split: u8,
}
/// Routable Connector chosen for a payment
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(from = "RoutableChoiceSerde", into = "RoutableChoiceSerde")]
pub struct RoutableConnectorChoice {
#[serde(skip)]
pub choice_kind: RoutableChoiceKind,
pub connector: RoutableConnectors,
#[schema(value_type = Option<String>)]
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, PartialEq)]
pub enum RoutableChoiceKind {
OnlyConnector,
FullStruct,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum RoutableChoiceSerde {
OnlyConnector(Box<RoutableConnectors>),
FullStruct {
connector: RoutableConnectors,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
},
}
impl std::fmt::Display for RoutableConnectorChoice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let base = self.connector.to_string();
if let Some(mca_id) = &self.merchant_connector_id {
return write!(f, "{}:{}", base, mca_id.get_string_repr());
}
write!(f, "{base}")
}
}
impl From<RoutableConnectorChoice> for ast::ConnectorChoice {
fn from(value: RoutableConnectorChoice) -> Self {
Self {
connector: value.connector,
}
}
}
impl PartialEq for RoutableConnectorChoice {
fn eq(&self, other: &Self) -> bool {
self.connector.eq(&other.connector)
&& self.merchant_connector_id.eq(&other.merchant_connector_id)
}
}
impl Eq for RoutableConnectorChoice {}
impl From<RoutableChoiceSerde> for RoutableConnectorChoice {
fn from(value: RoutableChoiceSerde) -> Self {
match value {
RoutableChoiceSerde::OnlyConnector(connector) => Self {
choice_kind: RoutableChoiceKind::OnlyConnector,
connector: *connector,
merchant_connector_id: None,
},
RoutableChoiceSerde::FullStruct {
connector,
merchant_connector_id,
} => Self {
choice_kind: RoutableChoiceKind::FullStruct,
connector,
merchant_connector_id,
},
}
}
}
impl From<RoutableConnectorChoice> for RoutableChoiceSerde {
fn from(value: RoutableConnectorChoice) -> Self {
match value.choice_kind {
RoutableChoiceKind::OnlyConnector => Self::OnlyConnector(Box::new(value.connector)),
RoutableChoiceKind::FullStruct => Self::FullStruct {
connector: value.connector,
merchant_connector_id: value.merchant_connector_id,
},
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct RoutableConnectorChoiceWithStatus {
pub routable_connector_choice: RoutableConnectorChoice,
pub status: bool,
}
impl RoutableConnectorChoiceWithStatus {
pub fn new(routable_connector_choice: RoutableConnectorChoice, status: bool) -> Self {
Self {
routable_connector_choice,
status,
}
}
}
#[derive(
Debug, Copy, Clone, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RoutingAlgorithmKind {
Single,
Priority,
VolumeSplit,
Advanced,
Dynamic,
ThreeDsDecisionRule,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingPayloadWrapper {
pub updated_config: Vec<RoutableConnectorChoice>,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(untagged)]
pub enum RoutingAlgorithmWrapper {
Static(StaticRoutingAlgorithm),
Dynamic(DynamicRoutingAlgorithm),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(untagged)]
pub enum DynamicRoutingAlgorithm {
EliminationBasedAlgorithm(EliminationRoutingConfig),
SuccessBasedAlgorithm(SuccessBasedRoutingConfig),
ContractBasedAlgorithm(ContractBasedRoutingConfig),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(
tag = "type",
content = "data",
rename_all = "snake_case",
try_from = "RoutingAlgorithmSerde"
)]
pub enum StaticRoutingAlgorithm {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
#[schema(value_type=ProgramConnectorSelection)]
Advanced(Program<ConnectorSelection>),
#[schema(value_type=ProgramThreeDsDecisionRule)]
ThreeDsDecisionRule(Program<ThreeDSDecisionRule>),
}
#[derive(Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ProgramThreeDsDecisionRule {
pub default_selection: ThreeDSDecisionRule,
#[schema(value_type = RuleThreeDsDecisionRule)]
pub rules: Vec<ast::Rule<ThreeDSDecisionRule>>,
#[schema(value_type = HashMap<String, serde_json::Value>)]
pub metadata: std::collections::HashMap<String, serde_json::Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct RuleThreeDsDecisionRule {
pub name: String,
pub connector_selection: ThreeDSDecision,
#[schema(value_type = Vec<IfStatement>)]
pub statements: Vec<ast::IfStatement>,
}
impl StaticRoutingAlgorithm {
pub fn should_validate_connectors_in_routing_config(&self) -> bool {
match self {
Self::Single(_) | Self::Priority(_) | Self::VolumeSplit(_) | Self::Advanced(_) => true,
Self::ThreeDsDecisionRule(_) => false,
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RoutingAlgorithmSerde {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
Advanced(Program<ConnectorSelection>),
ThreeDsDecisionRule(Program<ThreeDSDecisionRule>),
}
impl TryFrom<RoutingAlgorithmSerde> for StaticRoutingAlgorithm {
type Error = error_stack::Report<ParsingError>;
fn try_from(value: RoutingAlgorithmSerde) -> Result<Self, Self::Error> {
match &value {
RoutingAlgorithmSerde::Priority(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Priority Algorithm",
))?
}
RoutingAlgorithmSerde::VolumeSplit(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Volume split Algorithm",
))?
}
_ => {}
};
Ok(match value {
RoutingAlgorithmSerde::Single(i) => Self::Single(i),
RoutingAlgorithmSerde::Priority(i) => Self::Priority(i),
RoutingAlgorithmSerde::VolumeSplit(i) => Self::VolumeSplit(i),
RoutingAlgorithmSerde::Advanced(i) => Self::Advanced(i),
RoutingAlgorithmSerde::ThreeDsDecisionRule(i) => Self::ThreeDsDecisionRule(i),
})
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)]
#[serde(
tag = "type",
content = "data",
rename_all = "snake_case",
try_from = "StraightThroughAlgorithmSerde",
into = "StraightThroughAlgorithmSerde"
)]
pub enum StraightThroughAlgorithm {
#[schema(title = "Single")]
Single(Box<RoutableConnectorChoice>),
#[schema(title = "Priority")]
Priority(Vec<RoutableConnectorChoice>),
#[schema(title = "VolumeSplit")]
VolumeSplit(Vec<ConnectorVolumeSplit>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum StraightThroughAlgorithmInner {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum StraightThroughAlgorithmSerde {
Direct(StraightThroughAlgorithmInner),
Nested {
algorithm: StraightThroughAlgorithmInner,
},
}
impl TryFrom<StraightThroughAlgorithmSerde> for StraightThroughAlgorithm {
type Error = error_stack::Report<ParsingError>;
fn try_from(value: StraightThroughAlgorithmSerde) -> Result<Self, Self::Error> {
let inner = match value {
StraightThroughAlgorithmSerde::Direct(algorithm) => algorithm,
StraightThroughAlgorithmSerde::Nested { algorithm } => algorithm,
};
match &inner {
StraightThroughAlgorithmInner::Priority(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Priority Algorithm",
))?
}
StraightThroughAlgorithmInner::VolumeSplit(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Volume split Algorithm",
))?
}
_ => {}
};
Ok(match inner {
StraightThroughAlgorithmInner::Single(single) => Self::Single(single),
StraightThroughAlgorithmInner::Priority(plist) => Self::Priority(plist),
StraightThroughAlgorithmInner::VolumeSplit(vsplit) => Self::VolumeSplit(vsplit),
})
}
}
impl From<StraightThroughAlgorithm> for StraightThroughAlgorithmSerde {
fn from(value: StraightThroughAlgorithm) -> Self {
let inner = match value {
StraightThroughAlgorithm::Single(conn) => StraightThroughAlgorithmInner::Single(conn),
StraightThroughAlgorithm::Priority(plist) => {
StraightThroughAlgorithmInner::Priority(plist)
}
StraightThroughAlgorithm::VolumeSplit(vsplit) => {
StraightThroughAlgorithmInner::VolumeSplit(vsplit)
}
};
Self::Nested { algorithm: inner }
}
}
impl From<StraightThroughAlgorithm> for StaticRoutingAlgorithm {
fn from(value: StraightThroughAlgorithm) -> Self {
match value {
StraightThroughAlgorithm::Single(conn) => Self::Single(conn),
StraightThroughAlgorithm::Priority(conns) => Self::Priority(conns),
StraightThroughAlgorithm::VolumeSplit(splits) => Self::VolumeSplit(splits),
}
}
}
impl StaticRoutingAlgorithm {
pub fn get_kind(&self) -> RoutingAlgorithmKind {
match self {
Self::Single(_) => RoutingAlgorithmKind::Single,
Self::Priority(_) => RoutingAlgorithmKind::Priority,
Self::VolumeSplit(_) => RoutingAlgorithmKind::VolumeSplit,
Self::Advanced(_) => RoutingAlgorithmKind::Advanced,
Self::ThreeDsDecisionRule(_) => RoutingAlgorithmKind::ThreeDsDecisionRule,
}
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingAlgorithmRef {
pub algorithm_id: Option<common_utils::id_type::RoutingId>,
pub timestamp: i64,
pub config_algo_id: Option<String>,
pub surcharge_config_algo_id: Option<String>,
}
impl RoutingAlgorithmRef {
pub fn update_algorithm_id(&mut self, new_id: common_utils::id_type::RoutingId) {
self.algorithm_id = Some(new_id);
self.timestamp = common_utils::date_time::now_unix_timestamp();
}
pub fn update_conditional_config_id(&mut self, ids: String) {
self.config_algo_id = Some(ids);
self.timestamp = common_utils::date_time::now_unix_timestamp();
}
pub fn update_surcharge_config_id(&mut self, ids: String) {
self.surcharge_config_algo_id = Some(ids);
self.timestamp = common_utils::date_time::now_unix_timestamp();
}
pub fn parse_routing_algorithm(
value: Option<pii::SecretSerdeValue>,
) -> Result<Option<Self>, error_stack::Report<ParsingError>> {
value
.map(|val| val.parse_value::<Self>("RoutingAlgorithmRef"))
.transpose()
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingDictionaryRecord {
#[schema(value_type = String)]
pub id: common_utils::id_type::RoutingId,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub name: String,
pub kind: RoutingAlgorithmKind,
pub description: String,
pub created_at: i64,
pub modified_at: i64,
pub algorithm_for: Option<TransactionType>,
pub decision_engine_routing_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingDictionary {
#[schema(value_type = String)]
pub merchant_id: common_utils::id_type::MerchantId,
pub active_id: Option<String>,
pub records: Vec<RoutingDictionaryRecord>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
#[serde(untagged)]
pub enum RoutingKind {
Config(RoutingDictionary),
RoutingAlgorithm(Vec<RoutingDictionaryRecord>),
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
pub struct RoutingAlgorithmId {
#[schema(value_type = String)]
pub routing_algorithm_id: common_utils::id_type::RoutingId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingLinkWrapper {
pub profile_id: common_utils::id_type::ProfileId,
pub algorithm_id: RoutingAlgorithmId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicAlgorithmWithTimestamp<T> {
pub algorithm_id: Option<T>,
pub timestamp: i64,
}
impl<T> DynamicAlgorithmWithTimestamp<T> {
pub fn new(algorithm_id: Option<T>) -> Self {
Self {
algorithm_id,
timestamp: common_utils::date_time::now_unix_timestamp(),
}
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicRoutingAlgorithmRef {
pub success_based_algorithm: Option<SuccessBasedAlgorithm>,
pub dynamic_routing_volume_split: Option<u8>,
pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>,
pub contract_based_routing: Option<ContractRoutingAlgorithm>,
#[serde(default)]
pub is_merchant_created_in_decision_engine: bool,
}
pub trait DynamicRoutingAlgoAccessor {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>;
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures;
}
impl DynamicRoutingAlgoAccessor for SuccessBasedAlgorithm {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
self.algorithm_id_with_timestamp
}
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
&mut self.enabled_feature
}
}
impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
self.algorithm_id_with_timestamp
}
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
&mut self.enabled_feature
}
}
impl DynamicRoutingAlgoAccessor for ContractRoutingAlgorithm {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
self.algorithm_id_with_timestamp
}
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
&mut self.enabled_feature
}
}
impl EliminationRoutingAlgorithm {
pub fn new(
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
common_utils::id_type::RoutingId,
>,
) -> Self {
Self {
algorithm_id_with_timestamp,
enabled_feature: DynamicRoutingFeatures::None,
}
}
}
impl SuccessBasedAlgorithm {
pub fn new(
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
common_utils::id_type::RoutingId,
>,
) -> Self {
Self {
algorithm_id_with_timestamp,
enabled_feature: DynamicRoutingFeatures::None,
}
}
}
impl DynamicRoutingAlgorithmRef {
pub fn update(&mut self, new: Self) {
if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm {
self.elimination_routing_algorithm = Some(elimination_routing_algorithm)
}
if let Some(success_based_algorithm) = new.success_based_algorithm {
self.success_based_algorithm = Some(success_based_algorithm)
}
if let Some(contract_based_routing) = new.contract_based_routing {
self.contract_based_routing = Some(contract_based_routing)
}
}
pub fn update_enabled_features(
&mut self,
algo_type: DynamicRoutingType,
feature_to_enable: DynamicRoutingFeatures,
) {
match algo_type {
DynamicRoutingType::SuccessRateBasedRouting => {
self.success_based_algorithm
.as_mut()
.map(|algo| algo.enabled_feature = feature_to_enable);
}
DynamicRoutingType::EliminationRouting => {
self.elimination_routing_algorithm
.as_mut()
.map(|algo| algo.enabled_feature = feature_to_enable);
}
DynamicRoutingType::ContractBasedRouting => {
self.contract_based_routing
.as_mut()
.map(|algo| algo.enabled_feature = feature_to_enable);
}
}
}
pub fn update_volume_split(&mut self, volume: Option<u8>) {
self.dynamic_routing_volume_split = volume
}
pub fn update_merchant_creation_status_in_decision_engine(&mut self, is_created: bool) {
self.is_merchant_created_in_decision_engine = is_created;
}
pub fn is_success_rate_routing_enabled(&self) -> bool {
self.success_based_algorithm
.as_ref()
.map(|success_based_routing| {
success_based_routing.enabled_feature
== DynamicRoutingFeatures::DynamicConnectorSelection
|| success_based_routing.enabled_feature == DynamicRoutingFeatures::Metrics
})
.unwrap_or_default()
}
pub fn is_elimination_enabled(&self) -> bool {
self.elimination_routing_algorithm
.as_ref()
.map(|elimination_routing| {
elimination_routing.enabled_feature
== DynamicRoutingFeatures::DynamicConnectorSelection
|| elimination_routing.enabled_feature == DynamicRoutingFeatures::Metrics
})
.unwrap_or_default()
}
}
#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct RoutingVolumeSplit {
pub routing_type: RoutingType,
pub split: u8,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingVolumeSplitWrapper {
pub routing_info: RoutingVolumeSplit,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum RoutingType {
#[default]
Static,
Dynamic,
}
impl RoutingType {
pub fn is_dynamic_routing(self) -> bool {
self == Self::Dynamic
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SuccessBasedAlgorithm {
pub algorithm_id_with_timestamp:
DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
#[serde(default)]
pub enabled_feature: DynamicRoutingFeatures,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ContractRoutingAlgorithm {
pub algorithm_id_with_timestamp:
DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
#[serde(default)]
pub enabled_feature: DynamicRoutingFeatures,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EliminationRoutingAlgorithm {
pub algorithm_id_with_timestamp:
DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
#[serde(default)]
pub enabled_feature: DynamicRoutingFeatures,
}
impl EliminationRoutingAlgorithm {
pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) {
self.enabled_feature = feature_to_enable
}
}
impl SuccessBasedAlgorithm {
pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) {
self.enabled_feature = feature_to_enable
}
}
impl DynamicRoutingAlgorithmRef {
pub fn update_algorithm_id(
&mut self,
new_id: common_utils::id_type::RoutingId,
enabled_feature: DynamicRoutingFeatures,
dynamic_routing_type: DynamicRoutingType,
) {
match dynamic_routing_type {
DynamicRoutingType::SuccessRateBasedRouting => {
self.success_based_algorithm = Some(SuccessBasedAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
enabled_feature,
})
}
DynamicRoutingType::EliminationRouting => {
self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
enabled_feature,
})
}
DynamicRoutingType::ContractBasedRouting => {
self.contract_based_routing = Some(ContractRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
enabled_feature,
})
}
};
}
pub fn update_feature(
&mut self,
enabled_feature: DynamicRoutingFeatures,
dynamic_routing_type: DynamicRoutingType,
) {
match dynamic_routing_type {
DynamicRoutingType::SuccessRateBasedRouting => {
self.success_based_algorithm = Some(SuccessBasedAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature,
})
}
DynamicRoutingType::EliminationRouting => {
self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature,
})
}
DynamicRoutingType::ContractBasedRouting => {
self.contract_based_routing = Some(ContractRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature,
})
}
};
}
pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType) {
match dynamic_routing_type {
DynamicRoutingType::SuccessRateBasedRouting => {
if let Some(success_based_algo) = &self.success_based_algorithm {
self.success_based_algorithm = Some(SuccessBasedAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: success_based_algo.enabled_feature,
});
}
}
DynamicRoutingType::EliminationRouting => {
if let Some(elimination_based_algo) = &self.elimination_routing_algorithm {
self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: elimination_based_algo.enabled_feature,
});
}
}
DynamicRoutingType::ContractBasedRouting => {
if let Some(contract_based_algo) = &self.contract_based_routing {
self.contract_based_routing = Some(ContractRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: contract_based_algo.enabled_feature,
});
}
}
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ToggleDynamicRoutingQuery {
pub enable: DynamicRoutingFeatures,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateDynamicRoutingQuery {
pub enable: DynamicRoutingFeatures,
}
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct DynamicRoutingVolumeSplitQuery {
pub split: u8,
}
#[derive(
Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum DynamicRoutingFeatures {
Metrics,
DynamicConnectorSelection,
#[default]
None,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct DynamicRoutingUpdateConfigQuery {
#[schema(value_type = String)]
pub algorithm_id: common_utils::id_type::RoutingId,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ToggleDynamicRoutingWrapper {
pub profile_id: common_utils::id_type::ProfileId,
pub feature_to_enable: DynamicRoutingFeatures,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct ToggleDynamicRoutingPath {
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateDynamicRoutingWrapper {
pub profile_id: common_utils::id_type::ProfileId,
pub feature_to_enable: DynamicRoutingFeatures,
pub payload: DynamicRoutingPayload,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum DynamicRoutingPayload {
SuccessBasedRoutingPayload(SuccessBasedRoutingConfig),
EliminationRoutingPayload(EliminationRoutingConfig),
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct RoutingVolumeSplitResponse {
pub split: u8,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct EliminationRoutingConfig {
pub params: Option<Vec<DynamicRoutingConfigParams>>,
pub elimination_analyser_config: Option<EliminationAnalyserConfig>,
#[schema(value_type = DecisionEngineEliminationData)]
pub decision_engine_configs: Option<open_router::DecisionEngineEliminationData>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct EliminationAnalyserConfig {
pub bucket_size: Option<u64>,
pub bucket_leak_interval_in_secs: Option<u64>,
}
impl EliminationAnalyserConfig {
pub fn update(&mut self, new: Self) {
if let Some(bucket_size) = new.bucket_size {
self.bucket_size = Some(bucket_size)
}
if let Some(bucket_leak_interval_in_secs) = new.bucket_leak_interval_in_secs {
self.bucket_leak_interval_in_secs = Some(bucket_leak_interval_in_secs)
}
}
}
impl Default for EliminationRoutingConfig {
fn default() -> Self {
Self {
params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]),
elimination_analyser_config: Some(EliminationAnalyserConfig {
bucket_size: Some(5),
bucket_leak_interval_in_secs: Some(60),
}),
decision_engine_configs: None,
}
}
}
impl EliminationRoutingConfig {
pub fn update(&mut self, new: Self) {
if let Some(params) = new.params {
self.params = Some(params)
}
if let Some(new_config) = new.elimination_analyser_config {
self.elimination_analyser_config
.as_mut()
.map(|config| config.update(new_config));
}
if let Some(new_config) = new.decision_engine_configs {
self.decision_engine_configs
.as_mut()
.map(|config| config.update(new_config));
}
}
pub fn open_router_config_default() -> Self {
Self {
elimination_analyser_config: None,
params: None,
decision_engine_configs: Some(open_router::DecisionEngineEliminationData {
threshold: DEFAULT_ELIMINATION_THRESHOLD,
}),
}
}
pub fn get_decision_engine_configs(
&self,
) -> Result<open_router::DecisionEngineEliminationData, error_stack::Report<ValidationError>>
{
self.decision_engine_configs
.clone()
.ok_or(error_stack::Report::new(
ValidationError::MissingRequiredField {
field_name: "decision_engine_configs".to_string(),
},
))
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct SuccessBasedRoutingConfig {
pub params: Option<Vec<DynamicRoutingConfigParams>>,
pub config: Option<SuccessBasedRoutingConfigBody>,
#[schema(value_type = DecisionEngineSuccessRateData)]
pub decision_engine_configs: Option<open_router::DecisionEngineSuccessRateData>,
}
impl Default for SuccessBasedRoutingConfig {
fn default() -> Self {
Self {
params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]),
config: Some(SuccessBasedRoutingConfigBody {
min_aggregates_size: Some(5),
default_success_rate: Some(100.0),
max_aggregates_size: Some(8),
current_block_threshold: Some(CurrentBlockThreshold {
duration_in_mins: None,
max_total_count: Some(5),
}),
specificity_level: SuccessRateSpecificityLevel::default(),
exploration_percent: Some(20.0),
shuffle_on_tie_during_exploitation: Some(false),
}),
decision_engine_configs: None,
}
}
}
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, PartialEq, strum::Display,
)]
pub enum DynamicRoutingConfigParams {
PaymentMethod,
PaymentMethodType,
AuthenticationType,
Currency,
Country,
CardNetwork,
CardBin,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
pub struct SuccessBasedRoutingConfigBody {
pub min_aggregates_size: Option<u32>,
pub default_success_rate: Option<f64>,
pub max_aggregates_size: Option<u32>,
pub current_block_threshold: Option<CurrentBlockThreshold>,
#[serde(default)]
pub specificity_level: SuccessRateSpecificityLevel,
pub exploration_percent: Option<f64>,
pub shuffle_on_tie_during_exploitation: Option<bool>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
pub struct CurrentBlockThreshold {
pub duration_in_mins: Option<u64>,
pub max_total_count: Option<u64>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Default, Clone, Copy, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum SuccessRateSpecificityLevel {
#[default]
Merchant,
Global,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SuccessBasedRoutingPayloadWrapper {
pub updated_config: SuccessBasedRoutingConfig,
pub algorithm_id: common_utils::id_type::RoutingId,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EliminationRoutingPayloadWrapper {
pub updated_config: EliminationRoutingConfig,
pub algorithm_id: common_utils::id_type::RoutingId,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ContractBasedRoutingPayloadWrapper {
pub updated_config: ContractBasedRoutingConfig,
pub algorithm_id: common_utils::id_type::RoutingId,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ContractBasedRoutingSetupPayloadWrapper {
pub config: Option<ContractBasedRoutingConfig>,
pub profile_id: common_utils::id_type::ProfileId,
pub features_to_enable: DynamicRoutingFeatures,
}
#[derive(
Debug, Clone, Copy, strum::Display, serde::Serialize, serde::Deserialize, PartialEq, Eq,
)]
pub enum DynamicRoutingType {
SuccessRateBasedRouting,
EliminationRouting,
ContractBasedRouting,
}
impl SuccessBasedRoutingConfig {
pub fn update(&mut self, new: Self) {
if let Some(params) = new.params {
self.params = Some(params)
}
if let Some(new_config) = new.config {
self.config.as_mut().map(|config| config.update(new_config));
}
if let Some(new_config) = new.decision_engine_configs {
self.decision_engine_configs
.as_mut()
.map(|config| config.update(new_config));
}
}
pub fn open_router_config_default() -> Self {
Self {
params: None,
config: None,
decision_engine_configs: Some(open_router::DecisionEngineSuccessRateData {
default_latency_threshold: Some(DEFAULT_LATENCY_THRESHOLD),
default_bucket_size: Some(DEFAULT_BUCKET_SIZE),
default_hedging_percent: Some(DEFAULT_HEDGING_PERCENT),
default_lower_reset_factor: None,
default_upper_reset_factor: None,
default_gateway_extra_score: None,
sub_level_input_config: Some(vec![
open_router::DecisionEngineSRSubLevelInputConfig {
payment_method_type: Some(DEFAULT_PAYMENT_METHOD.to_string()),
payment_method: None,
latency_threshold: None,
bucket_size: Some(DEFAULT_BUCKET_SIZE),
hedging_percent: Some(DEFAULT_HEDGING_PERCENT),
lower_reset_factor: None,
upper_reset_factor: None,
gateway_extra_score: None,
},
]),
}),
}
}
pub fn get_decision_engine_configs(
&self,
) -> Result<open_router::DecisionEngineSuccessRateData, error_stack::Report<ValidationError>>
{
self.decision_engine_configs
.clone()
.ok_or(error_stack::Report::new(
ValidationError::MissingRequiredField {
field_name: "decision_engine_configs".to_string(),
},
))
}
}
impl SuccessBasedRoutingConfigBody {
pub fn update(&mut self, new: Self) {
if let Some(min_aggregates_size) = new.min_aggregates_size {
self.min_aggregates_size = Some(min_aggregates_size)
}
if let Some(default_success_rate) = new.default_success_rate {
self.default_success_rate = Some(default_success_rate)
}
if let Some(max_aggregates_size) = new.max_aggregates_size {
self.max_aggregates_size = Some(max_aggregates_size)
}
if let Some(current_block_threshold) = new.current_block_threshold {
self.current_block_threshold
.as_mut()
.map(|threshold| threshold.update(current_block_threshold));
}
self.specificity_level = new.specificity_level;
if let Some(exploration_percent) = new.exploration_percent {
self.exploration_percent = Some(exploration_percent);
}
if let Some(shuffle_on_tie_during_exploitation) = new.shuffle_on_tie_during_exploitation {
self.shuffle_on_tie_during_exploitation = Some(shuffle_on_tie_during_exploitation);
}
}
}
impl CurrentBlockThreshold {
pub fn update(&mut self, new: Self) {
if let Some(max_total_count) = new.max_total_count {
self.max_total_count = Some(max_total_count)
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct ContractBasedRoutingConfig {
pub config: Option<ContractBasedRoutingConfigBody>,
pub label_info: Option<Vec<LabelInformation>>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct ContractBasedRoutingConfigBody {
pub constants: Option<Vec<f64>>,
pub time_scale: Option<ContractBasedTimeScale>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct LabelInformation {
pub label: String,
pub target_count: u64,
pub target_time: u64,
#[schema(value_type = String)]
pub mca_id: common_utils::id_type::MerchantConnectorAccountId,
}
impl LabelInformation {
pub fn update_target_time(&mut self, new: &Self) {
self.target_time = new.target_time;
}
pub fn update_target_count(&mut self, new: &Self) {
self.target_count = new.target_count;
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ContractBasedTimeScale {
Day,
Month,
}
impl Default for ContractBasedRoutingConfig {
fn default() -> Self {
Self {
config: Some(ContractBasedRoutingConfigBody {
constants: Some(vec![0.7, 0.35]),
time_scale: Some(ContractBasedTimeScale::Day),
}),
label_info: None,
}
}
}
impl ContractBasedRoutingConfig {
pub fn update(&mut self, new: Self) {
if let Some(new_config) = new.config {
self.config.as_mut().map(|config| config.update(new_config));
}
if let Some(new_label_info) = new.label_info {
new_label_info.iter().for_each(|new_label_info| {
if let Some(existing_label_infos) = &mut self.label_info {
let mut updated = false;
for existing_label_info in &mut *existing_label_infos {
if existing_label_info.mca_id == new_label_info.mca_id {
existing_label_info.update_target_time(new_label_info);
existing_label_info.update_target_count(new_label_info);
updated = true;
}
}
if !updated {
existing_label_infos.push(new_label_info.clone());
}
} else {
self.label_info = Some(vec![new_label_info.clone()]);
}
});
}
}
}
impl ContractBasedRoutingConfigBody {
pub fn update(&mut self, new: Self) {
if let Some(new_cons) = new.constants {
self.constants = Some(new_cons)
}
if let Some(new_time_scale) = new.time_scale {
self.time_scale = Some(new_time_scale)
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct RoutableConnectorChoiceWithBucketName {
pub routable_connector_choice: RoutableConnectorChoice,
pub bucket_name: String,
}
impl RoutableConnectorChoiceWithBucketName {
pub fn new(routable_connector_choice: RoutableConnectorChoice, bucket_name: String) -> Self {
Self {
routable_connector_choice,
bucket_name,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateConfigEventRequest {
pub min_aggregates_size: Option<u32>,
pub default_success_rate: Option<f64>,
pub specificity_level: SuccessRateSpecificityLevel,
pub exploration_percent: Option<f64>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<CalSuccessRateConfigEventRequest>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationRoutingEventBucketConfig {
pub bucket_size: Option<u64>,
pub bucket_leak_interval_in_secs: Option<u64>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationRoutingEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<EliminationRoutingEventBucketConfig>,
}
/// API-1 types
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalContractScoreEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<ContractBasedRoutingConfig>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LabelWithScoreEventResponse {
pub score: f64,
pub label: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateEventResponse {
pub labels_with_score: Vec<LabelWithScoreEventResponse>,
pub routing_approach: RoutingApproach,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RoutingApproach {
Exploitation,
Exploration,
Elimination,
ContractBased,
Default,
}
impl RoutingApproach {
pub fn from_decision_engine_approach(approach: &str) -> Self {
match approach {
"SR_SELECTION_V3_ROUTING" => Self::Exploitation,
"SR_V3_HEDGING" => Self::Exploration,
_ => Self::Default,
}
}
}
impl std::fmt::Display for RoutingApproach {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Exploitation => write!(f, "Exploitation"),
Self::Exploration => write!(f, "Exploration"),
Self::Elimination => write!(f, "Elimination"),
Self::ContractBased => write!(f, "ContractBased"),
Self::Default => write!(f, "Default"),
}
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RuleMigrationQuery {
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub limit: Option<u32>,
pub offset: Option<u32>,
}
impl RuleMigrationQuery {
pub fn validated_limit(&self) -> u32 {
self.limit.unwrap_or(50).min(1000)
}
}
#[derive(Debug, serde::Serialize)]
pub struct RuleMigrationResult {
pub success: Vec<RuleMigrationResponse>,
pub errors: Vec<RuleMigrationError>,
}
#[derive(Debug, serde::Serialize)]
pub struct RuleMigrationResponse {
pub profile_id: common_utils::id_type::ProfileId,
pub euclid_algorithm_id: common_utils::id_type::RoutingId,
pub decision_engine_algorithm_id: String,
pub is_active_rule: bool,
}
#[derive(Debug, serde::Serialize)]
pub struct RuleMigrationError {
pub profile_id: common_utils::id_type::ProfileId,
pub algorithm_id: common_utils::id_type::RoutingId,
pub error: String,
}
impl RuleMigrationResponse {
pub fn new(
profile_id: common_utils::id_type::ProfileId,
euclid_algorithm_id: common_utils::id_type::RoutingId,
decision_engine_algorithm_id: String,
is_active_rule: bool,
) -> Self {
Self {
profile_id,
euclid_algorithm_id,
decision_engine_algorithm_id,
is_active_rule,
}
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RoutingResultSource {
/// External Decision Engine
DecisionEngine,
/// Inbuilt Hyperswitch Routing Engine
HyperswitchRouting,
}
//TODO: temporary change will be refactored afterwards
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)]
pub struct RoutingEvaluateRequest {
pub created_by: String,
#[schema(value_type = Object)]
///Parameters that can be used in the routing evaluate request.
///eg: {"parameters": {
/// "payment_method": {"type": "enum_variant", "value": "card"},
/// "payment_method_type": {"type": "enum_variant", "value": "credit"},
/// "amount": {"type": "number", "value": 10},
/// "currency": {"type": "str_value", "value": "INR"},
/// "authentication_type": {"type": "enum_variant", "value": "three_ds"},
/// "card_bin": {"type": "str_value", "value": "424242"},
/// "capture_method": {"type": "enum_variant", "value": "scheduled"},
/// "business_country": {"type": "str_value", "value": "IN"},
/// "billing_country": {"type": "str_value", "value": "IN"},
/// "business_label": {"type": "str_value", "value": "business_label"},
/// "setup_future_usage": {"type": "enum_variant", "value": "off_session"},
/// "card_network": {"type": "enum_variant", "value": "visa"},
/// "payment_type": {"type": "enum_variant", "value": "recurring_mandate"},
/// "mandate_type": {"type": "enum_variant", "value": "single_use"},
/// "mandate_acceptance_type": {"type": "enum_variant", "value": "online"},
/// "metadata":{"type": "metadata_variant", "value": {"key": "key1", "value": "value1"}}
/// }}
pub parameters: std::collections::HashMap<String, Option<ValueType>>,
pub fallback_output: Vec<DeRoutableConnectorChoice>,
}
impl common_utils::events::ApiEventMetric for RoutingEvaluateRequest {}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct RoutingEvaluateResponse {
pub status: String,
pub output: serde_json::Value,
#[serde(deserialize_with = "deserialize_connector_choices")]
pub evaluated_output: Vec<RoutableConnectorChoice>,
#[serde(deserialize_with = "deserialize_connector_choices")]
pub eligible_connectors: Vec<RoutableConnectorChoice>,
}
impl common_utils::events::ApiEventMetric for RoutingEvaluateResponse {}
fn deserialize_connector_choices<'de, D>(
deserializer: D,
) -> Result<Vec<RoutableConnectorChoice>, D::Error>
where
D: serde::Deserializer<'de>,
{
let infos = Vec::<DeRoutableConnectorChoice>::deserialize(deserializer)?;
Ok(infos
.into_iter()
.map(RoutableConnectorChoice::from)
.collect())
}
impl From<DeRoutableConnectorChoice> for RoutableConnectorChoice {
fn from(choice: DeRoutableConnectorChoice) -> Self {
Self {
choice_kind: RoutableChoiceKind::FullStruct,
connector: choice.gateway_name,
merchant_connector_id: choice.gateway_id,
}
}
}
/// Routable Connector chosen for a payment
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct DeRoutableConnectorChoice {
pub gateway_name: RoutableConnectors,
#[schema(value_type = String)]
pub gateway_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
/// Represents a value in the DSL
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum ValueType {
/// Represents a number literal
Number(u64),
/// Represents an enum variant
EnumVariant(String),
/// Represents a Metadata variant
MetadataVariant(MetadataValue),
/// Represents a arbitrary String value
StrValue(String),
/// Represents a global reference, which is a reference to a global variable
GlobalRef(String),
/// Represents an array of numbers. This is basically used for
/// "one of the given numbers" operations
/// eg: payment.method.amount = (1, 2, 3)
NumberArray(Vec<u64>),
/// Similar to NumberArray but for enum variants
/// eg: payment.method.cardtype = (debit, credit)
EnumVariantArray(Vec<String>),
/// Like a number array but can include comparisons. Useful for
/// conditions like "500 < amount < 1000"
/// eg: payment.amount = (> 500, < 1000)
NumberComparisonArray(Vec<NumberComparison>),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
pub struct MetadataValue {
pub key: String,
pub value: String,
}
/// Represents a number comparison for "NumberComparisonArrayValue"
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct NumberComparison {
pub comparison_type: ComparisonType,
pub number: u64,
}
/// Conditional comparison type
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ComparisonType {
Equal,
NotEqual,
LessThan,
LessThanEqual,
GreaterThan,
GreaterThanEqual,
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/routing.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 12091
}
|
large_file_-8378428666220114702
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/payments/additional_info.rs
</path>
<file>
use common_utils::new_type::{
MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId,
};
use masking::Secret;
use utoipa::ToSchema;
use crate::enums as api_enums;
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum BankDebitAdditionalData {
Ach(Box<AchBankDebitAdditionalData>),
Bacs(Box<BacsBankDebitAdditionalData>),
Becs(Box<BecsBankDebitAdditionalData>),
Sepa(Box<SepaBankDebitAdditionalData>),
SepaGuarenteedDebit(Box<SepaBankDebitAdditionalData>),
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct AchBankDebitAdditionalData {
/// Partially masked account number for ach bank debit payment
#[schema(value_type = String, example = "0001****3456")]
pub account_number: MaskedBankAccount,
/// Partially masked routing number for ach bank debit payment
#[schema(value_type = String, example = "110***000")]
pub routing_number: MaskedRoutingNumber,
/// Card holder's name
#[schema(value_type = Option<String>, example = "John Doe")]
pub card_holder_name: Option<Secret<String>>,
/// Bank account's owner name
#[schema(value_type = Option<String>, example = "John Doe")]
pub bank_account_holder_name: Option<Secret<String>>,
/// Name of the bank
#[schema(value_type = Option<BankNames>, example = "ach")]
pub bank_name: Option<common_enums::BankNames>,
/// Bank account type
#[schema(value_type = Option<BankType>, example = "checking")]
pub bank_type: Option<common_enums::BankType>,
/// Bank holder entity type
#[schema(value_type = Option<BankHolderType>, example = "personal")]
pub bank_holder_type: Option<common_enums::BankHolderType>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct BacsBankDebitAdditionalData {
/// Partially masked account number for Bacs payment method
#[schema(value_type = String, example = "0001****3456")]
pub account_number: MaskedBankAccount,
/// Partially masked sort code for Bacs payment method
#[schema(value_type = String, example = "108800")]
pub sort_code: MaskedSortCode,
/// Bank account's owner name
#[schema(value_type = Option<String>, example = "John Doe")]
pub bank_account_holder_name: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct BecsBankDebitAdditionalData {
/// Partially masked account number for Becs payment method
#[schema(value_type = String, example = "0001****3456")]
pub account_number: MaskedBankAccount,
/// Bank-State-Branch (bsb) number
#[schema(value_type = String, example = "000000")]
pub bsb_number: Secret<String>,
/// Bank account's owner name
#[schema(value_type = Option<String>, example = "John Doe")]
pub bank_account_holder_name: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct SepaBankDebitAdditionalData {
/// Partially masked international bank account number (iban) for SEPA
#[schema(value_type = String, example = "DE8937******013000")]
pub iban: MaskedIban,
/// Bank account's owner name
#[schema(value_type = Option<String>, example = "John Doe")]
pub bank_account_holder_name: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub enum BankRedirectDetails {
BancontactCard(Box<BancontactBankRedirectAdditionalData>),
Blik(Box<BlikBankRedirectAdditionalData>),
Giropay(Box<GiropayBankRedirectAdditionalData>),
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct BancontactBankRedirectAdditionalData {
/// Last 4 digits of the card number
#[schema(value_type = Option<String>, example = "4242")]
pub last4: Option<String>,
/// The card's expiry month
#[schema(value_type = Option<String>, example = "12")]
pub card_exp_month: Option<Secret<String>>,
/// The card's expiry year
#[schema(value_type = Option<String>, example = "24")]
pub card_exp_year: Option<Secret<String>>,
/// The card holder's name
#[schema(value_type = Option<String>, example = "John Test")]
pub card_holder_name: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct BlikBankRedirectAdditionalData {
#[schema(value_type = Option<String>, example = "3GD9MO")]
pub blik_code: Option<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct GiropayBankRedirectAdditionalData {
#[schema(value_type = Option<String>)]
/// Masked bank account bic code
pub bic: Option<MaskedSortCode>,
/// Partially masked international bank account number (iban) for SEPA
#[schema(value_type = Option<String>)]
pub iban: Option<MaskedIban>,
/// Country for bank payment
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub country: Option<api_enums::CountryAlpha2>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum BankTransferAdditionalData {
Ach {},
Sepa {},
Bacs {},
Multibanco {},
Permata {},
Bca {},
BniVa {},
BriVa {},
CimbVa {},
DanamonVa {},
MandiriVa {},
Pix(Box<PixBankTransferAdditionalData>),
Pse {},
LocalBankTransfer(Box<LocalBankTransferAdditionalData>),
InstantBankTransfer {},
InstantBankTransferFinland {},
InstantBankTransferPoland {},
IndonesianBankTransfer {
#[schema(value_type = Option<BankNames>, example = "bri")]
bank_name: Option<common_enums::BankNames>,
},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PixBankTransferAdditionalData {
/// Partially masked unique key for pix transfer
#[schema(value_type = Option<String>, example = "a1f4102e ****** 6fa48899c1d1")]
pub pix_key: Option<MaskedBankAccount>,
/// Partially masked CPF - CPF is a Brazilian tax identification number
#[schema(value_type = Option<String>, example = "**** 124689")]
pub cpf: Option<MaskedBankAccount>,
/// Partially masked CNPJ - CNPJ is a Brazilian company tax identification number
#[schema(value_type = Option<String>, example = "**** 417312")]
pub cnpj: Option<MaskedBankAccount>,
/// Partially masked source bank account number
#[schema(value_type = Option<String>, example = "********-****-4073-****-9fa964d08bc5")]
pub source_bank_account_id: Option<MaskedBankAccount>,
/// Partially masked destination bank account number _Deprecated: Will be removed in next stable release._
#[schema(value_type = Option<String>, example = "********-****-460b-****-f23b4e71c97b", deprecated)]
pub destination_bank_account_id: Option<MaskedBankAccount>,
/// The expiration date and time for the Pix QR code in ISO 8601 format
#[schema(value_type = Option<String>, example = "2025-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub expiry_date: Option<time::PrimitiveDateTime>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct LocalBankTransferAdditionalData {
/// Partially masked bank code
#[schema(value_type = Option<String>, example = "**** OA2312")]
pub bank_code: Option<MaskedBankAccount>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum GiftCardAdditionalData {
Givex(Box<GivexGiftCardAdditionalData>),
PaySafeCard {},
BhnCardNetwork {},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct GivexGiftCardAdditionalData {
/// Last 4 digits of the gift card number
#[schema(value_type = String, example = "4242")]
pub last4: Secret<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct CardTokenAdditionalData {
/// The card holder's name
#[schema(value_type = String, example = "John Test")]
pub card_holder_name: Option<Secret<String>>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum UpiAdditionalData {
UpiCollect(Box<UpiCollectAdditionalData>),
#[schema(value_type = UpiIntentData)]
UpiIntent(Box<super::UpiIntentData>),
#[schema(value_type = UpiQrData)]
UpiQr(Box<super::UpiQrData>),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct UpiCollectAdditionalData {
/// Masked VPA ID
#[schema(value_type = Option<String>, example = "ab********@okhdfcbank")]
pub vpa_id: Option<MaskedUpiVpaId>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct WalletAdditionalDataForCard {
/// Last 4 digits of the card number
pub last4: String,
/// The information of the payment method
pub card_network: String,
/// The type of payment method
#[serde(rename = "type")]
pub card_type: Option<String>,
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/payments/additional_info.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2453
}
|
large_file_8567644577564322737
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/events/payment.rs
</path>
<file>
use common_utils::events::{ApiEventMetric, ApiEventsType};
#[cfg(feature = "v2")]
use super::{
PaymentAttemptListRequest, PaymentAttemptListResponse, PaymentStartRedirectionRequest,
PaymentsCreateIntentRequest, PaymentsGetIntentRequest, PaymentsIntentResponse, PaymentsRequest,
RecoveryPaymentsCreate, RecoveryPaymentsResponse,
};
#[cfg(feature = "v2")]
use crate::payment_methods::{
ListMethodsForPaymentMethodsRequest, PaymentMethodListResponseForSession,
};
use crate::{
payment_methods::{
self, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse,
PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest,
PaymentMethodCollectLinkResponse, PaymentMethodMigrateResponse, PaymentMethodResponse,
PaymentMethodUpdate,
},
payments::{
self, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2,
PaymentListResponse, PaymentsAggregateResponse, PaymentsSessionResponse,
RedirectionResponse,
},
};
#[cfg(feature = "v1")]
use crate::{
payment_methods::{PaymentMethodListRequest, PaymentMethodListResponse},
payments::{
ExtendedCardInfoResponse, PaymentIdType, PaymentListFilterConstraints,
PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelPostCaptureRequest,
PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest,
PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse,
PaymentsExtendAuthorizationRequest, PaymentsExternalAuthenticationRequest,
PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest,
PaymentsManualUpdateRequest, PaymentsManualUpdateResponse,
PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRejectRequest,
PaymentsRetrieveRequest, PaymentsStartRequest, PaymentsUpdateMetadataRequest,
PaymentsUpdateMetadataResponse,
},
};
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsRetrieveRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
match self.resource_id {
PaymentIdType::PaymentIntentId(ref id) => Some(ApiEventsType::Payment {
payment_id: id.clone(),
}),
_ => None,
}
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsStartRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsCaptureRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.to_owned(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsCompleteAuthorizeRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsDynamicTaxCalculationRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsPostSessionTokensRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsUpdateMetadataRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsUpdateMetadataResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsPostSessionTokensResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsDynamicTaxCalculationResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsCancelRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsCancelPostCaptureRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsExtendAuthorizationRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsApproveRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsRejectRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for payments::PaymentsRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
match self.payment_id {
Some(PaymentIdType::PaymentIntentId(ref id)) => Some(ApiEventsType::Payment {
payment_id: id.clone(),
}),
_ => None,
}
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for payments::PaymentsEligibilityRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for payments::PaymentsEligibilityResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsCreateIntentRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::GiftCardBalanceCheckResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsGetIntentRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentAttemptListRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_intent_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentAttemptListResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsIntentResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentsResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentsCancelRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentsCancelResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for payments::PaymentsResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
impl ApiEventMetric for PaymentMethodResponse {
#[cfg(feature = "v1")]
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_id.clone(),
payment_method: self.payment_method,
payment_method_type: self.payment_method_type,
})
}
#[cfg(feature = "v2")]
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.id.clone(),
payment_method_type: self.payment_method_type,
payment_method_subtype: self.payment_method_subtype,
})
}
}
impl ApiEventMetric for PaymentMethodMigrateResponse {
#[cfg(feature = "v1")]
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_response.payment_method_id.clone(),
payment_method: self.payment_method_response.payment_method,
payment_method_type: self.payment_method_response.payment_method_type,
})
}
#[cfg(feature = "v2")]
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_response.id.clone(),
payment_method_type: self.payment_method_response.payment_method_type,
payment_method_subtype: self.payment_method_response.payment_method_subtype,
})
}
}
impl ApiEventMetric for PaymentMethodUpdate {}
#[cfg(feature = "v1")]
impl ApiEventMetric for payment_methods::DefaultPaymentMethod {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_id.clone(),
payment_method: None,
payment_method_type: None,
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payment_methods::PaymentMethodDeleteResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.id.clone(),
payment_method_type: None,
payment_method_subtype: None,
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for payment_methods::PaymentMethodDeleteResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_id.clone(),
payment_method: None,
payment_method_type: None,
})
}
}
impl ApiEventMetric for payment_methods::CustomerPaymentMethodsListResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentMethodListRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethodList {
payment_id: self
.client_secret
.as_ref()
.and_then(|cs| cs.rsplit_once("_secret_"))
.map(|(pid, _)| pid.to_string()),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for ListMethodsForPaymentMethodsRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethodList {
payment_id: self
.client_secret
.as_ref()
.and_then(|cs| cs.rsplit_once("_secret_"))
.map(|(pid, _)| pid.to_string()),
})
}
}
impl ApiEventMetric for ListCountriesCurrenciesRequest {}
impl ApiEventMetric for ListCountriesCurrenciesResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentMethodListResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for payment_methods::CustomerDefaultPaymentMethodResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.default_payment_method_id.clone().unwrap_or_default(),
payment_method: Some(self.payment_method),
payment_method_type: self.payment_method_type,
})
}
}
impl ApiEventMetric for PaymentMethodCollectLinkRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
self.pm_collect_link_id
.as_ref()
.map(|id| ApiEventsType::PaymentMethodCollectLink {
link_id: id.clone(),
})
}
}
impl ApiEventMetric for PaymentMethodCollectLinkRenderRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethodCollectLink {
link_id: self.pm_collect_link_id.clone(),
})
}
}
impl ApiEventMetric for PaymentMethodCollectLinkResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethodCollectLink {
link_id: self.pm_collect_link_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentListFilterConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PaymentListFilters {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PaymentListFiltersV2 {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PaymentListConstraints {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PaymentListResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for RecoveryPaymentsCreate {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for RecoveryPaymentsResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentListResponseV2 {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for PaymentsAggregateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::ResourceListAPI)
}
}
impl ApiEventMetric for RedirectionResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsIncrementalAuthorizationRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsExternalAuthenticationResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsExternalAuthenticationRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for ExtendedCardInfoResponse {}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsManualUpdateRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsManualUpdateResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
impl ApiEventMetric for PaymentsSessionResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.payment_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentStartRedirectionRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentMethodListResponseForPayments {
// Payment id would be populated by the request
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentMethodListResponseForSession {}
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentsCaptureResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
})
}
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/events/payment.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3896
}
|
large_file_8811878837615013302
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/analytics/payments.rs
</path>
<file>
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use common_utils::id_type;
use super::{ForexMetric, NameDescription, TimeRange};
use crate::enums::{
AttemptStatus, AuthenticationType, CardNetwork, Connector, Currency, PaymentMethod,
PaymentMethodType, RoutingApproach,
};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct PaymentFilters {
#[serde(default)]
pub currency: Vec<Currency>,
#[serde(default)]
pub status: Vec<AttemptStatus>,
#[serde(default)]
pub connector: Vec<Connector>,
#[serde(default)]
pub auth_type: Vec<AuthenticationType>,
#[serde(default)]
pub payment_method: Vec<PaymentMethod>,
#[serde(default)]
pub payment_method_type: Vec<PaymentMethodType>,
#[serde(default)]
pub client_source: Vec<String>,
#[serde(default)]
pub client_version: Vec<String>,
#[serde(default)]
pub card_network: Vec<CardNetwork>,
#[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
#[serde(default)]
pub merchant_id: Vec<id_type::MerchantId>,
#[serde(default)]
pub card_last_4: Vec<String>,
#[serde(default)]
pub card_issuer: Vec<String>,
#[serde(default)]
pub error_reason: Vec<String>,
#[serde(default)]
pub first_attempt: Vec<bool>,
#[serde(default)]
pub routing_approach: Vec<RoutingApproach>,
#[serde(default)]
pub signature_network: Vec<String>,
#[serde(default)]
pub is_issuer_regulated: Vec<bool>,
#[serde(default)]
pub is_debit_routed: Vec<bool>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentDimensions {
// Do not change the order of these enums
// Consult the Dashboard FE folks since these also affects the order of metrics on FE
Connector,
PaymentMethod,
PaymentMethodType,
Currency,
#[strum(serialize = "authentication_type")]
#[serde(rename = "authentication_type")]
AuthType,
#[strum(serialize = "status")]
#[serde(rename = "status")]
PaymentStatus,
ClientSource,
ClientVersion,
ProfileId,
CardNetwork,
MerchantId,
#[strum(serialize = "card_last_4")]
#[serde(rename = "card_last_4")]
CardLast4,
CardIssuer,
ErrorReason,
RoutingApproach,
SignatureNetwork,
IsIssuerRegulated,
IsDebitRouted,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentMetrics {
PaymentSuccessRate,
PaymentCount,
PaymentSuccessCount,
PaymentProcessedAmount,
AvgTicketSize,
RetriesCount,
ConnectorSuccessRate,
DebitRouting,
SessionizedPaymentSuccessRate,
SessionizedPaymentCount,
SessionizedPaymentSuccessCount,
SessionizedPaymentProcessedAmount,
SessionizedAvgTicketSize,
SessionizedRetriesCount,
SessionizedConnectorSuccessRate,
SessionizedDebitRouting,
PaymentsDistribution,
FailureReasons,
}
impl ForexMetric for PaymentMetrics {
fn is_forex_metric(&self) -> bool {
matches!(
self,
Self::PaymentProcessedAmount
| Self::AvgTicketSize
| Self::DebitRouting
| Self::SessionizedPaymentProcessedAmount
| Self::SessionizedAvgTicketSize
| Self::SessionizedDebitRouting,
)
}
}
#[derive(Debug, Default, serde::Serialize)]
pub struct ErrorResult {
pub reason: String,
pub count: i64,
pub percentage: f64,
}
#[derive(
Clone,
Copy,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum PaymentDistributions {
#[strum(serialize = "error_message")]
PaymentErrorMessage,
}
pub mod metric_behaviour {
pub struct PaymentSuccessRate;
pub struct PaymentCount;
pub struct PaymentSuccessCount;
pub struct PaymentProcessedAmount;
pub struct AvgTicketSize;
}
impl From<PaymentMetrics> for NameDescription {
fn from(value: PaymentMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<PaymentDimensions> for NameDescription {
fn from(value: PaymentDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct PaymentMetricsBucketIdentifier {
pub currency: Option<Currency>,
pub status: Option<AttemptStatus>,
pub connector: Option<String>,
#[serde(rename = "authentication_type")]
pub auth_type: Option<AuthenticationType>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub profile_id: Option<String>,
pub card_network: Option<String>,
pub merchant_id: Option<String>,
pub card_last_4: Option<String>,
pub card_issuer: Option<String>,
pub error_reason: Option<String>,
pub routing_approach: Option<RoutingApproach>,
pub signature_network: Option<String>,
pub is_issuer_regulated: Option<bool>,
pub is_debit_routed: Option<bool>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
// Coz FE sucks
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl PaymentMetricsBucketIdentifier {
#[allow(clippy::too_many_arguments)]
pub fn new(
currency: Option<Currency>,
status: Option<AttemptStatus>,
connector: Option<String>,
auth_type: Option<AuthenticationType>,
payment_method: Option<String>,
payment_method_type: Option<String>,
client_source: Option<String>,
client_version: Option<String>,
profile_id: Option<String>,
card_network: Option<String>,
merchant_id: Option<String>,
card_last_4: Option<String>,
card_issuer: Option<String>,
error_reason: Option<String>,
routing_approach: Option<RoutingApproach>,
signature_network: Option<String>,
is_issuer_regulated: Option<bool>,
is_debit_routed: Option<bool>,
normalized_time_range: TimeRange,
) -> Self {
Self {
currency,
status,
connector,
auth_type,
payment_method,
payment_method_type,
client_source,
client_version,
profile_id,
card_network,
merchant_id,
card_last_4,
card_issuer,
error_reason,
routing_approach,
signature_network,
is_issuer_regulated,
is_debit_routed,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
impl Hash for PaymentMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.currency.hash(state);
self.status.map(|i| i.to_string()).hash(state);
self.connector.hash(state);
self.auth_type.map(|i| i.to_string()).hash(state);
self.payment_method.hash(state);
self.payment_method_type.hash(state);
self.client_source.hash(state);
self.client_version.hash(state);
self.profile_id.hash(state);
self.card_network.hash(state);
self.merchant_id.hash(state);
self.card_last_4.hash(state);
self.card_issuer.hash(state);
self.error_reason.hash(state);
self.routing_approach
.clone()
.map(|i| i.to_string())
.hash(state);
self.signature_network.hash(state);
self.is_issuer_regulated.hash(state);
self.is_debit_routed.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for PaymentMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct PaymentMetricsBucketValue {
pub payment_success_rate: Option<f64>,
pub payment_count: Option<u64>,
pub payment_success_count: Option<u64>,
pub payment_processed_amount: Option<u64>,
pub payment_processed_amount_in_usd: Option<u64>,
pub payment_processed_count: Option<u64>,
pub payment_processed_amount_without_smart_retries: Option<u64>,
pub payment_processed_amount_without_smart_retries_usd: Option<u64>,
pub payment_processed_count_without_smart_retries: Option<u64>,
pub avg_ticket_size: Option<f64>,
pub payment_error_message: Option<Vec<ErrorResult>>,
pub retries_count: Option<u64>,
pub retries_amount_processed: Option<u64>,
pub connector_success_rate: Option<f64>,
pub payments_success_rate_distribution: Option<f64>,
pub payments_success_rate_distribution_without_smart_retries: Option<f64>,
pub payments_success_rate_distribution_with_only_retries: Option<f64>,
pub payments_failure_rate_distribution: Option<f64>,
pub payments_failure_rate_distribution_without_smart_retries: Option<f64>,
pub payments_failure_rate_distribution_with_only_retries: Option<f64>,
pub failure_reason_count: Option<u64>,
pub failure_reason_count_without_smart_retries: Option<u64>,
pub debit_routed_transaction_count: Option<u64>,
pub debit_routing_savings: Option<u64>,
pub debit_routing_savings_in_usd: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: PaymentMetricsBucketValue,
#[serde(flatten)]
pub dimensions: PaymentMetricsBucketIdentifier,
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/analytics/payments.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2339
}
|
large_file_2693833652179268185
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: api_models
File: crates/api_models/src/analytics/auth_events.rs
</path>
<file>
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use common_enums::{
AuthenticationConnectors, AuthenticationStatus, Currency, DecoupledAuthenticationType,
TransactionStatus,
};
use super::{NameDescription, TimeRange};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct AuthEventFilters {
#[serde(default)]
pub authentication_status: Vec<AuthenticationStatus>,
#[serde(default)]
pub trans_status: Vec<TransactionStatus>,
#[serde(default)]
pub authentication_type: Vec<DecoupledAuthenticationType>,
#[serde(default)]
pub error_message: Vec<String>,
#[serde(default)]
pub authentication_connector: Vec<AuthenticationConnectors>,
#[serde(default)]
pub message_version: Vec<String>,
#[serde(default)]
pub platform: Vec<String>,
#[serde(default)]
pub acs_reference_number: Vec<String>,
#[serde(default)]
pub mcc: Vec<String>,
#[serde(default)]
pub currency: Vec<Currency>,
#[serde(default)]
pub merchant_country: Vec<String>,
#[serde(default)]
pub billing_country: Vec<String>,
#[serde(default)]
pub shipping_country: Vec<String>,
#[serde(default)]
pub issuer_country: Vec<String>,
#[serde(default)]
pub earliest_supported_version: Vec<String>,
#[serde(default)]
pub latest_supported_version: Vec<String>,
#[serde(default)]
pub whitelist_decision: Vec<bool>,
#[serde(default)]
pub device_manufacturer: Vec<String>,
#[serde(default)]
pub device_type: Vec<String>,
#[serde(default)]
pub device_brand: Vec<String>,
#[serde(default)]
pub device_os: Vec<String>,
#[serde(default)]
pub device_display: Vec<String>,
#[serde(default)]
pub browser_name: Vec<String>,
#[serde(default)]
pub browser_version: Vec<String>,
#[serde(default)]
pub issuer_id: Vec<String>,
#[serde(default)]
pub scheme_name: Vec<String>,
#[serde(default)]
pub exemption_requested: Vec<bool>,
#[serde(default)]
pub exemption_accepted: Vec<bool>,
}
#[derive(
Debug,
serde::Serialize,
serde::Deserialize,
strum::AsRefStr,
PartialEq,
PartialOrd,
Eq,
Ord,
strum::Display,
strum::EnumIter,
Clone,
Copy,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AuthEventDimensions {
AuthenticationStatus,
#[strum(serialize = "trans_status")]
#[serde(rename = "trans_status")]
TransactionStatus,
AuthenticationType,
ErrorMessage,
AuthenticationConnector,
MessageVersion,
AcsReferenceNumber,
Platform,
Mcc,
Currency,
MerchantCountry,
BillingCountry,
ShippingCountry,
IssuerCountry,
EarliestSupportedVersion,
LatestSupportedVersion,
WhitelistDecision,
DeviceManufacturer,
DeviceType,
DeviceBrand,
DeviceOs,
DeviceDisplay,
BrowserName,
BrowserVersion,
IssuerId,
SchemeName,
ExemptionRequested,
ExemptionAccepted,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum AuthEventMetrics {
AuthenticationCount,
AuthenticationAttemptCount,
AuthenticationSuccessCount,
ChallengeFlowCount,
FrictionlessFlowCount,
FrictionlessSuccessCount,
ChallengeAttemptCount,
ChallengeSuccessCount,
AuthenticationErrorMessage,
AuthenticationFunnel,
AuthenticationExemptionApprovedCount,
AuthenticationExemptionRequestedCount,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
pub enum AuthEventFlows {
IncomingWebhookReceive,
PaymentsExternalAuthentication,
}
pub mod metric_behaviour {
pub struct AuthenticationCount;
pub struct AuthenticationAttemptCount;
pub struct AuthenticationSuccessCount;
pub struct ChallengeFlowCount;
pub struct FrictionlessFlowCount;
pub struct FrictionlessSuccessCount;
pub struct ChallengeAttemptCount;
pub struct ChallengeSuccessCount;
pub struct AuthenticationErrorMessage;
pub struct AuthenticationFunnel;
}
impl From<AuthEventMetrics> for NameDescription {
fn from(value: AuthEventMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
impl From<AuthEventDimensions> for NameDescription {
fn from(value: AuthEventDimensions) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct AuthEventMetricsBucketIdentifier {
pub authentication_status: Option<AuthenticationStatus>,
pub trans_status: Option<TransactionStatus>,
pub authentication_type: Option<DecoupledAuthenticationType>,
pub error_message: Option<String>,
pub authentication_connector: Option<AuthenticationConnectors>,
pub message_version: Option<String>,
pub acs_reference_number: Option<String>,
pub mcc: Option<String>,
pub currency: Option<Currency>,
pub merchant_country: Option<String>,
pub billing_country: Option<String>,
pub shipping_country: Option<String>,
pub issuer_country: Option<String>,
pub earliest_supported_version: Option<String>,
pub latest_supported_version: Option<String>,
pub whitelist_decision: Option<bool>,
pub device_manufacturer: Option<String>,
pub device_type: Option<String>,
pub device_brand: Option<String>,
pub device_os: Option<String>,
pub device_display: Option<String>,
pub browser_name: Option<String>,
pub browser_version: Option<String>,
pub issuer_id: Option<String>,
pub scheme_name: Option<String>,
pub exemption_requested: Option<bool>,
pub exemption_accepted: Option<bool>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
#[serde(with = "common_utils::custom_serde::iso8601custom")]
pub start_time: time::PrimitiveDateTime,
}
impl AuthEventMetricsBucketIdentifier {
#[allow(clippy::too_many_arguments)]
pub fn new(
authentication_status: Option<AuthenticationStatus>,
trans_status: Option<TransactionStatus>,
authentication_type: Option<DecoupledAuthenticationType>,
error_message: Option<String>,
authentication_connector: Option<AuthenticationConnectors>,
message_version: Option<String>,
acs_reference_number: Option<String>,
mcc: Option<String>,
currency: Option<Currency>,
merchant_country: Option<String>,
billing_country: Option<String>,
shipping_country: Option<String>,
issuer_country: Option<String>,
earliest_supported_version: Option<String>,
latest_supported_version: Option<String>,
whitelist_decision: Option<bool>,
device_manufacturer: Option<String>,
device_type: Option<String>,
device_brand: Option<String>,
device_os: Option<String>,
device_display: Option<String>,
browser_name: Option<String>,
browser_version: Option<String>,
issuer_id: Option<String>,
scheme_name: Option<String>,
exemption_requested: Option<bool>,
exemption_accepted: Option<bool>,
normalized_time_range: TimeRange,
) -> Self {
Self {
authentication_status,
trans_status,
authentication_type,
error_message,
authentication_connector,
message_version,
acs_reference_number,
mcc,
currency,
merchant_country,
billing_country,
shipping_country,
issuer_country,
earliest_supported_version,
latest_supported_version,
whitelist_decision,
device_manufacturer,
device_type,
device_brand,
device_os,
device_display,
browser_name,
browser_version,
issuer_id,
scheme_name,
exemption_requested,
exemption_accepted,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
}
}
impl Hash for AuthEventMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.authentication_status.hash(state);
self.trans_status.hash(state);
self.authentication_type.hash(state);
self.authentication_connector.hash(state);
self.message_version.hash(state);
self.acs_reference_number.hash(state);
self.error_message.hash(state);
self.mcc.hash(state);
self.currency.hash(state);
self.merchant_country.hash(state);
self.billing_country.hash(state);
self.shipping_country.hash(state);
self.issuer_country.hash(state);
self.earliest_supported_version.hash(state);
self.latest_supported_version.hash(state);
self.whitelist_decision.hash(state);
self.device_manufacturer.hash(state);
self.device_type.hash(state);
self.device_brand.hash(state);
self.device_os.hash(state);
self.device_display.hash(state);
self.browser_name.hash(state);
self.browser_version.hash(state);
self.issuer_id.hash(state);
self.scheme_name.hash(state);
self.exemption_requested.hash(state);
self.exemption_accepted.hash(state);
self.time_bucket.hash(state);
}
}
impl PartialEq for AuthEventMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct AuthEventMetricsBucketValue {
pub authentication_count: Option<u64>,
pub authentication_attempt_count: Option<u64>,
pub authentication_success_count: Option<u64>,
pub challenge_flow_count: Option<u64>,
pub challenge_attempt_count: Option<u64>,
pub challenge_success_count: Option<u64>,
pub frictionless_flow_count: Option<u64>,
pub frictionless_success_count: Option<u64>,
pub error_message_count: Option<u64>,
pub authentication_funnel: Option<u64>,
pub authentication_exemption_approved_count: Option<u64>,
pub authentication_exemption_requested_count: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: AuthEventMetricsBucketValue,
#[serde(flatten)]
pub dimensions: AuthEventMetricsBucketIdentifier,
}
</file>
|
{
"crate": "api_models",
"file": "crates/api_models/src/analytics/auth_events.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2254
}
|
large_file_6645482508593124123
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: router_env
File: crates/router_env/src/logger/types.rs
</path>
<file>
//! Types.
use serde::Deserialize;
use strum::{Display, EnumString};
pub use tracing::{
field::{Field, Visit},
Level, Value,
};
/// Category and tag of log event.
///
/// Don't hesitate to add your variant if it is missing here.
#[derive(Debug, Default, Deserialize, Clone, Display, EnumString)]
pub enum Tag {
/// General.
#[default]
General,
/// Redis: get.
RedisGet,
/// Redis: set.
RedisSet,
/// API: incoming web request.
ApiIncomingRequest,
/// API: outgoing web request.
ApiOutgoingRequest,
/// Data base: create.
DbCreate,
/// Data base: read.
DbRead,
/// Data base: updare.
DbUpdate,
/// Data base: delete.
DbDelete,
/// Begin Request
BeginRequest,
/// End Request
EndRequest,
/// Call initiated to connector.
InitiatedToConnector,
/// Event: general.
Event,
/// Compatibility Layer Request
CompatibilityLayerRequest,
}
/// API Flow
#[derive(Debug, Display, Clone, PartialEq, Eq)]
pub enum Flow {
/// Health check
HealthCheck,
/// Deep health Check
DeepHealthCheck,
/// Organization create flow
OrganizationCreate,
/// Organization retrieve flow
OrganizationRetrieve,
/// Organization update flow
OrganizationUpdate,
/// Merchants account create flow.
MerchantsAccountCreate,
/// Merchants account retrieve flow.
MerchantsAccountRetrieve,
/// Merchants account update flow.
MerchantsAccountUpdate,
/// Merchants account delete flow.
MerchantsAccountDelete,
/// Merchant Connectors create flow.
MerchantConnectorsCreate,
/// Merchant Connectors retrieve flow.
MerchantConnectorsRetrieve,
/// Merchant account list
MerchantAccountList,
/// Merchant Connectors update flow.
MerchantConnectorsUpdate,
/// Merchant Connectors delete flow.
MerchantConnectorsDelete,
/// Merchant Connectors list flow.
MerchantConnectorsList,
/// Merchant Transfer Keys
MerchantTransferKey,
/// ConfigKey create flow.
ConfigKeyCreate,
/// ConfigKey fetch flow.
ConfigKeyFetch,
/// Enable platform account flow.
EnablePlatformAccount,
/// ConfigKey Update flow.
ConfigKeyUpdate,
/// ConfigKey Delete flow.
ConfigKeyDelete,
/// Customers create flow.
CustomersCreate,
/// Customers retrieve flow.
CustomersRetrieve,
/// Customers update flow.
CustomersUpdate,
/// Customers delete flow.
CustomersDelete,
/// Customers get mandates flow.
CustomersGetMandates,
/// Create an Ephemeral Key.
EphemeralKeyCreate,
/// Delete an Ephemeral Key.
EphemeralKeyDelete,
/// Mandates retrieve flow.
MandatesRetrieve,
/// Mandates revoke flow.
MandatesRevoke,
/// Mandates list flow.
MandatesList,
/// Payment methods create flow.
PaymentMethodsCreate,
/// Payment methods migrate flow.
PaymentMethodsMigrate,
/// Payment methods batch update flow.
PaymentMethodsBatchUpdate,
/// Payment methods list flow.
PaymentMethodsList,
/// Payment method save flow
PaymentMethodSave,
/// Customer payment methods list flow.
CustomerPaymentMethodsList,
/// Payment methods token data get flow.
GetPaymentMethodTokenData,
/// List Customers for a merchant
CustomersList,
///List Customers for a merchant with constraints.
CustomersListWithConstraints,
/// Retrieve countries and currencies for connector and payment method
ListCountriesCurrencies,
/// Payment method create collect link flow.
PaymentMethodCollectLink,
/// Payment methods retrieve flow.
PaymentMethodsRetrieve,
/// Payment methods update flow.
PaymentMethodsUpdate,
/// Payment methods delete flow.
PaymentMethodsDelete,
/// Network token status check flow.
NetworkTokenStatusCheck,
/// Default Payment method flow.
DefaultPaymentMethodsSet,
/// Payments create flow.
PaymentsCreate,
/// Payments Retrieve flow.
PaymentsRetrieve,
/// Payments Retrieve force sync flow.
PaymentsRetrieveForceSync,
/// Payments Retrieve using merchant reference id
PaymentsRetrieveUsingMerchantReferenceId,
/// Payments update flow.
PaymentsUpdate,
/// Payments confirm flow.
PaymentsConfirm,
/// Payments capture flow.
PaymentsCapture,
/// Payments cancel flow.
PaymentsCancel,
/// Payments cancel post capture flow.
PaymentsCancelPostCapture,
/// Payments approve flow.
PaymentsApprove,
/// Payments reject flow.
PaymentsReject,
/// Payments Session Token flow
PaymentsSessionToken,
/// Payments start flow.
PaymentsStart,
/// Payments list flow.
PaymentsList,
/// Payments filters flow
PaymentsFilters,
/// Payments aggregates flow
PaymentsAggregate,
/// Payments Create Intent flow
PaymentsCreateIntent,
/// Payments Get Intent flow
PaymentsGetIntent,
/// Payments Update Intent flow
PaymentsUpdateIntent,
/// Payments confirm intent flow
PaymentsConfirmIntent,
/// Payments create and confirm intent flow
PaymentsCreateAndConfirmIntent,
/// Payment attempt list flow
PaymentAttemptsList,
#[cfg(feature = "payouts")]
/// Payouts create flow
PayoutsCreate,
#[cfg(feature = "payouts")]
/// Payouts retrieve flow.
PayoutsRetrieve,
#[cfg(feature = "payouts")]
/// Payouts update flow.
PayoutsUpdate,
/// Payouts confirm flow.
PayoutsConfirm,
#[cfg(feature = "payouts")]
/// Payouts cancel flow.
PayoutsCancel,
#[cfg(feature = "payouts")]
/// Payouts fulfill flow.
PayoutsFulfill,
#[cfg(feature = "payouts")]
/// Payouts list flow.
PayoutsList,
#[cfg(feature = "payouts")]
/// Payouts filter flow.
PayoutsFilter,
/// Payouts accounts flow.
PayoutsAccounts,
/// Payout link initiate flow
PayoutLinkInitiate,
/// Payments Redirect flow
PaymentsRedirect,
/// Payemnts Complete Authorize Flow
PaymentsCompleteAuthorize,
/// Refunds create flow.
RefundsCreate,
/// Refunds retrieve flow.
RefundsRetrieve,
/// Refunds retrieve force sync flow.
RefundsRetrieveForceSync,
/// Refunds update flow.
RefundsUpdate,
/// Refunds list flow.
RefundsList,
/// Refunds filters flow
RefundsFilters,
/// Refunds aggregates flow
RefundsAggregate,
// Retrieve forex flow.
RetrieveForexFlow,
/// Toggles recon service for a merchant.
ReconMerchantUpdate,
/// Recon token request flow.
ReconTokenRequest,
/// Initial request for recon service.
ReconServiceRequest,
/// Recon token verification flow
ReconVerifyToken,
/// Routing create flow,
RoutingCreateConfig,
/// Routing link config
RoutingLinkConfig,
/// Routing link config
RoutingUnlinkConfig,
/// Routing retrieve config
RoutingRetrieveConfig,
/// Routing retrieve active config
RoutingRetrieveActiveConfig,
/// Routing retrieve default config
RoutingRetrieveDefaultConfig,
/// Routing retrieve dictionary
RoutingRetrieveDictionary,
/// Rule migration for decision-engine
DecisionEngineRuleMigration,
/// Routing update config
RoutingUpdateConfig,
/// Routing update default config
RoutingUpdateDefaultConfig,
/// Routing delete config
RoutingDeleteConfig,
/// Subscription create flow,
CreateSubscription,
/// Subscription get plans flow,
GetPlansForSubscription,
/// Subscription confirm flow,
ConfirmSubscription,
/// Subscription create and confirm flow,
CreateAndConfirmSubscription,
/// Get Subscription flow
GetSubscription,
/// Update Subscription flow
UpdateSubscription,
/// Get Subscription estimate flow
GetSubscriptionEstimate,
/// Create dynamic routing
CreateDynamicRoutingConfig,
/// Toggle dynamic routing
ToggleDynamicRouting,
/// Update dynamic routing config
UpdateDynamicRoutingConfigs,
/// Add record to blocklist
AddToBlocklist,
/// Delete record from blocklist
DeleteFromBlocklist,
/// List entries from blocklist
ListBlocklist,
/// Toggle blocklist for merchant
ToggleBlocklistGuard,
/// Incoming Webhook Receive
IncomingWebhookReceive,
/// Recovery incoming webhook receive
RecoveryIncomingWebhookReceive,
/// Validate payment method flow
ValidatePaymentMethod,
/// API Key create flow
ApiKeyCreate,
/// API Key retrieve flow
ApiKeyRetrieve,
/// API Key update flow
ApiKeyUpdate,
/// API Key revoke flow
ApiKeyRevoke,
/// API Key list flow
ApiKeyList,
/// Dispute Retrieve flow
DisputesRetrieve,
/// Dispute List flow
DisputesList,
/// Dispute Filters flow
DisputesFilters,
/// Cards Info flow
CardsInfo,
/// Create File flow
CreateFile,
/// Delete File flow
DeleteFile,
/// Retrieve File flow
RetrieveFile,
/// Dispute Evidence submission flow
DisputesEvidenceSubmit,
/// Create Config Key flow
CreateConfigKey,
/// Attach Dispute Evidence flow
AttachDisputeEvidence,
/// Delete Dispute Evidence flow
DeleteDisputeEvidence,
/// Disputes aggregate flow
DisputesAggregate,
/// Retrieve Dispute Evidence flow
RetrieveDisputeEvidence,
/// Invalidate cache flow
CacheInvalidate,
/// Payment Link Retrieve flow
PaymentLinkRetrieve,
/// payment Link Initiate flow
PaymentLinkInitiate,
/// payment Link Initiate flow
PaymentSecureLinkInitiate,
/// Payment Link List flow
PaymentLinkList,
/// Payment Link Status
PaymentLinkStatus,
/// Create a profile
ProfileCreate,
/// Update a profile
ProfileUpdate,
/// Retrieve a profile
ProfileRetrieve,
/// Delete a profile
ProfileDelete,
/// List all the profiles for a merchant
ProfileList,
/// Different verification flows
Verification,
/// Rust locker migration
RustLockerMigration,
/// Gsm Rule Creation flow
GsmRuleCreate,
/// Gsm Rule Retrieve flow
GsmRuleRetrieve,
/// Gsm Rule Update flow
GsmRuleUpdate,
/// Apple pay certificates migration
ApplePayCertificatesMigration,
/// Gsm Rule Delete flow
GsmRuleDelete,
/// Get data from embedded flow
GetDataFromHyperswitchAiFlow,
// List all chat interactions
ListAllChatInteractions,
/// User Sign Up
UserSignUp,
/// User Sign Up
UserSignUpWithMerchantId,
/// User Sign In
UserSignIn,
/// User transfer key
UserTransferKey,
/// User connect account
UserConnectAccount,
/// Upsert Decision Manager Config
DecisionManagerUpsertConfig,
/// Delete Decision Manager Config
DecisionManagerDeleteConfig,
/// Retrieve Decision Manager Config
DecisionManagerRetrieveConfig,
/// Manual payment fulfillment acknowledgement
FrmFulfillment,
/// Get connectors feature matrix
FeatureMatrix,
/// Change password flow
ChangePassword,
/// Signout flow
Signout,
/// Set Dashboard Metadata flow
SetDashboardMetadata,
/// Get Multiple Dashboard Metadata flow
GetMultipleDashboardMetadata,
/// Payment Connector Verify
VerifyPaymentConnector,
/// Internal user signup
InternalUserSignup,
/// Create tenant level user
TenantUserCreate,
/// Switch org
SwitchOrg,
/// Switch merchant v2
SwitchMerchantV2,
/// Switch profile
SwitchProfile,
/// Get permission info
GetAuthorizationInfo,
/// Get Roles info
GetRolesInfo,
/// Get Parent Group Info
GetParentGroupInfo,
/// List roles v2
ListRolesV2,
/// List invitable roles at entity level
ListInvitableRolesAtEntityLevel,
/// List updatable roles at entity level
ListUpdatableRolesAtEntityLevel,
/// Get role
GetRole,
/// Get parent info for role
GetRoleV2,
/// Get role from token
GetRoleFromToken,
/// Get resources and groups for role from token
GetRoleFromTokenV2,
/// Get parent groups info for role from token
GetParentGroupsInfoForRoleFromToken,
/// Update user role
UpdateUserRole,
/// Create merchant account for user in a org
UserMerchantAccountCreate,
/// Create Platform
CreatePlatformAccount,
/// Create Org in a given tenancy
UserOrgMerchantCreate,
/// Generate Sample Data
GenerateSampleData,
/// Delete Sample Data
DeleteSampleData,
/// Get details of a user
GetUserDetails,
/// Get details of a user role in a merchant account
GetUserRoleDetails,
/// PaymentMethodAuth Link token create
PmAuthLinkTokenCreate,
/// PaymentMethodAuth Exchange token create
PmAuthExchangeToken,
/// Get reset password link
ForgotPassword,
/// Reset password using link
ResetPassword,
/// Force set or force change password
RotatePassword,
/// Invite multiple users
InviteMultipleUser,
/// Reinvite user
ReInviteUser,
/// Accept invite from email
AcceptInviteFromEmail,
/// Delete user role
DeleteUserRole,
/// Incremental Authorization flow
PaymentsIncrementalAuthorization,
/// Extend Authorization flow
PaymentsExtendAuthorization,
/// Get action URL for connector onboarding
GetActionUrl,
/// Sync connector onboarding status
SyncOnboardingStatus,
/// Reset tracking id
ResetTrackingId,
/// Verify email Token
VerifyEmail,
/// Send verify email
VerifyEmailRequest,
/// Update user account details
UpdateUserAccountDetails,
/// Accept user invitation using entities
AcceptInvitationsV2,
/// Accept user invitation using entities before user login
AcceptInvitationsPreAuth,
/// Initiate external authentication for a payment
PaymentsExternalAuthentication,
/// Authorize the payment after external 3ds authentication
PaymentsAuthorize,
/// Create Role
CreateRole,
/// Create Role V2
CreateRoleV2,
/// Update Role
UpdateRole,
/// User email flow start
UserFromEmail,
/// Begin TOTP
TotpBegin,
/// Reset TOTP
TotpReset,
/// Verify TOTP
TotpVerify,
/// Update TOTP secret
TotpUpdate,
/// Verify Access Code
RecoveryCodeVerify,
/// Generate or Regenerate recovery codes
RecoveryCodesGenerate,
/// Terminate two factor authentication
TerminateTwoFactorAuth,
/// Check 2FA status
TwoFactorAuthStatus,
/// Create user authentication method
CreateUserAuthenticationMethod,
/// Update user authentication method
UpdateUserAuthenticationMethod,
/// List user authentication methods
ListUserAuthenticationMethods,
/// Get sso auth url
GetSsoAuthUrl,
/// Signin with SSO
SignInWithSso,
/// Auth Select
AuthSelect,
/// List Orgs for user
ListOrgForUser,
/// List Merchants for user in org
ListMerchantsForUserInOrg,
/// List Profile for user in org and merchant
ListProfileForUserInOrgAndMerchant,
/// List Users in Org
ListUsersInLineage,
/// List invitations for user
ListInvitationsForUser,
/// Get theme using lineage
GetThemeUsingLineage,
/// Get theme using theme id
GetThemeUsingThemeId,
/// Upload file to theme storage
UploadFileToThemeStorage,
/// Create theme
CreateTheme,
/// Update theme
UpdateTheme,
/// Delete theme
DeleteTheme,
/// Create user theme
CreateUserTheme,
/// Update user theme
UpdateUserTheme,
/// Delete user theme
DeleteUserTheme,
/// Upload file to user theme storage
UploadFileToUserThemeStorage,
/// Get user theme using theme id
GetUserThemeUsingThemeId,
///List All Themes In Lineage
ListAllThemesInLineage,
/// Get user theme using lineage
GetUserThemeUsingLineage,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
WebhookEventDeliveryAttemptList,
/// Manually retry the delivery for a webhook event
WebhookEventDeliveryRetry,
/// Retrieve status of the Poll
RetrievePollStatus,
/// Toggles the extended card info feature in profile level
ToggleExtendedCardInfo,
/// Toggles the extended card info feature in profile level
ToggleConnectorAgnosticMit,
/// Get the extended card info associated to a payment_id
GetExtendedCardInfo,
/// Manually update the refund details like status, error code, error message etc.
RefundsManualUpdate,
/// Manually update the payment details like status, error code, error message etc.
PaymentsManualUpdate,
/// Dynamic Tax Calcultion
SessionUpdateTaxCalculation,
ProxyConfirmIntent,
/// Payments post session tokens flow
PaymentsPostSessionTokens,
/// Payments Update Metadata
PaymentsUpdateMetadata,
/// Payments start redirection flow
PaymentStartRedirection,
/// Volume split on the routing type
VolumeSplitOnRoutingType,
/// Routing evaluate rule flow
RoutingEvaluateRule,
/// Relay flow
Relay,
/// Relay retrieve flow
RelayRetrieve,
/// Card tokenization flow
TokenizeCard,
/// Card tokenization using payment method flow
TokenizeCardUsingPaymentMethodId,
/// Cards batch tokenization flow
TokenizeCardBatch,
/// Incoming Relay Webhook Receive
IncomingRelayWebhookReceive,
/// Generate Hypersense Token
HypersenseTokenRequest,
/// Verify Hypersense Token
HypersenseVerifyToken,
/// Signout Hypersense Token
HypersenseSignoutToken,
/// Payment Method Session Create
PaymentMethodSessionCreate,
/// Payment Method Session Retrieve
PaymentMethodSessionRetrieve,
// Payment Method Session Update
PaymentMethodSessionUpdate,
/// Update a saved payment method using the payment methods session
PaymentMethodSessionUpdateSavedPaymentMethod,
/// Delete a saved payment method using the payment methods session
PaymentMethodSessionDeleteSavedPaymentMethod,
/// Confirm a payment method session with payment method data
PaymentMethodSessionConfirm,
/// Create Cards Info flow
CardsInfoCreate,
/// Update Cards Info flow
CardsInfoUpdate,
/// Cards Info migrate flow
CardsInfoMigrate,
///Total payment method count for merchant
TotalPaymentMethodCount,
/// Process Tracker Revenue Recovery Workflow Retrieve
RevenueRecoveryRetrieve,
/// Process Tracker Revenue Recovery Workflow Resume
RevenueRecoveryResume,
/// Tokenization flow
TokenizationCreate,
/// Tokenization retrieve flow
TokenizationRetrieve,
/// Clone Connector flow
CloneConnector,
/// Authentication Create flow
AuthenticationCreate,
/// Authentication Eligibility flow
AuthenticationEligibility,
/// Authentication Sync flow
AuthenticationSync,
/// Authentication Sync Post Update flow
AuthenticationSyncPostUpdate,
/// Authentication Authenticate flow
AuthenticationAuthenticate,
///Proxy Flow
Proxy,
/// Profile Acquirer Create flow
ProfileAcquirerCreate,
/// Profile Acquirer Update flow
ProfileAcquirerUpdate,
/// ThreeDs Decision Rule Execute flow
ThreeDsDecisionRuleExecute,
/// Incoming Network Token Webhook Receive
IncomingNetworkTokenWebhookReceive,
/// Decision Engine Decide Gateway Call
DecisionEngineDecideGatewayCall,
/// Decision Engine Gateway Feedback Call
DecisionEngineGatewayFeedbackCall,
/// Recovery payments create flow.
RecoveryPaymentsCreate,
/// Tokenization delete flow
TokenizationDelete,
/// Payment method data backfill flow
RecoveryDataBackfill,
/// Revenue recovery Redis operations flow
RevenueRecoveryRedis,
/// Gift card balance check flow
GiftCardBalanceCheck,
/// Payments Submit Eligibility flow
PaymentsSubmitEligibility,
}
/// Trait for providing generic behaviour to flow metric
pub trait FlowMetric: ToString + std::fmt::Debug + Clone {}
impl FlowMetric for Flow {}
/// Category of log event.
#[derive(Debug)]
pub enum Category {
/// Redis: general.
Redis,
/// API: general.
Api,
/// Database: general.
Store,
/// Event: general.
Event,
/// General: general.
General,
}
</file>
|
{
"crate": "router_env",
"file": "crates/router_env/src/logger/types.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4481
}
|
large_file_4340694606232621867
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: router_env
File: crates/router_env/src/logger/formatter.rs
</path>
<file>
//! Formatting [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router.
use std::{
collections::{HashMap, HashSet},
fmt,
io::Write,
sync::LazyLock,
};
use config::ConfigError;
use serde::ser::{SerializeMap, Serializer};
use serde_json::{ser::Formatter, Value};
// use time::format_description::well_known::Rfc3339;
use time::format_description::well_known::Iso8601;
use tracing::{Event, Metadata, Subscriber};
use tracing_subscriber::{
fmt::MakeWriter,
layer::Context,
registry::{LookupSpan, SpanRef},
Layer,
};
use crate::Storage;
// TODO: Documentation coverage for this crate
// Implicit keys
const MESSAGE: &str = "message";
const HOSTNAME: &str = "hostname";
const PID: &str = "pid";
const ENV: &str = "env";
const VERSION: &str = "version";
const BUILD: &str = "build";
const LEVEL: &str = "level";
const TARGET: &str = "target";
const SERVICE: &str = "service";
const LINE: &str = "line";
const FILE: &str = "file";
const FN: &str = "fn";
const FULL_NAME: &str = "full_name";
const TIME: &str = "time";
// Extra implicit keys. Keys that are provided during runtime but should be treated as
// implicit in the logs
const FLOW: &str = "flow";
const MERCHANT_AUTH: &str = "merchant_authentication";
const MERCHANT_ID: &str = "merchant_id";
const REQUEST_METHOD: &str = "request_method";
const REQUEST_URL_PATH: &str = "request_url_path";
const REQUEST_ID: &str = "request_id";
const WORKFLOW_ID: &str = "workflow_id";
const GLOBAL_ID: &str = "global_id";
const SESSION_ID: &str = "session_id";
/// Set of predefined implicit keys.
pub static IMPLICIT_KEYS: LazyLock<rustc_hash::FxHashSet<&str>> = LazyLock::new(|| {
let mut set = rustc_hash::FxHashSet::default();
set.insert(HOSTNAME);
set.insert(PID);
set.insert(ENV);
set.insert(VERSION);
set.insert(BUILD);
set.insert(LEVEL);
set.insert(TARGET);
set.insert(SERVICE);
set.insert(LINE);
set.insert(FILE);
set.insert(FN);
set.insert(FULL_NAME);
set.insert(TIME);
set
});
/// Extra implicit keys. Keys that are not purely implicit but need to be logged alongside
/// other implicit keys in the log json.
pub static EXTRA_IMPLICIT_KEYS: LazyLock<rustc_hash::FxHashSet<&str>> = LazyLock::new(|| {
let mut set = rustc_hash::FxHashSet::default();
set.insert(MESSAGE);
set.insert(FLOW);
set.insert(MERCHANT_AUTH);
set.insert(MERCHANT_ID);
set.insert(REQUEST_METHOD);
set.insert(REQUEST_URL_PATH);
set.insert(REQUEST_ID);
set.insert(GLOBAL_ID);
set.insert(SESSION_ID);
set.insert(WORKFLOW_ID);
set
});
/// Describe type of record: entering a span, exiting a span, an event.
#[derive(Clone, Debug)]
pub enum RecordType {
/// Entering a span.
EnterSpan,
/// Exiting a span.
ExitSpan,
/// Event.
Event,
}
impl fmt::Display for RecordType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let repr = match self {
Self::EnterSpan => "START",
Self::ExitSpan => "END",
Self::Event => "EVENT",
};
write!(f, "{repr}")
}
}
/// Format log records.
/// `FormattingLayer` relies on the `tracing_bunyan_formatter::JsonStorageLayer` which is storage of entries.
#[derive(Debug)]
pub struct FormattingLayer<W, F>
where
W: for<'a> MakeWriter<'a> + 'static,
F: Formatter + Clone,
{
dst_writer: W,
pid: u32,
hostname: String,
env: String,
service: String,
#[cfg(feature = "vergen")]
version: String,
#[cfg(feature = "vergen")]
build: String,
default_fields: HashMap<String, Value>,
formatter: F,
}
impl<W, F> FormattingLayer<W, F>
where
W: for<'a> MakeWriter<'a> + 'static,
F: Formatter + Clone,
{
/// Constructor of `FormattingLayer`.
///
/// A `name` will be attached to all records during formatting.
/// A `dst_writer` to forward all records.
///
/// ## Example
/// ```rust
/// let formatting_layer = router_env::FormattingLayer::new("my_service", std::io::stdout, serde_json::ser::CompactFormatter);
/// ```
pub fn new(
service: &str,
dst_writer: W,
formatter: F,
) -> error_stack::Result<Self, ConfigError> {
Self::new_with_implicit_entries(service, dst_writer, HashMap::new(), formatter)
}
/// Construct of `FormattingLayer with implicit default entries.
pub fn new_with_implicit_entries(
service: &str,
dst_writer: W,
default_fields: HashMap<String, Value>,
formatter: F,
) -> error_stack::Result<Self, ConfigError> {
let pid = std::process::id();
let hostname = gethostname::gethostname().to_string_lossy().into_owned();
let service = service.to_string();
#[cfg(feature = "vergen")]
let version = crate::version!().to_string();
#[cfg(feature = "vergen")]
let build = crate::build!().to_string();
let env = crate::env::which().to_string();
for key in default_fields.keys() {
if IMPLICIT_KEYS.contains(key.as_str()) {
return Err(ConfigError::Message(format!(
"A reserved key `{key}` was included in `default_fields` in the log formatting layer"
))
.into());
}
}
Ok(Self {
dst_writer,
pid,
hostname,
env,
service,
#[cfg(feature = "vergen")]
version,
#[cfg(feature = "vergen")]
build,
default_fields,
formatter,
})
}
/// Serialize common for both span and event entries.
fn common_serialize<S>(
&self,
map_serializer: &mut impl SerializeMap<Error = serde_json::Error>,
metadata: &Metadata<'_>,
span: Option<&SpanRef<'_, S>>,
storage: &Storage<'_>,
name: &str,
) -> Result<(), std::io::Error>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let is_extra = |s: &str| !IMPLICIT_KEYS.contains(s);
let is_extra_implicit = |s: &str| is_extra(s) && EXTRA_IMPLICIT_KEYS.contains(s);
map_serializer.serialize_entry(HOSTNAME, &self.hostname)?;
map_serializer.serialize_entry(PID, &self.pid)?;
map_serializer.serialize_entry(ENV, &self.env)?;
#[cfg(feature = "vergen")]
map_serializer.serialize_entry(VERSION, &self.version)?;
#[cfg(feature = "vergen")]
map_serializer.serialize_entry(BUILD, &self.build)?;
map_serializer.serialize_entry(LEVEL, &format_args!("{}", metadata.level()))?;
map_serializer.serialize_entry(TARGET, metadata.target())?;
map_serializer.serialize_entry(SERVICE, &self.service)?;
map_serializer.serialize_entry(LINE, &metadata.line())?;
map_serializer.serialize_entry(FILE, &metadata.file())?;
map_serializer.serialize_entry(FN, name)?;
map_serializer
.serialize_entry(FULL_NAME, &format_args!("{}::{}", metadata.target(), name))?;
if let Ok(time) = &time::OffsetDateTime::now_utc().format(&Iso8601::DEFAULT) {
map_serializer.serialize_entry(TIME, time)?;
}
// Write down implicit default entries.
for (key, value) in self.default_fields.iter() {
map_serializer.serialize_entry(key, value)?;
}
#[cfg(feature = "log_custom_entries_to_extra")]
let mut extra = serde_json::Map::default();
let mut explicit_entries_set: HashSet<&str> = HashSet::default();
// Write down explicit event's entries.
for (key, value) in storage.values.iter() {
if is_extra_implicit(key) {
#[cfg(feature = "log_extra_implicit_fields")]
map_serializer.serialize_entry(key, value)?;
explicit_entries_set.insert(key);
} else if is_extra(key) {
#[cfg(feature = "log_custom_entries_to_extra")]
extra.insert(key.to_string(), value.clone());
#[cfg(not(feature = "log_custom_entries_to_extra"))]
map_serializer.serialize_entry(key, value)?;
explicit_entries_set.insert(key);
} else {
tracing::warn!(
?key,
?value,
"Attempting to log a reserved entry. It won't be added to the logs"
);
}
}
// Write down entries from the span, if it exists.
if let Some(span) = &span {
let extensions = span.extensions();
if let Some(visitor) = extensions.get::<Storage<'_>>() {
for (key, value) in &visitor.values {
if is_extra_implicit(key) && !explicit_entries_set.contains(key) {
#[cfg(feature = "log_extra_implicit_fields")]
map_serializer.serialize_entry(key, value)?;
} else if is_extra(key) && !explicit_entries_set.contains(key) {
#[cfg(feature = "log_custom_entries_to_extra")]
extra.insert(key.to_string(), value.clone());
#[cfg(not(feature = "log_custom_entries_to_extra"))]
map_serializer.serialize_entry(key, value)?;
} else {
tracing::warn!(
?key,
?value,
"Attempting to log a reserved entry. It won't be added to the logs"
);
}
}
}
}
#[cfg(feature = "log_custom_entries_to_extra")]
map_serializer.serialize_entry("extra", &extra)?;
Ok(())
}
/// Flush memory buffer into an output stream trailing it with next line.
///
/// Should be done by single `write_all` call to avoid fragmentation of log because of mutlithreading.
fn flush(&self, mut buffer: Vec<u8>) -> Result<(), std::io::Error> {
buffer.write_all(b"\n")?;
self.dst_writer.make_writer().write_all(&buffer)
}
/// Serialize entries of span.
fn span_serialize<S>(
&self,
span: &SpanRef<'_, S>,
ty: RecordType,
) -> Result<Vec<u8>, std::io::Error>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let mut buffer = Vec::new();
let mut serializer =
serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone());
let mut map_serializer = serializer.serialize_map(None)?;
let message = Self::span_message(span, ty);
let mut storage = Storage::default();
storage.record_value("message", message.into());
self.common_serialize(
&mut map_serializer,
span.metadata(),
Some(span),
&storage,
span.name(),
)?;
map_serializer.end()?;
Ok(buffer)
}
/// Serialize event into a buffer of bytes using parent span.
pub fn event_serialize<S>(
&self,
span: Option<&SpanRef<'_, S>>,
event: &Event<'_>,
) -> std::io::Result<Vec<u8>>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let mut buffer = Vec::new();
let mut serializer =
serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone());
let mut map_serializer = serializer.serialize_map(None)?;
let mut storage = Storage::default();
event.record(&mut storage);
let name = span.map_or("?", SpanRef::name);
Self::event_message(span, event, &mut storage);
self.common_serialize(&mut map_serializer, event.metadata(), span, &storage, name)?;
map_serializer.end()?;
Ok(buffer)
}
/// Format message of a span.
///
/// Example: "[FN_WITHOUT_COLON - START]"
fn span_message<S>(span: &SpanRef<'_, S>, ty: RecordType) -> String
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
format!("[{} - {}]", span.metadata().name().to_uppercase(), ty)
}
/// Format message of an event.
///
/// Examples: "[FN_WITHOUT_COLON - EVENT] Message"
fn event_message<S>(span: Option<&SpanRef<'_, S>>, event: &Event<'_>, storage: &mut Storage<'_>)
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
// Get value of kept "message" or "target" if does not exist.
let message = storage
.values
.entry("message")
.or_insert_with(|| event.metadata().target().into());
// Prepend the span name to the message if span exists.
if let (Some(span), Value::String(a)) = (span, message) {
*a = format!("{} {}", Self::span_message(span, RecordType::Event), a,);
}
}
}
#[allow(clippy::expect_used)]
impl<S, W, F> Layer<S> for FormattingLayer<W, F>
where
S: Subscriber + for<'a> LookupSpan<'a>,
W: for<'a> MakeWriter<'a> + 'static,
F: Formatter + Clone + 'static,
{
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
// Event could have no span.
let span = ctx.lookup_current();
let result: std::io::Result<Vec<u8>> = self.event_serialize(span.as_ref(), event);
if let Ok(formatted) = result {
let _ = self.flush(formatted);
}
}
#[cfg(feature = "log_active_span_json")]
fn on_enter(&self, id: &tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(id).expect("No span");
if let Ok(serialized) = self.span_serialize(&span, RecordType::EnterSpan) {
let _ = self.flush(serialized);
}
}
#[cfg(not(feature = "log_active_span_json"))]
fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(&id).expect("No span");
if span.parent().is_none() {
if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) {
let _ = self.flush(serialized);
}
}
}
#[cfg(feature = "log_active_span_json")]
fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(&id).expect("No span");
if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) {
let _ = self.flush(serialized);
}
}
}
</file>
|
{
"crate": "router_env",
"file": "crates/router_env/src/logger/formatter.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3369
}
|
large_file_-2334278377122081905
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: router_env
File: crates/router_env/src/logger/setup.rs
</path>
<file>
//! Setup logging subsystem.
use std::time::Duration;
use ::config::ConfigError;
use serde_json::ser::{CompactFormatter, PrettyFormatter};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::{fmt, prelude::*, util::SubscriberInitExt, EnvFilter, Layer};
use crate::{config, FormattingLayer, StorageSubscription};
/// Contains guards necessary for logging and metrics collection.
#[derive(Debug)]
pub struct TelemetryGuard {
_log_guards: Vec<WorkerGuard>,
}
/// Setup logging sub-system specifying the logging configuration, service (binary) name, and a
/// list of external crates for which a more verbose logging must be enabled. All crates within the
/// current cargo workspace are automatically considered for verbose logging.
#[allow(clippy::print_stdout)] // The logger hasn't been initialized yet
pub fn setup(
config: &config::Log,
service_name: &str,
crates_to_filter: impl AsRef<[&'static str]>,
) -> error_stack::Result<TelemetryGuard, ConfigError> {
let mut guards = Vec::new();
// Setup OpenTelemetry traces and metrics
let traces_layer = if config.telemetry.traces_enabled {
setup_tracing_pipeline(&config.telemetry, service_name)
} else {
None
};
if config.telemetry.metrics_enabled {
setup_metrics_pipeline(&config.telemetry)
};
// Setup file logging
let file_writer = if config.file.enabled {
let mut path = crate::env::workspace_path();
// Using an absolute path for file log path would replace workspace path with absolute path,
// which is the intended behavior for us.
path.push(&config.file.path);
let file_appender = tracing_appender::rolling::hourly(&path, &config.file.file_name);
let (file_writer, guard) = tracing_appender::non_blocking(file_appender);
guards.push(guard);
let file_filter = get_envfilter(
config.file.filtering_directive.as_ref(),
config::Level(tracing::Level::WARN),
config.file.level,
&crates_to_filter,
);
println!("Using file logging filter: {file_filter}");
let layer = FormattingLayer::new(service_name, file_writer, CompactFormatter)?
.with_filter(file_filter);
Some(layer)
} else {
None
};
let subscriber = tracing_subscriber::registry()
.with(traces_layer)
.with(StorageSubscription)
.with(file_writer);
// Setup console logging
if config.console.enabled {
let (console_writer, guard) = tracing_appender::non_blocking(std::io::stdout());
guards.push(guard);
let console_filter = get_envfilter(
config.console.filtering_directive.as_ref(),
config::Level(tracing::Level::WARN),
config.console.level,
&crates_to_filter,
);
println!("Using console logging filter: {console_filter}");
match config.console.log_format {
config::LogFormat::Default => {
let logging_layer = fmt::layer()
.with_timer(fmt::time::time())
.pretty()
.with_writer(console_writer)
.with_filter(console_filter);
subscriber.with(logging_layer).init();
}
config::LogFormat::Json => {
error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None);
subscriber
.with(
FormattingLayer::new(service_name, console_writer, CompactFormatter)?
.with_filter(console_filter),
)
.init();
}
config::LogFormat::PrettyJson => {
error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None);
subscriber
.with(
FormattingLayer::new(service_name, console_writer, PrettyFormatter::new())?
.with_filter(console_filter),
)
.init();
}
}
} else {
subscriber.init();
};
// Returning the TelemetryGuard for logs to be printed and metrics to be collected until it is
// dropped
Ok(TelemetryGuard {
_log_guards: guards,
})
}
fn get_opentelemetry_exporter_config(
config: &config::LogTelemetry,
) -> opentelemetry_otlp::ExportConfig {
let mut exporter_config = opentelemetry_otlp::ExportConfig {
protocol: opentelemetry_otlp::Protocol::Grpc,
endpoint: config.otel_exporter_otlp_endpoint.clone(),
..Default::default()
};
if let Some(timeout) = config.otel_exporter_otlp_timeout {
exporter_config.timeout = Duration::from_millis(timeout);
}
exporter_config
}
#[derive(Debug, Clone)]
enum TraceUrlAssert {
Match(String),
EndsWith(String),
}
impl TraceUrlAssert {
fn compare_url(&self, url: &str) -> bool {
match self {
Self::Match(value) => url == value,
Self::EndsWith(end) => url.ends_with(end),
}
}
}
impl From<String> for TraceUrlAssert {
fn from(value: String) -> Self {
match value {
url if url.starts_with('*') => Self::EndsWith(url.trim_start_matches('*').to_string()),
url => Self::Match(url),
}
}
}
#[derive(Debug, Clone)]
struct TraceAssertion {
clauses: Option<Vec<TraceUrlAssert>>,
/// default behaviour for tracing if no condition is provided
default: bool,
}
impl TraceAssertion {
/// Should the provided url be traced
fn should_trace_url(&self, url: &str) -> bool {
match &self.clauses {
Some(clauses) => clauses.iter().all(|cur| cur.compare_url(url)),
None => self.default,
}
}
}
/// Conditional Sampler for providing control on url based tracing
#[derive(Clone, Debug)]
struct ConditionalSampler<T: opentelemetry_sdk::trace::ShouldSample + Clone + 'static>(
TraceAssertion,
T,
);
impl<T: opentelemetry_sdk::trace::ShouldSample + Clone + 'static>
opentelemetry_sdk::trace::ShouldSample for ConditionalSampler<T>
{
fn should_sample(
&self,
parent_context: Option<&opentelemetry::Context>,
trace_id: opentelemetry::trace::TraceId,
name: &str,
span_kind: &opentelemetry::trace::SpanKind,
attributes: &[opentelemetry::KeyValue],
links: &[opentelemetry::trace::Link],
) -> opentelemetry::trace::SamplingResult {
use opentelemetry::trace::TraceContextExt;
match attributes
.iter()
.find(|&kv| kv.key == opentelemetry::Key::new("http.route"))
.map_or(self.0.default, |inner| {
self.0.should_trace_url(&inner.value.as_str())
}) {
true => {
self.1
.should_sample(parent_context, trace_id, name, span_kind, attributes, links)
}
false => opentelemetry::trace::SamplingResult {
decision: opentelemetry::trace::SamplingDecision::Drop,
attributes: Vec::new(),
trace_state: match parent_context {
Some(ctx) => ctx.span().span_context().trace_state().clone(),
None => opentelemetry::trace::TraceState::default(),
},
},
}
}
}
fn setup_tracing_pipeline(
config: &config::LogTelemetry,
service_name: &str,
) -> Option<
tracing_opentelemetry::OpenTelemetryLayer<
tracing_subscriber::Registry,
opentelemetry_sdk::trace::Tracer,
>,
> {
use opentelemetry::trace::TracerProvider;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_sdk::trace;
opentelemetry::global::set_text_map_propagator(
opentelemetry_sdk::propagation::TraceContextPropagator::new(),
);
// Set the export interval to 1 second
let batch_config = trace::BatchConfigBuilder::default()
.with_scheduled_delay(Duration::from_millis(1000))
.build();
let exporter_result = opentelemetry_otlp::SpanExporter::builder()
.with_tonic()
.with_export_config(get_opentelemetry_exporter_config(config))
.build();
let exporter = if config.ignore_errors {
#[allow(clippy::print_stderr)] // The logger hasn't been initialized yet
exporter_result
.inspect_err(|error| eprintln!("Failed to build traces exporter: {error:?}"))
.ok()?
} else {
// Safety: This is conditional, there is an option to avoid this behavior at runtime.
#[allow(clippy::expect_used)]
exporter_result.expect("Failed to build traces exporter")
};
let mut provider_builder = trace::TracerProvider::builder()
.with_span_processor(
trace::BatchSpanProcessor::builder(
exporter,
// The runtime would have to be updated if a different web framework is used
opentelemetry_sdk::runtime::TokioCurrentThread,
)
.with_batch_config(batch_config)
.build(),
)
.with_sampler(trace::Sampler::ParentBased(Box::new(ConditionalSampler(
TraceAssertion {
clauses: config
.route_to_trace
.clone()
.map(|inner| inner.into_iter().map(TraceUrlAssert::from).collect()),
default: false,
},
trace::Sampler::TraceIdRatioBased(config.sampling_rate.unwrap_or(1.0)),
))))
.with_resource(opentelemetry_sdk::Resource::new(vec![
opentelemetry::KeyValue::new("service.name", service_name.to_owned()),
]));
if config.use_xray_generator {
provider_builder = provider_builder
.with_id_generator(opentelemetry_aws::trace::XrayIdGenerator::default());
}
Some(
tracing_opentelemetry::layer()
.with_tracer(provider_builder.build().tracer(service_name.to_owned())),
)
}
fn setup_metrics_pipeline(config: &config::LogTelemetry) {
use opentelemetry_otlp::WithExportConfig;
let exporter_result = opentelemetry_otlp::MetricExporter::builder()
.with_tonic()
.with_temporality(opentelemetry_sdk::metrics::Temporality::Cumulative)
.with_export_config(get_opentelemetry_exporter_config(config))
.build();
let exporter = if config.ignore_errors {
#[allow(clippy::print_stderr)] // The logger hasn't been initialized yet
exporter_result
.inspect_err(|error| eprintln!("Failed to build metrics exporter: {error:?}"))
.ok();
return;
} else {
// Safety: This is conditional, there is an option to avoid this behavior at runtime.
#[allow(clippy::expect_used)]
exporter_result.expect("Failed to build metrics exporter")
};
let reader = opentelemetry_sdk::metrics::PeriodicReader::builder(
exporter,
// The runtime would have to be updated if a different web framework is used
opentelemetry_sdk::runtime::TokioCurrentThread,
)
.with_interval(Duration::from_secs(3))
.with_timeout(Duration::from_secs(10))
.build();
let provider = opentelemetry_sdk::metrics::SdkMeterProvider::builder()
.with_reader(reader)
.with_resource(opentelemetry_sdk::Resource::new([
opentelemetry::KeyValue::new(
"pod",
std::env::var("POD_NAME").unwrap_or(String::from("hyperswitch-server-default")),
),
]))
.build();
opentelemetry::global::set_meter_provider(provider);
}
fn get_envfilter(
filtering_directive: Option<&String>,
default_log_level: config::Level,
filter_log_level: config::Level,
crates_to_filter: impl AsRef<[&'static str]>,
) -> EnvFilter {
filtering_directive
.map(|filter| {
// Try to create target filter from specified filtering directive, if set
// Safety: If user is overriding the default filtering directive, then we need to panic
// for invalid directives.
#[allow(clippy::expect_used)]
EnvFilter::builder()
.with_default_directive(default_log_level.into_level().into())
.parse(filter)
.expect("Invalid EnvFilter filtering directive")
})
.unwrap_or_else(|| {
// Construct a default target filter otherwise
let mut workspace_members = crate::cargo_workspace_members!();
workspace_members.extend(crates_to_filter.as_ref());
workspace_members
.drain()
.zip(std::iter::repeat(filter_log_level.into_level()))
.fold(
EnvFilter::default().add_directive(default_log_level.into_level().into()),
|env_filter, (target, level)| {
// Safety: This is a hardcoded basic filtering directive. If even the basic
// filter is wrong, it's better to panic.
#[allow(clippy::expect_used)]
env_filter.add_directive(
format!("{target}={level}")
.parse()
.expect("Invalid EnvFilter directive format"),
)
},
)
})
}
</file>
|
{
"crate": "router_env",
"file": "crates/router_env/src/logger/setup.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2837
}
|
large_file_-8006309315447122477
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: redis_interface
File: crates/redis_interface/src/types.rs
</path>
<file>
//! Data types and type conversions
//! from `fred`'s internal data-types to custom data-types
use common_utils::errors::CustomResult;
use fred::types::RedisValue as FredRedisValue;
use crate::{errors, RedisConnectionPool};
pub struct RedisValue {
inner: FredRedisValue,
}
impl std::ops::Deref for RedisValue {
type Target = FredRedisValue;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl RedisValue {
pub fn new(value: FredRedisValue) -> Self {
Self { inner: value }
}
pub fn into_inner(self) -> FredRedisValue {
self.inner
}
pub fn from_bytes(val: Vec<u8>) -> Self {
Self {
inner: FredRedisValue::Bytes(val.into()),
}
}
pub fn from_string(value: String) -> Self {
Self {
inner: FredRedisValue::String(value.into()),
}
}
}
impl From<RedisValue> for FredRedisValue {
fn from(v: RedisValue) -> Self {
v.inner
}
}
#[derive(Debug, serde::Deserialize, Clone)]
#[serde(default)]
pub struct RedisSettings {
pub host: String,
pub port: u16,
pub cluster_enabled: bool,
pub cluster_urls: Vec<String>,
pub use_legacy_version: bool,
pub pool_size: usize,
pub reconnect_max_attempts: u32,
/// Reconnect delay in milliseconds
pub reconnect_delay: u32,
/// TTL in seconds
pub default_ttl: u32,
/// TTL for hash-tables in seconds
pub default_hash_ttl: u32,
pub stream_read_count: u64,
pub auto_pipeline: bool,
pub disable_auto_backpressure: bool,
pub max_in_flight_commands: u64,
pub default_command_timeout: u64,
pub max_feed_count: u64,
pub unresponsive_timeout: u64,
}
impl RedisSettings {
/// Validates the Redis configuration provided.
pub fn validate(&self) -> CustomResult<(), errors::RedisError> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
when(self.host.is_default_or_empty(), || {
Err(errors::RedisError::InvalidConfiguration(
"Redis `host` must be specified".into(),
))
})?;
when(self.cluster_enabled && self.cluster_urls.is_empty(), || {
Err(errors::RedisError::InvalidConfiguration(
"Redis `cluster_urls` must be specified if `cluster_enabled` is `true`".into(),
))
})?;
when(
self.default_command_timeout < self.unresponsive_timeout,
|| {
Err(errors::RedisError::InvalidConfiguration(
"Unresponsive timeout cannot be greater than the command timeout".into(),
)
.into())
},
)
}
}
impl Default for RedisSettings {
fn default() -> Self {
Self {
host: "127.0.0.1".to_string(),
port: 6379,
cluster_enabled: false,
cluster_urls: vec![],
use_legacy_version: false,
pool_size: 5,
reconnect_max_attempts: 5,
reconnect_delay: 5,
default_ttl: 300,
stream_read_count: 1,
default_hash_ttl: 900,
auto_pipeline: true,
disable_auto_backpressure: false,
max_in_flight_commands: 5000,
default_command_timeout: 30,
max_feed_count: 200,
unresponsive_timeout: 10,
}
}
}
#[derive(Debug)]
pub enum RedisEntryId {
UserSpecifiedID {
milliseconds: String,
sequence_number: String,
},
AutoGeneratedID,
AfterLastID,
/// Applicable only with consumer groups
UndeliveredEntryID,
}
impl From<RedisEntryId> for fred::types::XID {
fn from(id: RedisEntryId) -> Self {
match id {
RedisEntryId::UserSpecifiedID {
milliseconds,
sequence_number,
} => Self::Manual(fred::bytes_utils::format_bytes!(
"{milliseconds}-{sequence_number}"
)),
RedisEntryId::AutoGeneratedID => Self::Auto,
RedisEntryId::AfterLastID => Self::Max,
RedisEntryId::UndeliveredEntryID => Self::NewInGroup,
}
}
}
impl From<&RedisEntryId> for fred::types::XID {
fn from(id: &RedisEntryId) -> Self {
match id {
RedisEntryId::UserSpecifiedID {
milliseconds,
sequence_number,
} => Self::Manual(fred::bytes_utils::format_bytes!(
"{milliseconds}-{sequence_number}"
)),
RedisEntryId::AutoGeneratedID => Self::Auto,
RedisEntryId::AfterLastID => Self::Max,
RedisEntryId::UndeliveredEntryID => Self::NewInGroup,
}
}
}
#[derive(Eq, PartialEq)]
pub enum SetnxReply {
KeySet,
KeyNotSet, // Existing key
}
impl fred::types::FromRedis for SetnxReply {
fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {
match value {
// Returns String ( "OK" ) in case of success
fred::types::RedisValue::String(_) => Ok(Self::KeySet),
// Return Null in case of failure
fred::types::RedisValue::Null => Ok(Self::KeyNotSet),
// Unexpected behaviour
_ => Err(fred::error::RedisError::new(
fred::error::RedisErrorKind::Unknown,
"Unexpected SETNX command reply",
)),
}
}
}
#[derive(Eq, PartialEq)]
pub enum HsetnxReply {
KeySet,
KeyNotSet, // Existing key
}
impl fred::types::FromRedis for HsetnxReply {
fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {
match value {
fred::types::RedisValue::Integer(1) => Ok(Self::KeySet),
fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet),
_ => Err(fred::error::RedisError::new(
fred::error::RedisErrorKind::Unknown,
"Unexpected HSETNX command reply",
)),
}
}
}
#[derive(Eq, PartialEq)]
pub enum MsetnxReply {
KeysSet,
KeysNotSet, // At least one existing key
}
impl fred::types::FromRedis for MsetnxReply {
fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {
match value {
fred::types::RedisValue::Integer(1) => Ok(Self::KeysSet),
fred::types::RedisValue::Integer(0) => Ok(Self::KeysNotSet),
_ => Err(fred::error::RedisError::new(
fred::error::RedisErrorKind::Unknown,
"Unexpected MSETNX command reply",
)),
}
}
}
#[derive(Debug)]
pub enum StreamCapKind {
MinID,
MaxLen,
}
impl From<StreamCapKind> for fred::types::XCapKind {
fn from(item: StreamCapKind) -> Self {
match item {
StreamCapKind::MaxLen => Self::MaxLen,
StreamCapKind::MinID => Self::MinID,
}
}
}
#[derive(Debug)]
pub enum StreamCapTrim {
Exact,
AlmostExact,
}
impl From<StreamCapTrim> for fred::types::XCapTrim {
fn from(item: StreamCapTrim) -> Self {
match item {
StreamCapTrim::Exact => Self::Exact,
StreamCapTrim::AlmostExact => Self::AlmostExact,
}
}
}
#[derive(Debug)]
pub enum DelReply {
KeyDeleted,
KeyNotDeleted, // Key not found
}
impl DelReply {
pub fn is_key_deleted(&self) -> bool {
matches!(self, Self::KeyDeleted)
}
pub fn is_key_not_deleted(&self) -> bool {
matches!(self, Self::KeyNotDeleted)
}
}
impl fred::types::FromRedis for DelReply {
fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {
match value {
fred::types::RedisValue::Integer(1) => Ok(Self::KeyDeleted),
fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotDeleted),
_ => Err(fred::error::RedisError::new(
fred::error::RedisErrorKind::Unknown,
"Unexpected del command reply",
)),
}
}
}
#[derive(Debug)]
pub enum SaddReply {
KeySet,
KeyNotSet,
}
impl fred::types::FromRedis for SaddReply {
fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> {
match value {
fred::types::RedisValue::Integer(1) => Ok(Self::KeySet),
fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet),
_ => Err(fred::error::RedisError::new(
fred::error::RedisErrorKind::Unknown,
"Unexpected sadd command reply",
)),
}
}
}
#[derive(Debug)]
pub enum SetGetReply<T> {
ValueSet(T), // Value was set and this is the value that was set
ValueExists(T), // Value already existed and this is the existing value
}
impl<T> SetGetReply<T> {
pub fn get_value(&self) -> &T {
match self {
Self::ValueSet(value) => value,
Self::ValueExists(value) => value,
}
}
}
#[derive(Debug)]
pub struct RedisKey(String);
impl RedisKey {
pub fn tenant_aware_key(&self, pool: &RedisConnectionPool) -> String {
pool.add_prefix(&self.0)
}
pub fn tenant_unaware_key(&self, _pool: &RedisConnectionPool) -> String {
self.0.clone()
}
}
impl<T: AsRef<str>> From<T> for RedisKey {
fn from(value: T) -> Self {
let value = value.as_ref();
Self(value.to_string())
}
}
</file>
|
{
"crate": "redis_interface",
"file": "crates/redis_interface/src/types.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2273
}
|
large_file_81702331631476155
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: redis_interface
File: crates/redis_interface/src/commands.rs
</path>
<file>
//! An interface to abstract the `fred` commands
//!
//! The folder provides generic functions for providing serialization
//! and deserialization while calling redis.
//! It also includes instruments to provide tracing.
use std::fmt::Debug;
use common_utils::{
errors::CustomResult,
ext_traits::{AsyncExt, ByteSliceExt, Encode, StringExt},
fp_utils,
};
use error_stack::{report, ResultExt};
use fred::{
interfaces::{HashesInterface, KeysInterface, ListInterface, SetsInterface, StreamsInterface},
prelude::{LuaInterface, RedisErrorKind},
types::{
Expiration, FromRedis, MultipleIDs, MultipleKeys, MultipleOrderedPairs, MultipleStrings,
MultipleValues, RedisMap, RedisValue, ScanType, Scanner, SetOptions, XCap, XReadResponse,
},
};
use futures::StreamExt;
use tracing::instrument;
use crate::{
errors,
types::{
DelReply, HsetnxReply, MsetnxReply, RedisEntryId, RedisKey, SaddReply, SetGetReply,
SetnxReply,
},
};
impl super::RedisConnectionPool {
pub fn add_prefix(&self, key: &str) -> String {
if self.key_prefix.is_empty() {
key.to_string()
} else {
format!("{}:{}", self.key_prefix, key)
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_key<V>(&self, key: &RedisKey, value: V) -> CustomResult<(), errors::RedisError>
where
V: TryInto<RedisValue> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.set(
key.tenant_aware_key(self),
value,
Some(Expiration::EX(self.config.default_ttl.into())),
None,
false,
)
.await
.change_context(errors::RedisError::SetFailed)
}
pub async fn set_key_without_modifying_ttl<V>(
&self,
key: &RedisKey,
value: V,
) -> CustomResult<(), errors::RedisError>
where
V: TryInto<RedisValue> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.set(
key.tenant_aware_key(self),
value,
Some(Expiration::KEEPTTL),
None,
false,
)
.await
.change_context(errors::RedisError::SetFailed)
}
pub async fn set_multiple_keys_if_not_exist<V>(
&self,
value: V,
) -> CustomResult<MsetnxReply, errors::RedisError>
where
V: TryInto<RedisMap> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.msetnx(value)
.await
.change_context(errors::RedisError::SetFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_key_if_not_exist<V>(
&self,
key: &RedisKey,
value: V,
ttl: Option<i64>,
) -> CustomResult<SetnxReply, errors::RedisError>
where
V: serde::Serialize + Debug,
{
let serialized = value
.encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.set_key_if_not_exists_with_expiry(key, serialized.as_slice(), ttl)
.await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_key<V>(
&self,
key: &RedisKey,
value: V,
) -> CustomResult<(), errors::RedisError>
where
V: serde::Serialize + Debug,
{
let serialized = value
.encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.set_key(key, serialized.as_slice()).await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_key_without_modifying_ttl<V>(
&self,
key: &RedisKey,
value: V,
) -> CustomResult<(), errors::RedisError>
where
V: serde::Serialize + Debug,
{
let serialized = value
.encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.set_key_without_modifying_ttl(key, serialized.as_slice())
.await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_key_with_expiry<V>(
&self,
key: &RedisKey,
value: V,
seconds: i64,
) -> CustomResult<(), errors::RedisError>
where
V: serde::Serialize + Debug,
{
let serialized = value
.encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.pool
.set(
key.tenant_aware_key(self),
serialized.as_slice(),
Some(Expiration::EX(seconds)),
None,
false,
)
.await
.change_context(errors::RedisError::SetExFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_key<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
match self
.pool
.get(key.tenant_aware_key(self))
.await
.change_context(errors::RedisError::GetFailed)
{
Ok(v) => Ok(v),
Err(_err) => {
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
#[cfg(feature = "multitenancy_fallback")]
{
self.pool
.get(key.tenant_unaware_key(self))
.await
.change_context(errors::RedisError::GetFailed)
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
async fn get_multiple_keys_with_mget<V>(
&self,
keys: &[RedisKey],
) -> CustomResult<Vec<Option<V>>, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
if keys.is_empty() {
return Ok(Vec::new());
}
let tenant_aware_keys: Vec<String> =
keys.iter().map(|key| key.tenant_aware_key(self)).collect();
self.pool
.mget(tenant_aware_keys)
.await
.change_context(errors::RedisError::GetFailed)
}
#[instrument(level = "DEBUG", skip(self))]
async fn get_multiple_keys_with_parallel_get<V>(
&self,
keys: &[RedisKey],
) -> CustomResult<Vec<Option<V>>, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
if keys.is_empty() {
return Ok(Vec::new());
}
let tenant_aware_keys: Vec<String> =
keys.iter().map(|key| key.tenant_aware_key(self)).collect();
let futures = tenant_aware_keys
.iter()
.map(|redis_key| self.pool.get::<Option<V>, _>(redis_key));
let results = futures::future::try_join_all(futures)
.await
.change_context(errors::RedisError::GetFailed)
.attach_printable("Failed to get keys in cluster mode")?;
Ok(results)
}
/// Helper method to encapsulate the logic for choosing between cluster and non-cluster modes
#[instrument(level = "DEBUG", skip(self))]
async fn get_keys_by_mode<V>(
&self,
keys: &[RedisKey],
) -> CustomResult<Vec<Option<V>>, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
if self.config.cluster_enabled {
// Use individual GET commands for cluster mode to avoid CROSSSLOT errors
self.get_multiple_keys_with_parallel_get(keys).await
} else {
// Use MGET for non-cluster mode for better performance
self.get_multiple_keys_with_mget(keys).await
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_multiple_keys<V>(
&self,
keys: &[RedisKey],
) -> CustomResult<Vec<Option<V>>, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
if keys.is_empty() {
return Ok(Vec::new());
}
match self.get_keys_by_mode(keys).await {
Ok(values) => Ok(values),
Err(_err) => {
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
#[cfg(feature = "multitenancy_fallback")]
{
let tenant_unaware_keys: Vec<RedisKey> = keys
.iter()
.map(|key| key.tenant_unaware_key(self).into())
.collect();
self.get_keys_by_mode(&tenant_unaware_keys).await
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn exists<V>(&self, key: &RedisKey) -> CustomResult<bool, errors::RedisError>
where
V: Into<MultipleKeys> + Unpin + Send + 'static,
{
match self
.pool
.exists(key.tenant_aware_key(self))
.await
.change_context(errors::RedisError::GetFailed)
{
Ok(v) => Ok(v),
Err(_err) => {
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
#[cfg(feature = "multitenancy_fallback")]
{
self.pool
.exists(key.tenant_unaware_key(self))
.await
.change_context(errors::RedisError::GetFailed)
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_and_deserialize_key<T>(
&self,
key: &RedisKey,
type_name: &'static str,
) -> CustomResult<T, errors::RedisError>
where
T: serde::de::DeserializeOwned,
{
let value_bytes = self.get_key::<Vec<u8>>(key).await?;
fp_utils::when(value_bytes.is_empty(), || Err(errors::RedisError::NotFound))?;
value_bytes
.parse_struct(type_name)
.change_context(errors::RedisError::JsonDeserializationFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_and_deserialize_multiple_keys<T>(
&self,
keys: &[RedisKey],
type_name: &'static str,
) -> CustomResult<Vec<Option<T>>, errors::RedisError>
where
T: serde::de::DeserializeOwned,
{
let value_bytes_vec = self.get_multiple_keys::<Vec<u8>>(keys).await?;
let mut results = Vec::with_capacity(value_bytes_vec.len());
for value_bytes_opt in value_bytes_vec {
match value_bytes_opt {
Some(value_bytes) => {
if value_bytes.is_empty() {
results.push(None);
} else {
let parsed = value_bytes
.parse_struct(type_name)
.change_context(errors::RedisError::JsonDeserializationFailed)?;
results.push(Some(parsed));
}
}
None => results.push(None),
}
}
Ok(results)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn delete_key(&self, key: &RedisKey) -> CustomResult<DelReply, errors::RedisError> {
match self
.pool
.del(key.tenant_aware_key(self))
.await
.change_context(errors::RedisError::DeleteFailed)
{
Ok(v) => Ok(v),
Err(_err) => {
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
#[cfg(feature = "multitenancy_fallback")]
{
self.pool
.del(key.tenant_unaware_key(self))
.await
.change_context(errors::RedisError::DeleteFailed)
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn delete_multiple_keys(
&self,
keys: &[RedisKey],
) -> CustomResult<Vec<DelReply>, errors::RedisError> {
let futures = keys.iter().map(|key| self.delete_key(key));
let del_result = futures::future::try_join_all(futures)
.await
.change_context(errors::RedisError::DeleteFailed)?;
Ok(del_result)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_key_with_expiry<V>(
&self,
key: &RedisKey,
value: V,
seconds: i64,
) -> CustomResult<(), errors::RedisError>
where
V: TryInto<RedisValue> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.set(
key.tenant_aware_key(self),
value,
Some(Expiration::EX(seconds)),
None,
false,
)
.await
.change_context(errors::RedisError::SetExFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_key_if_not_exists_with_expiry<V>(
&self,
key: &RedisKey,
value: V,
seconds: Option<i64>,
) -> CustomResult<SetnxReply, errors::RedisError>
where
V: TryInto<RedisValue> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.set(
key.tenant_aware_key(self),
value,
Some(Expiration::EX(
seconds.unwrap_or(self.config.default_ttl.into()),
)),
Some(SetOptions::NX),
false,
)
.await
.change_context(errors::RedisError::SetFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_expiry(
&self,
key: &RedisKey,
seconds: i64,
) -> CustomResult<(), errors::RedisError> {
self.pool
.expire(key.tenant_aware_key(self), seconds)
.await
.change_context(errors::RedisError::SetExpiryFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_expire_at(
&self,
key: &RedisKey,
timestamp: i64,
) -> CustomResult<(), errors::RedisError> {
self.pool
.expire_at(key.tenant_aware_key(self), timestamp)
.await
.change_context(errors::RedisError::SetExpiryFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_ttl(&self, key: &RedisKey) -> CustomResult<i64, errors::RedisError> {
self.pool
.ttl(key.tenant_aware_key(self))
.await
.change_context(errors::RedisError::GetFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_hash_fields<V>(
&self,
key: &RedisKey,
values: V,
ttl: Option<i64>,
) -> CustomResult<(), errors::RedisError>
where
V: TryInto<RedisMap> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
let output: Result<(), _> = self
.pool
.hset(key.tenant_aware_key(self), values)
.await
.change_context(errors::RedisError::SetHashFailed);
// setting expiry for the key
output
.async_and_then(|_| {
self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl.into()))
})
.await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_hash_field_if_not_exist<V>(
&self,
key: &RedisKey,
field: &str,
value: V,
ttl: Option<u32>,
) -> CustomResult<HsetnxReply, errors::RedisError>
where
V: TryInto<RedisValue> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
let output: Result<HsetnxReply, _> = self
.pool
.hsetnx(key.tenant_aware_key(self), field, value)
.await
.change_context(errors::RedisError::SetHashFieldFailed);
output
.async_and_then(|inner| async {
self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl).into())
.await?;
Ok(inner)
})
.await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_hash_field_if_not_exist<V>(
&self,
key: &RedisKey,
field: &str,
value: V,
ttl: Option<u32>,
) -> CustomResult<HsetnxReply, errors::RedisError>
where
V: serde::Serialize + Debug,
{
let serialized = value
.encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.set_hash_field_if_not_exist(key, field, serialized.as_slice(), ttl)
.await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_multiple_hash_field_if_not_exist<V>(
&self,
kv: &[(&RedisKey, V)],
field: &str,
ttl: Option<u32>,
) -> CustomResult<Vec<HsetnxReply>, errors::RedisError>
where
V: serde::Serialize + Debug,
{
let mut hsetnx: Vec<HsetnxReply> = Vec::with_capacity(kv.len());
for (key, val) in kv {
hsetnx.push(
self.serialize_and_set_hash_field_if_not_exist(key, field, val, ttl)
.await?,
);
}
Ok(hsetnx)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn increment_fields_in_hash<T>(
&self,
key: &RedisKey,
fields_to_increment: &[(T, i64)],
) -> CustomResult<Vec<usize>, errors::RedisError>
where
T: Debug + ToString,
{
let mut values_after_increment = Vec::with_capacity(fields_to_increment.len());
for (field, increment) in fields_to_increment.iter() {
values_after_increment.push(
self.pool
.hincrby(key.tenant_aware_key(self), field.to_string(), *increment)
.await
.change_context(errors::RedisError::IncrementHashFieldFailed)?,
)
}
Ok(values_after_increment)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn hscan(
&self,
key: &RedisKey,
pattern: &str,
count: Option<u32>,
) -> CustomResult<Vec<String>, errors::RedisError> {
Ok(self
.pool
.next()
.hscan::<&str, &str>(&key.tenant_aware_key(self), pattern, count)
.filter_map(|value| async move {
match value {
Ok(mut v) => {
let v = v.take_results()?;
let v: Vec<String> =
v.iter().filter_map(|(_, val)| val.as_string()).collect();
Some(futures::stream::iter(v))
}
Err(err) => {
tracing::error!(redis_err=?err, "Redis error while executing hscan command");
None
}
}
})
.flatten()
.collect::<Vec<_>>()
.await)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn scan(
&self,
pattern: &RedisKey,
count: Option<u32>,
scan_type: Option<ScanType>,
) -> CustomResult<Vec<String>, errors::RedisError> {
Ok(self
.pool
.next()
.scan(pattern.tenant_aware_key(self), count, scan_type)
.filter_map(|value| async move {
match value {
Ok(mut v) => {
let v = v.take_results()?;
let v: Vec<String> =
v.into_iter().filter_map(|val| val.into_string()).collect();
Some(futures::stream::iter(v))
}
Err(err) => {
tracing::error!(redis_err=?err, "Redis error while executing scan command");
None
}
}
})
.flatten()
.collect::<Vec<_>>()
.await)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn hscan_and_deserialize<T>(
&self,
key: &RedisKey,
pattern: &str,
count: Option<u32>,
) -> CustomResult<Vec<T>, errors::RedisError>
where
T: serde::de::DeserializeOwned,
{
let redis_results = self.hscan(key, pattern, count).await?;
Ok(redis_results
.iter()
.filter_map(|v| {
let r: T = v.parse_struct(std::any::type_name::<T>()).ok()?;
Some(r)
})
.collect())
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_hash_field<V>(
&self,
key: &RedisKey,
field: &str,
) -> CustomResult<V, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
match self
.pool
.hget(key.tenant_aware_key(self), field)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
{
Ok(v) => Ok(v),
Err(_err) => {
#[cfg(feature = "multitenancy_fallback")]
{
self.pool
.hget(key.tenant_unaware_key(self), field)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
}
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_hash_fields<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
match self
.pool
.hgetall(key.tenant_aware_key(self))
.await
.change_context(errors::RedisError::GetHashFieldFailed)
{
Ok(v) => Ok(v),
Err(_err) => {
#[cfg(feature = "multitenancy_fallback")]
{
self.pool
.hgetall(key.tenant_unaware_key(self))
.await
.change_context(errors::RedisError::GetHashFieldFailed)
}
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_hash_field_and_deserialize<V>(
&self,
key: &RedisKey,
field: &str,
type_name: &'static str,
) -> CustomResult<V, errors::RedisError>
where
V: serde::de::DeserializeOwned,
{
let value_bytes = self.get_hash_field::<Vec<u8>>(key, field).await?;
if value_bytes.is_empty() {
return Err(errors::RedisError::NotFound.into());
}
value_bytes
.parse_struct(type_name)
.change_context(errors::RedisError::JsonDeserializationFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn sadd<V>(
&self,
key: &RedisKey,
members: V,
) -> CustomResult<SaddReply, errors::RedisError>
where
V: TryInto<MultipleValues> + Debug + Send,
V::Error: Into<fred::error::RedisError> + Send,
{
self.pool
.sadd(key.tenant_aware_key(self), members)
.await
.change_context(errors::RedisError::SetAddMembersFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_append_entry<F>(
&self,
stream: &RedisKey,
entry_id: &RedisEntryId,
fields: F,
) -> CustomResult<(), errors::RedisError>
where
F: TryInto<MultipleOrderedPairs> + Debug + Send + Sync,
F::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.xadd(stream.tenant_aware_key(self), false, None, entry_id, fields)
.await
.change_context(errors::RedisError::StreamAppendFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_delete_entries<Ids>(
&self,
stream: &RedisKey,
ids: Ids,
) -> CustomResult<usize, errors::RedisError>
where
Ids: Into<MultipleStrings> + Debug + Send + Sync,
{
self.pool
.xdel(stream.tenant_aware_key(self), ids)
.await
.change_context(errors::RedisError::StreamDeleteFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_trim_entries<C>(
&self,
stream: &RedisKey,
xcap: C,
) -> CustomResult<usize, errors::RedisError>
where
C: TryInto<XCap> + Debug + Send + Sync,
C::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.xtrim(stream.tenant_aware_key(self), xcap)
.await
.change_context(errors::RedisError::StreamTrimFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_acknowledge_entries<Ids>(
&self,
stream: &RedisKey,
group: &str,
ids: Ids,
) -> CustomResult<usize, errors::RedisError>
where
Ids: Into<MultipleIDs> + Debug + Send + Sync,
{
self.pool
.xack(stream.tenant_aware_key(self), group, ids)
.await
.change_context(errors::RedisError::StreamAcknowledgeFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_get_length(
&self,
stream: &RedisKey,
) -> CustomResult<usize, errors::RedisError> {
self.pool
.xlen(stream.tenant_aware_key(self))
.await
.change_context(errors::RedisError::GetLengthFailed)
}
pub fn get_keys_with_prefix<K>(&self, keys: K) -> MultipleKeys
where
K: Into<MultipleKeys> + Debug + Send + Sync,
{
let multiple_keys: MultipleKeys = keys.into();
let res = multiple_keys
.inner()
.iter()
.filter_map(|key| key.as_str().map(RedisKey::from))
.map(|k: RedisKey| k.tenant_aware_key(self))
.collect::<Vec<_>>();
MultipleKeys::from(res)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_read_entries<K, Ids>(
&self,
streams: K,
ids: Ids,
read_count: Option<u64>,
) -> CustomResult<XReadResponse<String, String, String, String>, errors::RedisError>
where
K: Into<MultipleKeys> + Debug + Send + Sync,
Ids: Into<MultipleIDs> + Debug + Send + Sync,
{
let strms = self.get_keys_with_prefix(streams);
self.pool
.xread_map(
Some(read_count.unwrap_or(self.config.default_stream_read_count)),
None,
strms,
ids,
)
.await
.map_err(|err| match err.kind() {
RedisErrorKind::NotFound | RedisErrorKind::Parse => {
report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable)
}
_ => report!(err).change_context(errors::RedisError::StreamReadFailed),
})
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_read_with_options<K, Ids>(
&self,
streams: K,
ids: Ids,
count: Option<u64>,
block: Option<u64>, // timeout in milliseconds
group: Option<(&str, &str)>, // (group_name, consumer_name)
) -> CustomResult<XReadResponse<String, String, String, Option<String>>, errors::RedisError>
where
K: Into<MultipleKeys> + Debug + Send + Sync,
Ids: Into<MultipleIDs> + Debug + Send + Sync,
{
match group {
Some((group_name, consumer_name)) => {
self.pool
.xreadgroup_map(
group_name,
consumer_name,
count,
block,
false,
self.get_keys_with_prefix(streams),
ids,
)
.await
}
None => {
self.pool
.xread_map(count, block, self.get_keys_with_prefix(streams), ids)
.await
}
}
.map_err(|err| match err.kind() {
RedisErrorKind::NotFound | RedisErrorKind::Parse => {
report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable)
}
_ => report!(err).change_context(errors::RedisError::StreamReadFailed),
})
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn append_elements_to_list<V>(
&self,
key: &RedisKey,
elements: V,
) -> CustomResult<(), errors::RedisError>
where
V: TryInto<MultipleValues> + Debug + Send,
V::Error: Into<fred::error::RedisError> + Send,
{
self.pool
.rpush(key.tenant_aware_key(self), elements)
.await
.change_context(errors::RedisError::AppendElementsToListFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_list_elements(
&self,
key: &RedisKey,
start: i64,
stop: i64,
) -> CustomResult<Vec<String>, errors::RedisError> {
self.pool
.lrange(key.tenant_aware_key(self), start, stop)
.await
.change_context(errors::RedisError::GetListElementsFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_list_length(&self, key: &RedisKey) -> CustomResult<usize, errors::RedisError> {
self.pool
.llen(key.tenant_aware_key(self))
.await
.change_context(errors::RedisError::GetListLengthFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn lpop_list_elements(
&self,
key: &RedisKey,
count: Option<usize>,
) -> CustomResult<Vec<String>, errors::RedisError> {
self.pool
.lpop(key.tenant_aware_key(self), count)
.await
.change_context(errors::RedisError::PopListElementsFailed)
}
// Consumer Group API
#[instrument(level = "DEBUG", skip(self))]
pub async fn consumer_group_create(
&self,
stream: &RedisKey,
group: &str,
id: &RedisEntryId,
) -> CustomResult<(), errors::RedisError> {
if matches!(
id,
RedisEntryId::AutoGeneratedID | RedisEntryId::UndeliveredEntryID
) {
// FIXME: Replace with utils::when
Err(errors::RedisError::InvalidRedisEntryId)?;
}
self.pool
.xgroup_create(stream.tenant_aware_key(self), group, id, true)
.await
.change_context(errors::RedisError::ConsumerGroupCreateFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn consumer_group_destroy(
&self,
stream: &RedisKey,
group: &str,
) -> CustomResult<usize, errors::RedisError> {
self.pool
.xgroup_destroy(stream.tenant_aware_key(self), group)
.await
.change_context(errors::RedisError::ConsumerGroupDestroyFailed)
}
// the number of pending messages that the consumer had before it was deleted
#[instrument(level = "DEBUG", skip(self))]
pub async fn consumer_group_delete_consumer(
&self,
stream: &RedisKey,
group: &str,
consumer: &str,
) -> CustomResult<usize, errors::RedisError> {
self.pool
.xgroup_delconsumer(stream.tenant_aware_key(self), group, consumer)
.await
.change_context(errors::RedisError::ConsumerGroupRemoveConsumerFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn consumer_group_set_last_id(
&self,
stream: &RedisKey,
group: &str,
id: &RedisEntryId,
) -> CustomResult<String, errors::RedisError> {
self.pool
.xgroup_setid(stream.tenant_aware_key(self), group, id)
.await
.change_context(errors::RedisError::ConsumerGroupSetIdFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn consumer_group_set_message_owner<Ids, R>(
&self,
stream: &RedisKey,
group: &str,
consumer: &str,
min_idle_time: u64,
ids: Ids,
) -> CustomResult<R, errors::RedisError>
where
Ids: Into<MultipleIDs> + Debug + Send + Sync,
R: FromRedis + Unpin + Send + 'static,
{
self.pool
.xclaim(
stream.tenant_aware_key(self),
group,
consumer,
min_idle_time,
ids,
None,
None,
None,
false,
false,
)
.await
.change_context(errors::RedisError::ConsumerGroupClaimFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn evaluate_redis_script<V, T>(
&self,
lua_script: &'static str,
key: Vec<String>,
values: V,
) -> CustomResult<T, errors::RedisError>
where
V: TryInto<MultipleValues> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
T: serde::de::DeserializeOwned + FromRedis,
{
let val: T = self
.pool
.eval(lua_script, key, values)
.await
.change_context(errors::RedisError::IncrementHashFieldFailed)?;
Ok(val)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_multiple_keys_if_not_exists_and_get_values<V>(
&self,
keys: &[(RedisKey, V)],
ttl: Option<i64>,
) -> CustomResult<Vec<SetGetReply<V>>, errors::RedisError>
where
V: TryInto<RedisValue>
+ Debug
+ FromRedis
+ ToOwned<Owned = V>
+ Send
+ Sync
+ serde::de::DeserializeOwned,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
let futures = keys.iter().map(|(key, value)| {
self.set_key_if_not_exists_and_get_value(key, (*value).to_owned(), ttl)
});
let del_result = futures::future::try_join_all(futures)
.await
.change_context(errors::RedisError::SetFailed)?;
Ok(del_result)
}
/// Sets a value in Redis if not already present, and returns the value (either existing or newly set).
/// This operation is atomic using Redis transactions.
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_key_if_not_exists_and_get_value<V>(
&self,
key: &RedisKey,
value: V,
ttl: Option<i64>,
) -> CustomResult<SetGetReply<V>, errors::RedisError>
where
V: TryInto<RedisValue> + Debug + FromRedis + Send + Sync + serde::de::DeserializeOwned,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
let redis_key = key.tenant_aware_key(self);
let ttl_seconds = ttl.unwrap_or(self.config.default_ttl.into());
// Get a client from the pool and start transaction
let trx = self.get_transaction();
// Try to set if not exists with expiry - queue the command
trx.set::<(), _, _>(
&redis_key,
value,
Some(Expiration::EX(ttl_seconds)),
Some(SetOptions::NX),
false,
)
.await
.change_context(errors::RedisError::SetFailed)
.attach_printable("Failed to queue set command")?;
// Always get the value after the SET attempt - queue the command
trx.get::<V, _>(&redis_key)
.await
.change_context(errors::RedisError::GetFailed)
.attach_printable("Failed to queue get command")?;
// Execute transaction
let mut results: Vec<RedisValue> = trx
.exec(true)
.await
.change_context(errors::RedisError::SetFailed)
.attach_printable("Failed to execute the redis transaction")?;
let msg = "Got unexpected number of results from transaction";
let get_result = results
.pop()
.ok_or(errors::RedisError::SetFailed)
.attach_printable(msg)?;
let set_result = results
.pop()
.ok_or(errors::RedisError::SetFailed)
.attach_printable(msg)?;
// Parse the GET result to get the actual value
let actual_value: V = FromRedis::from_value(get_result)
.change_context(errors::RedisError::SetFailed)
.attach_printable("Failed to convert from redis value")?;
// Check if SET NX succeeded or failed
match set_result {
// SET NX returns "OK" if key was set
RedisValue::String(_) => Ok(SetGetReply::ValueSet(actual_value)),
// SET NX returns null if key already exists
RedisValue::Null => Ok(SetGetReply::ValueExists(actual_value)),
_ => Err(report!(errors::RedisError::SetFailed))
.attach_printable("Unexpected result from SET NX operation"),
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used, clippy::unwrap_used)]
use std::collections::HashMap;
use crate::{errors::RedisError, RedisConnectionPool, RedisEntryId, RedisSettings};
#[tokio::test]
async fn test_consumer_group_create() {
let is_invalid_redis_entry_error = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let redis_conn = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
// Act
let result1 = redis_conn
.consumer_group_create(&"TEST1".into(), "GTEST", &RedisEntryId::AutoGeneratedID)
.await;
let result2 = redis_conn
.consumer_group_create(
&"TEST3".into(),
"GTEST",
&RedisEntryId::UndeliveredEntryID,
)
.await;
// Assert Setup
*result1.unwrap_err().current_context() == RedisError::InvalidRedisEntryId
&& *result2.unwrap_err().current_context() == RedisError::InvalidRedisEntryId
})
})
.await
.expect("Spawn block failure");
assert!(is_invalid_redis_entry_error);
}
#[tokio::test]
async fn test_delete_existing_key_success() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let _ = pool.set_key(&"key".into(), "value".to_string()).await;
// Act
let result = pool.delete_key(&"key".into()).await;
// Assert setup
result.is_ok()
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
#[tokio::test]
async fn test_delete_non_existing_key_success() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
// Act
let result = pool.delete_key(&"key not exists".into()).await;
// Assert Setup
result.is_ok()
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
#[tokio::test]
async fn test_setting_keys_using_scripts() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let lua_script = r#"
for i = 1, #KEYS do
redis.call("INCRBY", KEYS[i], ARGV[i])
end
return
"#;
let mut keys_and_values = HashMap::new();
for i in 0..10 {
keys_and_values.insert(format!("key{i}"), i);
}
let key = keys_and_values.keys().cloned().collect::<Vec<_>>();
let values = keys_and_values
.values()
.map(|val| val.to_string())
.collect::<Vec<String>>();
// Act
let result = pool
.evaluate_redis_script::<_, ()>(lua_script, key, values)
.await;
// Assert Setup
result.is_ok()
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
#[tokio::test]
async fn test_getting_keys_using_scripts() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
// First set some keys
for i in 0..3 {
let key = format!("script_test_key{i}").into();
let _ = pool.set_key(&key, format!("value{i}")).await;
}
let lua_script = r#"
local results = {}
for i = 1, #KEYS do
results[i] = redis.call("GET", KEYS[i])
end
return results
"#;
let keys = vec![
"script_test_key0".to_string(),
"script_test_key1".to_string(),
"script_test_key2".to_string(),
];
// Act
let result = pool
.evaluate_redis_script::<_, Vec<String>>(lua_script, keys, vec![""])
.await;
// Assert Setup
result.is_ok()
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
#[tokio::test]
async fn test_set_key_if_not_exists_and_get_value_new_key() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key = "test_new_key_string".into();
let value = "test_value".to_string();
// Act
let result = pool
.set_key_if_not_exists_and_get_value(&key, value.clone(), Some(30))
.await;
// Assert
match result {
Ok(crate::types::SetGetReply::ValueSet(returned_value)) => {
returned_value == value
}
_ => false,
}
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
#[tokio::test]
async fn test_set_key_if_not_exists_and_get_value_existing_key() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key = "test_existing_key_string".into();
let initial_value = "initial_value".to_string();
let new_value = "new_value".to_string();
// First, set an initial value using regular set_key
let _ = pool.set_key(&key, initial_value.clone()).await;
// Act - try to set a new value (should fail and return existing value)
let result = pool
.set_key_if_not_exists_and_get_value(&key, new_value, Some(30))
.await;
// Assert
match result {
Ok(crate::types::SetGetReply::ValueExists(returned_value)) => {
returned_value == initial_value
}
_ => false,
}
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
#[tokio::test]
async fn test_set_key_if_not_exists_and_get_value_with_default_ttl() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key = "test_default_ttl_key_string".into();
let value = "test_value".to_string();
// Act - use None for TTL to test default behavior
let result = pool
.set_key_if_not_exists_and_get_value(&key, value.clone(), None)
.await;
// Assert
match result {
Ok(crate::types::SetGetReply::ValueSet(returned_value)) => {
returned_value == value
}
_ => false,
}
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
#[tokio::test]
async fn test_set_key_if_not_exists_and_get_value_concurrent_access() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let key_name = "test_concurrent_key_string";
let value1 = "value1".to_string();
let value2 = "value2".to_string();
// Act - simulate concurrent access
let pool1 = pool.clone("");
let pool2 = pool.clone("");
let key1 = key_name.into();
let key2 = key_name.into();
let (result1, result2) = tokio::join!(
pool1.set_key_if_not_exists_and_get_value(&key1, value1, Some(30)),
pool2.set_key_if_not_exists_and_get_value(&key2, value2, Some(30))
);
// Assert - one should succeed with ValueSet, one should fail with ValueExists
let result1_is_set = matches!(result1, Ok(crate::types::SetGetReply::ValueSet(_)));
let result2_is_set = matches!(result2, Ok(crate::types::SetGetReply::ValueSet(_)));
let result1_is_exists =
matches!(result1, Ok(crate::types::SetGetReply::ValueExists(_)));
let result2_is_exists =
matches!(result2, Ok(crate::types::SetGetReply::ValueExists(_)));
// Exactly one should be ValueSet and one should be ValueExists
(result1_is_set && result2_is_exists) || (result1_is_exists && result2_is_set)
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
#[tokio::test]
async fn test_get_multiple_keys_success() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
// Set up test data
let keys = vec![
"multi_test_key1".into(),
"multi_test_key2".into(),
"multi_test_key3".into(),
];
let values = ["value1", "value2", "value3"];
// Set the keys
for (key, value) in keys.iter().zip(values.iter()) {
let _ = pool.set_key(key, value.to_string()).await;
}
// Act
let result = pool.get_multiple_keys::<String>(&keys).await;
// Assert
match result {
Ok(retrieved_values) => {
retrieved_values.len() == 3
&& retrieved_values.first() == Some(&Some("value1".to_string()))
&& retrieved_values.get(1) == Some(&Some("value2".to_string()))
&& retrieved_values.get(2) == Some(&Some("value3".to_string()))
}
_ => false,
}
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
#[tokio::test]
async fn test_get_multiple_keys_with_missing_keys() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let keys = vec![
"existing_key".into(),
"non_existing_key".into(),
"another_existing_key".into(),
];
// Set only some keys
let _ = pool
.set_key(
keys.first().expect("should not be none"),
"value1".to_string(),
)
.await;
let _ = pool
.set_key(
keys.get(2).expect("should not be none"),
"value3".to_string(),
)
.await;
// Act
let result = pool.get_multiple_keys::<String>(&keys).await;
// Assert
match result {
Ok(retrieved_values) => {
retrieved_values.len() == 3
&& *retrieved_values.first().expect("should not be none")
== Some("value1".to_string())
&& retrieved_values.get(1).is_some_and(|v| v.is_none())
&& *retrieved_values.get(2).expect("should not be none")
== Some("value3".to_string())
}
_ => false,
}
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
#[tokio::test]
async fn test_get_multiple_keys_empty_input() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
let keys: Vec<crate::types::RedisKey> = vec![];
// Act
let result = pool.get_multiple_keys::<String>(&keys).await;
// Assert
match result {
Ok(retrieved_values) => retrieved_values.is_empty(),
_ => false,
}
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
#[tokio::test]
async fn test_get_and_deserialize_multiple_keys() {
let is_success = tokio::task::spawn_blocking(move || {
futures::executor::block_on(async {
// Arrange
let pool = RedisConnectionPool::new(&RedisSettings::default())
.await
.expect("failed to create redis connection pool");
#[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug, Clone)]
struct TestData {
id: u32,
name: String,
}
let test_data = [
TestData {
id: 1,
name: "test1".to_string(),
},
TestData {
id: 2,
name: "test2".to_string(),
},
];
let keys = vec![
"serialize_test_key1".into(),
"serialize_test_key2".into(),
"non_existing_serialize_key".into(),
];
// Set serialized data for first two keys
for (i, data) in test_data.iter().enumerate() {
let _ = pool
.serialize_and_set_key(keys.get(i).expect("should not be none"), data)
.await;
}
// Act
let result = pool
.get_and_deserialize_multiple_keys::<TestData>(&keys, "TestData")
.await;
// Assert
match result {
Ok(retrieved_data) => {
retrieved_data.len() == 3
&& retrieved_data.first() == Some(&Some(test_data[0].clone()))
&& retrieved_data.get(1) == Some(&Some(test_data[1].clone()))
&& retrieved_data.get(2) == Some(&None)
}
_ => false,
}
})
})
.await
.expect("Spawn block failure");
assert!(is_success);
}
}
</file>
|
{
"crate": "redis_interface",
"file": "crates/redis_interface/src/commands.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 12052
}
|
large_file_5372505162865322972
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: payment_methods
File: crates/payment_methods/src/controller.rs
</path>
<file>
use std::fmt::Debug;
#[cfg(feature = "payouts")]
use api_models::payouts;
use api_models::{enums as api_enums, payment_methods as api};
#[cfg(feature = "v1")]
use common_enums::enums as common_enums;
#[cfg(feature = "v2")]
use common_utils::encryption;
use common_utils::{crypto, ext_traits, id_type, type_name, types::keymanager};
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::payment_methods::PaymentMethodVaultSourceDetails;
use hyperswitch_domain_models::{merchant_key_store, payment_methods, type_encryption};
use masking::{PeekInterface, Secret};
#[cfg(feature = "v1")]
use scheduler::errors as sch_errors;
use serde::{Deserialize, Serialize};
use storage_impl::{errors as storage_errors, payment_method};
use crate::core::errors;
#[derive(Debug, Deserialize, Serialize)]
pub struct DeleteCardResp {
pub status: String,
pub error_message: Option<String>,
pub error_code: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DataDuplicationCheck {
Duplicated,
MetaDataChanged,
}
#[async_trait::async_trait]
pub trait PaymentMethodsController {
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn create_payment_method(
&self,
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
payment_method_id: &str,
locker_id: Option<String>,
merchant_id: &id_type::MerchantId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
payment_method_data: crypto::OptionalEncryptableValue,
connector_mandate_details: Option<serde_json::Value>,
status: Option<common_enums::PaymentMethodStatus>,
network_transaction_id: Option<String>,
payment_method_billing_address: crypto::OptionalEncryptableValue,
card_scheme: Option<String>,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: crypto::OptionalEncryptableValue,
vault_source_details: Option<PaymentMethodVaultSourceDetails>,
) -> errors::PmResult<payment_methods::PaymentMethod>;
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn insert_payment_method(
&self,
resp: &api::PaymentMethodResponse,
req: &api::PaymentMethodCreate,
key_store: &merchant_key_store::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
locker_id: Option<String>,
connector_mandate_details: Option<serde_json::Value>,
network_transaction_id: Option<String>,
payment_method_billing_address: crypto::OptionalEncryptableValue,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: crypto::OptionalEncryptableValue,
vault_source_details: Option<PaymentMethodVaultSourceDetails>,
) -> errors::PmResult<payment_methods::PaymentMethod>;
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn insert_payment_method(
&self,
resp: &api::PaymentMethodResponse,
req: &api::PaymentMethodCreate,
key_store: &merchant_key_store::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
locker_id: Option<String>,
connector_mandate_details: Option<serde_json::Value>,
network_transaction_id: Option<String>,
payment_method_billing_address: Option<encryption::Encryption>,
) -> errors::PmResult<payment_methods::PaymentMethod>;
#[cfg(feature = "v1")]
async fn add_payment_method(
&self,
req: &api::PaymentMethodCreate,
) -> errors::PmResponse<api::PaymentMethodResponse>;
#[cfg(feature = "v1")]
async fn retrieve_payment_method(
&self,
pm: api::PaymentMethodId,
) -> errors::PmResponse<api::PaymentMethodResponse>;
#[cfg(feature = "v1")]
async fn delete_payment_method(
&self,
pm_id: api::PaymentMethodId,
) -> errors::PmResponse<api::PaymentMethodDeleteResponse>;
async fn add_card_hs(
&self,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
locker_choice: api_enums::LockerChoice,
card_reference: Option<&str>,
) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>;
/// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method
async fn add_card_to_locker(
&self,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
card_reference: Option<&str>,
) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>;
#[cfg(feature = "payouts")]
async fn add_bank_to_locker(
&self,
req: api::PaymentMethodCreate,
key_store: &merchant_key_store::MerchantKeyStore,
bank: &payouts::Bank,
customer_id: &id_type::CustomerId,
) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>;
#[cfg(feature = "v1")]
async fn get_or_insert_payment_method(
&self,
req: api::PaymentMethodCreate,
resp: &mut api::PaymentMethodResponse,
customer_id: &id_type::CustomerId,
key_store: &merchant_key_store::MerchantKeyStore,
) -> errors::PmResult<payment_methods::PaymentMethod>;
#[cfg(feature = "v2")]
async fn get_or_insert_payment_method(
&self,
_req: api::PaymentMethodCreate,
_resp: &mut api::PaymentMethodResponse,
_customer_id: &id_type::CustomerId,
_key_store: &merchant_key_store::MerchantKeyStore,
) -> errors::PmResult<payment_methods::PaymentMethod> {
todo!()
}
#[cfg(feature = "v1")]
async fn get_card_details_with_locker_fallback(
&self,
pm: &payment_methods::PaymentMethod,
) -> errors::PmResult<Option<api::CardDetailFromLocker>>;
#[cfg(feature = "v1")]
async fn get_card_details_without_locker_fallback(
&self,
pm: &payment_methods::PaymentMethod,
) -> errors::PmResult<api::CardDetailFromLocker>;
async fn delete_card_from_locker(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> errors::PmResult<DeleteCardResp>;
#[cfg(feature = "v1")]
fn store_default_payment_method(
&self,
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> (api::PaymentMethodResponse, Option<DataDuplicationCheck>);
#[cfg(feature = "v2")]
fn store_default_payment_method(
&self,
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> (api::PaymentMethodResponse, Option<DataDuplicationCheck>);
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn save_network_token_and_update_payment_method(
&self,
req: &api::PaymentMethodMigrate,
key_store: &merchant_key_store::MerchantKeyStore,
network_token_data: &api_models::payment_methods::MigrateNetworkTokenData,
network_token_requestor_ref_id: String,
pm_id: String,
) -> errors::PmResult<bool>;
#[cfg(feature = "v1")]
async fn set_default_payment_method(
&self,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
payment_method_id: String,
) -> errors::PmResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse>;
#[cfg(feature = "v1")]
async fn add_payment_method_status_update_task(
&self,
payment_method: &payment_methods::PaymentMethod,
prev_status: common_enums::PaymentMethodStatus,
curr_status: common_enums::PaymentMethodStatus,
merchant_id: &id_type::MerchantId,
) -> Result<(), sch_errors::ProcessTrackerError>;
#[cfg(feature = "v1")]
async fn validate_merchant_connector_ids_in_connector_mandate_details(
&self,
key_store: &merchant_key_store::MerchantKeyStore,
connector_mandate_details: &api_models::payment_methods::CommonMandateReference,
merchant_id: &id_type::MerchantId,
card_network: Option<common_enums::CardNetwork>,
) -> errors::PmResult<()>;
#[cfg(feature = "v1")]
async fn get_card_details_from_locker(
&self,
pm: &payment_methods::PaymentMethod,
) -> errors::PmResult<api::CardDetailFromLocker>;
}
pub async fn create_encrypted_data<T>(
key_manager_state: &keymanager::KeyManagerState,
key_store: &merchant_key_store::MerchantKeyStore,
data: T,
) -> Result<
crypto::Encryptable<Secret<serde_json::Value>>,
error_stack::Report<storage_errors::StorageError>,
>
where
T: Debug + Serialize,
{
let key = key_store.key.get_inner().peek();
let identifier = keymanager::Identifier::Merchant(key_store.merchant_id.clone());
let encoded_data = ext_traits::Encode::encode_to_value(&data)
.change_context(storage_errors::StorageError::SerializationFailed)
.attach_printable("Unable to encode data")?;
let secret_data = Secret::<_, masking::WithType>::new(encoded_data);
let encrypted_data = type_encryption::crypto_operation(
key_manager_state,
type_name!(payment_method::PaymentMethod),
type_encryption::CryptoOperation::Encrypt(secret_data),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_operation())
.change_context(storage_errors::StorageError::EncryptionError)
.attach_printable("Unable to encrypt data")?;
Ok(encrypted_data)
}
</file>
|
{
"crate": "payment_methods",
"file": "crates/payment_methods/src/controller.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2396
}
|
large_file_2254975610905864971
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: payment_methods
File: crates/payment_methods/src/helpers.rs
</path>
<file>
use api_models::{enums as api_enums, payment_methods as api};
#[cfg(feature = "v1")]
use common_utils::ext_traits::AsyncExt;
pub use hyperswitch_domain_models::{errors::api_error_response, payment_methods as domain};
#[cfg(feature = "v1")]
use router_env::logger;
use crate::state;
#[cfg(feature = "v1")]
pub async fn populate_bin_details_for_payment_method_create(
card_details: api_models::payment_methods::CardDetail,
db: Box<dyn state::PaymentMethodsStorageInterface>,
) -> api_models::payment_methods::CardDetail {
let card_isin: Option<_> = Some(card_details.card_number.get_card_isin());
if card_details.card_issuer.is_some()
&& card_details.card_network.is_some()
&& card_details.card_type.is_some()
&& card_details.card_issuing_country.is_some()
{
api::CardDetail {
card_issuer: card_details.card_issuer.to_owned(),
card_network: card_details.card_network.clone(),
card_type: card_details.card_type.to_owned(),
card_issuing_country: card_details.card_issuing_country.to_owned(),
card_exp_month: card_details.card_exp_month.clone(),
card_exp_year: card_details.card_exp_year.clone(),
card_holder_name: card_details.card_holder_name.clone(),
card_number: card_details.card_number.clone(),
nick_name: card_details.nick_name.clone(),
}
} else {
let card_info = card_isin
.clone()
.async_and_then(|card_isin| async move {
db.get_card_info(&card_isin)
.await
.map_err(|error| logger::error!(card_info_error=?error))
.ok()
})
.await
.flatten()
.map(|card_info| api::CardDetail {
card_issuer: card_info.card_issuer,
card_network: card_info.card_network.clone(),
card_type: card_info.card_type,
card_issuing_country: card_info.card_issuing_country,
card_exp_month: card_details.card_exp_month.clone(),
card_exp_year: card_details.card_exp_year.clone(),
card_holder_name: card_details.card_holder_name.clone(),
card_number: card_details.card_number.clone(),
nick_name: card_details.nick_name.clone(),
});
card_info.unwrap_or_else(|| api::CardDetail {
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
card_exp_month: card_details.card_exp_month.clone(),
card_exp_year: card_details.card_exp_year.clone(),
card_holder_name: card_details.card_holder_name.clone(),
card_number: card_details.card_number.clone(),
nick_name: card_details.nick_name.clone(),
})
}
}
#[cfg(feature = "v2")]
pub async fn populate_bin_details_for_payment_method_create(
_card_details: api_models::payment_methods::CardDetail,
_db: &dyn state::PaymentMethodsStorageInterface,
) -> api_models::payment_methods::CardDetail {
todo!()
}
pub fn validate_payment_method_type_against_payment_method(
payment_method: api_enums::PaymentMethod,
payment_method_type: api_enums::PaymentMethodType,
) -> bool {
match payment_method {
#[cfg(feature = "v1")]
api_enums::PaymentMethod::Card => matches!(
payment_method_type,
api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit
),
#[cfg(feature = "v2")]
api_enums::PaymentMethod::Card => matches!(
payment_method_type,
api_enums::PaymentMethodType::Credit
| api_enums::PaymentMethodType::Debit
| api_enums::PaymentMethodType::Card
),
api_enums::PaymentMethod::PayLater => matches!(
payment_method_type,
api_enums::PaymentMethodType::Affirm
| api_enums::PaymentMethodType::Alma
| api_enums::PaymentMethodType::AfterpayClearpay
| api_enums::PaymentMethodType::Klarna
| api_enums::PaymentMethodType::PayBright
| api_enums::PaymentMethodType::Atome
| api_enums::PaymentMethodType::Walley
| api_enums::PaymentMethodType::Breadpay
| api_enums::PaymentMethodType::Flexiti
),
api_enums::PaymentMethod::Wallet => matches!(
payment_method_type,
api_enums::PaymentMethodType::AmazonPay
| api_enums::PaymentMethodType::Bluecode
| api_enums::PaymentMethodType::Paysera
| api_enums::PaymentMethodType::Skrill
| api_enums::PaymentMethodType::ApplePay
| api_enums::PaymentMethodType::GooglePay
| api_enums::PaymentMethodType::Paypal
| api_enums::PaymentMethodType::AliPay
| api_enums::PaymentMethodType::AliPayHk
| api_enums::PaymentMethodType::Dana
| api_enums::PaymentMethodType::MbWay
| api_enums::PaymentMethodType::MobilePay
| api_enums::PaymentMethodType::SamsungPay
| api_enums::PaymentMethodType::Twint
| api_enums::PaymentMethodType::Vipps
| api_enums::PaymentMethodType::TouchNGo
| api_enums::PaymentMethodType::Swish
| api_enums::PaymentMethodType::WeChatPay
| api_enums::PaymentMethodType::GoPay
| api_enums::PaymentMethodType::Gcash
| api_enums::PaymentMethodType::Momo
| api_enums::PaymentMethodType::KakaoPay
| api_enums::PaymentMethodType::Cashapp
| api_enums::PaymentMethodType::Mifinity
| api_enums::PaymentMethodType::Paze
| api_enums::PaymentMethodType::RevolutPay
),
api_enums::PaymentMethod::BankRedirect => matches!(
payment_method_type,
api_enums::PaymentMethodType::Giropay
| api_enums::PaymentMethodType::Ideal
| api_enums::PaymentMethodType::Sofort
| api_enums::PaymentMethodType::Eft
| api_enums::PaymentMethodType::Eps
| api_enums::PaymentMethodType::BancontactCard
| api_enums::PaymentMethodType::Blik
| api_enums::PaymentMethodType::LocalBankRedirect
| api_enums::PaymentMethodType::OnlineBankingThailand
| api_enums::PaymentMethodType::OnlineBankingCzechRepublic
| api_enums::PaymentMethodType::OnlineBankingFinland
| api_enums::PaymentMethodType::OnlineBankingFpx
| api_enums::PaymentMethodType::OnlineBankingPoland
| api_enums::PaymentMethodType::OnlineBankingSlovakia
| api_enums::PaymentMethodType::Przelewy24
| api_enums::PaymentMethodType::Trustly
| api_enums::PaymentMethodType::Bizum
| api_enums::PaymentMethodType::Interac
| api_enums::PaymentMethodType::OpenBankingUk
| api_enums::PaymentMethodType::OpenBankingPIS
),
api_enums::PaymentMethod::BankTransfer => matches!(
payment_method_type,
api_enums::PaymentMethodType::Ach
| api_enums::PaymentMethodType::SepaBankTransfer
| api_enums::PaymentMethodType::Bacs
| api_enums::PaymentMethodType::Multibanco
| api_enums::PaymentMethodType::Pix
| api_enums::PaymentMethodType::Pse
| api_enums::PaymentMethodType::PermataBankTransfer
| api_enums::PaymentMethodType::BcaBankTransfer
| api_enums::PaymentMethodType::BniVa
| api_enums::PaymentMethodType::BriVa
| api_enums::PaymentMethodType::CimbVa
| api_enums::PaymentMethodType::DanamonVa
| api_enums::PaymentMethodType::MandiriVa
| api_enums::PaymentMethodType::LocalBankTransfer
| api_enums::PaymentMethodType::InstantBankTransfer
| api_enums::PaymentMethodType::InstantBankTransferFinland
| api_enums::PaymentMethodType::InstantBankTransferPoland
| api_enums::PaymentMethodType::IndonesianBankTransfer
),
api_enums::PaymentMethod::BankDebit => matches!(
payment_method_type,
api_enums::PaymentMethodType::Ach
| api_enums::PaymentMethodType::Sepa
| api_enums::PaymentMethodType::SepaGuarenteedDebit
| api_enums::PaymentMethodType::Bacs
| api_enums::PaymentMethodType::Becs
),
api_enums::PaymentMethod::Crypto => matches!(
payment_method_type,
api_enums::PaymentMethodType::CryptoCurrency
),
api_enums::PaymentMethod::Reward => matches!(
payment_method_type,
api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward
),
api_enums::PaymentMethod::RealTimePayment => matches!(
payment_method_type,
api_enums::PaymentMethodType::Fps
| api_enums::PaymentMethodType::DuitNow
| api_enums::PaymentMethodType::PromptPay
| api_enums::PaymentMethodType::VietQr
),
api_enums::PaymentMethod::Upi => matches!(
payment_method_type,
api_enums::PaymentMethodType::UpiCollect
| api_enums::PaymentMethodType::UpiIntent
| api_enums::PaymentMethodType::UpiQr
),
api_enums::PaymentMethod::Voucher => matches!(
payment_method_type,
api_enums::PaymentMethodType::Boleto
| api_enums::PaymentMethodType::Efecty
| api_enums::PaymentMethodType::PagoEfectivo
| api_enums::PaymentMethodType::RedCompra
| api_enums::PaymentMethodType::RedPagos
| api_enums::PaymentMethodType::Indomaret
| api_enums::PaymentMethodType::Alfamart
| api_enums::PaymentMethodType::Oxxo
| api_enums::PaymentMethodType::SevenEleven
| api_enums::PaymentMethodType::Lawson
| api_enums::PaymentMethodType::MiniStop
| api_enums::PaymentMethodType::FamilyMart
| api_enums::PaymentMethodType::Seicomart
| api_enums::PaymentMethodType::PayEasy
),
api_enums::PaymentMethod::GiftCard => {
matches!(
payment_method_type,
api_enums::PaymentMethodType::Givex | api_enums::PaymentMethodType::PaySafeCard
)
}
api_enums::PaymentMethod::CardRedirect => matches!(
payment_method_type,
api_enums::PaymentMethodType::Knet
| api_enums::PaymentMethodType::Benefit
| api_enums::PaymentMethodType::MomoAtm
| api_enums::PaymentMethodType::CardRedirect
),
api_enums::PaymentMethod::OpenBanking => matches!(
payment_method_type,
api_enums::PaymentMethodType::OpenBankingPIS
),
api_enums::PaymentMethod::MobilePayment => matches!(
payment_method_type,
api_enums::PaymentMethodType::DirectCarrierBilling
),
}
}
pub trait ForeignFrom<F> {
fn foreign_from(from: F) -> Self;
}
/// Trait for converting from one foreign type to another
pub trait ForeignTryFrom<F>: Sized {
/// Custom error for conversion failure
type Error;
/// Convert from a foreign type to the current type and return an error if the conversion fails
fn foreign_try_from(from: F) -> Result<Self, Self::Error>;
}
#[cfg(feature = "v1")]
impl ForeignFrom<(Option<api::CardDetailFromLocker>, domain::PaymentMethod)>
for api::PaymentMethodResponse
{
fn foreign_from(
(card_details, item): (Option<api::CardDetailFromLocker>, domain::PaymentMethod),
) -> Self {
Self {
merchant_id: item.merchant_id.to_owned(),
customer_id: Some(item.customer_id.to_owned()),
payment_method_id: item.get_id().clone(),
payment_method: item.get_payment_method_type(),
payment_method_type: item.get_payment_method_subtype(),
card: card_details,
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: None,
metadata: item.metadata,
created: Some(item.created_at),
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: None,
client_secret: item.client_secret,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<(Option<api::CardDetailFromLocker>, domain::PaymentMethod)>
for api::PaymentMethodResponse
{
fn foreign_from(
(_card_details, _item): (Option<api::CardDetailFromLocker>, domain::PaymentMethod),
) -> Self {
todo!()
}
}
pub trait StorageErrorExt<T, E> {
#[track_caller]
fn to_not_found_response(self, not_found_response: E) -> error_stack::Result<T, E>;
#[track_caller]
fn to_duplicate_response(self, duplicate_response: E) -> error_stack::Result<T, E>;
}
impl<T> StorageErrorExt<T, api_error_response::ApiErrorResponse>
for error_stack::Result<T, storage_impl::StorageError>
{
#[track_caller]
fn to_not_found_response(
self,
not_found_response: api_error_response::ApiErrorResponse,
) -> error_stack::Result<T, api_error_response::ApiErrorResponse> {
self.map_err(|err| {
let new_err = match err.current_context() {
storage_impl::StorageError::ValueNotFound(_) => not_found_response,
storage_impl::StorageError::CustomerRedacted => {
api_error_response::ApiErrorResponse::CustomerRedacted
}
_ => api_error_response::ApiErrorResponse::InternalServerError,
};
err.change_context(new_err)
})
}
#[track_caller]
fn to_duplicate_response(
self,
duplicate_response: api_error_response::ApiErrorResponse,
) -> error_stack::Result<T, api_error_response::ApiErrorResponse> {
self.map_err(|err| {
let new_err = match err.current_context() {
storage_impl::StorageError::DuplicateValue { .. } => duplicate_response,
_ => api_error_response::ApiErrorResponse::InternalServerError,
};
err.change_context(new_err)
})
}
}
</file>
|
{
"crate": "payment_methods",
"file": "crates/payment_methods/src/helpers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3309
}
|
large_file_5624175765570621261
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: payment_methods
File: crates/payment_methods/src/core/migration.rs
</path>
<file>
use actix_multipart::form::{self, bytes, text};
use api_models::payment_methods as pm_api;
use csv::Reader;
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::{api, merchant_context};
use masking::PeekInterface;
use rdkafka::message::ToBytes;
use router_env::{instrument, tracing};
use crate::core::errors;
#[cfg(feature = "v1")]
use crate::{controller as pm, state};
pub mod payment_methods;
pub use payment_methods::migrate_payment_method;
#[cfg(feature = "v1")]
type PmMigrationResult<T> =
errors::CustomResult<api::ApplicationResponse<T>, errors::ApiErrorResponse>;
#[cfg(feature = "v1")]
pub async fn migrate_payment_methods(
state: &state::PaymentMethodsState,
payment_methods: Vec<pm_api::PaymentMethodRecord>,
merchant_id: &common_utils::id_type::MerchantId,
merchant_context: &merchant_context::MerchantContext,
mca_ids: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
controller: &dyn pm::PaymentMethodsController,
) -> PmMigrationResult<Vec<pm_api::PaymentMethodMigrationResponse>> {
let mut result = Vec::with_capacity(payment_methods.len());
for record in payment_methods {
let req = pm_api::PaymentMethodMigrate::try_from((
&record,
merchant_id.clone(),
mca_ids.as_ref(),
))
.map_err(|err| errors::ApiErrorResponse::InvalidRequestData {
message: format!("error: {err:?}"),
})
.attach_printable("record deserialization failed");
let res = match req {
Ok(migrate_request) => {
let res = migrate_payment_method(
state,
migrate_request,
merchant_id,
merchant_context,
controller,
)
.await;
match res {
Ok(api::ApplicationResponse::Json(response)) => Ok(response),
Err(e) => Err(e.to_string()),
_ => Err("Failed to migrate payment method".to_string()),
}
}
Err(e) => Err(e.to_string()),
};
result.push(pm_api::PaymentMethodMigrationResponse::from((res, record)));
}
Ok(api::ApplicationResponse::Json(result))
}
#[derive(Debug, form::MultipartForm)]
pub struct PaymentMethodsMigrateForm {
#[multipart(limit = "1MB")]
pub file: bytes::Bytes,
pub merchant_id: text::Text<common_utils::id_type::MerchantId>,
pub merchant_connector_id:
Option<text::Text<common_utils::id_type::MerchantConnectorAccountId>>,
pub merchant_connector_ids: Option<text::Text<String>>,
}
pub struct MerchantConnectorValidator;
impl MerchantConnectorValidator {
pub fn parse_comma_separated_ids(
ids_string: &str,
) -> Result<Vec<common_utils::id_type::MerchantConnectorAccountId>, errors::ApiErrorResponse>
{
// Estimate capacity based on comma count
let capacity = ids_string.matches(',').count() + 1;
let mut result = Vec::with_capacity(capacity);
for id in ids_string.split(',') {
let trimmed_id = id.trim();
if !trimmed_id.is_empty() {
let mca_id =
common_utils::id_type::MerchantConnectorAccountId::wrap(trimmed_id.to_string())
.map_err(|_| errors::ApiErrorResponse::InvalidRequestData {
message: format!("Invalid merchant_connector_account_id: {trimmed_id}"),
})?;
result.push(mca_id);
}
}
Ok(result)
}
fn validate_form_csv_conflicts(
records: &[pm_api::PaymentMethodRecord],
form_has_single_id: bool,
form_has_multiple_ids: bool,
) -> Result<(), errors::ApiErrorResponse> {
if form_has_single_id {
// If form has merchant_connector_id, CSV records should not have merchant_connector_ids
for (index, record) in records.iter().enumerate() {
if record.merchant_connector_ids.is_some() {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Record at line {} has merchant_connector_ids but form has merchant_connector_id. Only one should be provided",
index + 1
),
});
}
}
}
if form_has_multiple_ids {
// If form has merchant_connector_ids, CSV records should not have merchant_connector_id
for (index, record) in records.iter().enumerate() {
if record.merchant_connector_id.is_some() {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Record at line {} has merchant_connector_id but form has merchant_connector_ids. Only one should be provided",
index + 1
),
});
}
}
}
Ok(())
}
}
type MigrationValidationResult = Result<
(
common_utils::id_type::MerchantId,
Vec<pm_api::PaymentMethodRecord>,
Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
),
errors::ApiErrorResponse,
>;
impl PaymentMethodsMigrateForm {
pub fn validate_and_get_payment_method_records(self) -> MigrationValidationResult {
// Step 1: Validate form-level conflicts
let form_has_single_id = self.merchant_connector_id.is_some();
let form_has_multiple_ids = self.merchant_connector_ids.is_some();
if form_has_single_id && form_has_multiple_ids {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Both merchant_connector_id and merchant_connector_ids cannot be provided"
.to_string(),
});
}
// Ensure at least one is provided
if !form_has_single_id && !form_has_multiple_ids {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Either merchant_connector_id or merchant_connector_ids must be provided"
.to_string(),
});
}
// Step 2: Parse CSV
let records = parse_csv(self.file.data.to_bytes()).map_err(|e| {
errors::ApiErrorResponse::PreconditionFailed {
message: e.to_string(),
}
})?;
// Step 3: Validate CSV vs Form conflicts
MerchantConnectorValidator::validate_form_csv_conflicts(
&records,
form_has_single_id,
form_has_multiple_ids,
)?;
// Step 4: Prepare the merchant connector account IDs for return
let mca_ids = if let Some(ref single_id) = self.merchant_connector_id {
Some(vec![(**single_id).clone()])
} else if let Some(ref ids_string) = self.merchant_connector_ids {
let parsed_ids = MerchantConnectorValidator::parse_comma_separated_ids(ids_string)?;
if parsed_ids.is_empty() {
None
} else {
Some(parsed_ids)
}
} else {
None
};
// Step 5: Return the updated structure
Ok((self.merchant_id.clone(), records, mca_ids))
}
}
fn parse_csv(data: &[u8]) -> csv::Result<Vec<pm_api::PaymentMethodRecord>> {
let mut csv_reader = Reader::from_reader(data);
let mut records = Vec::new();
let mut id_counter = 0;
for result in csv_reader.deserialize() {
let mut record: pm_api::PaymentMethodRecord = result?;
id_counter += 1;
record.line_number = Some(id_counter);
records.push(record);
}
Ok(records)
}
#[instrument(skip_all)]
pub fn validate_card_expiry(
card_exp_month: &masking::Secret<String>,
card_exp_year: &masking::Secret<String>,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
let exp_month = card_exp_month
.peek()
.to_string()
.parse::<u8>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_exp_month",
})?;
::cards::CardExpirationMonth::try_from(exp_month).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Month".to_string(),
},
)?;
let year_str = card_exp_year.peek().to_string();
validate_card_exp_year(year_str).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Year".to_string(),
},
)?;
Ok(())
}
fn validate_card_exp_year(year: String) -> Result<(), errors::ValidationError> {
let year_str = year.to_string();
if year_str.len() == 2 || year_str.len() == 4 {
year_str
.parse::<u16>()
.map_err(|_| errors::ValidationError::InvalidValue {
message: "card_exp_year".to_string(),
})?;
Ok(())
} else {
Err(errors::ValidationError::InvalidValue {
message: "invalid card expiration year".to_string(),
})
}
}
#[derive(Debug)]
pub struct RecordMigrationStatus {
pub card_migrated: Option<bool>,
pub network_token_migrated: Option<bool>,
pub connector_mandate_details_migrated: Option<bool>,
pub network_transaction_migrated: Option<bool>,
}
#[derive(Debug)]
pub struct RecordMigrationStatusBuilder {
pub card_migrated: Option<bool>,
pub network_token_migrated: Option<bool>,
pub connector_mandate_details_migrated: Option<bool>,
pub network_transaction_migrated: Option<bool>,
}
impl RecordMigrationStatusBuilder {
pub fn new() -> Self {
Self {
card_migrated: None,
network_token_migrated: None,
connector_mandate_details_migrated: None,
network_transaction_migrated: None,
}
}
pub fn card_migrated(&mut self, card_migrated: bool) {
self.card_migrated = Some(card_migrated);
}
pub fn network_token_migrated(&mut self, network_token_migrated: Option<bool>) {
self.network_token_migrated = network_token_migrated;
}
pub fn connector_mandate_details_migrated(
&mut self,
connector_mandate_details_migrated: Option<bool>,
) {
self.connector_mandate_details_migrated = connector_mandate_details_migrated;
}
pub fn network_transaction_id_migrated(&mut self, network_transaction_migrated: Option<bool>) {
self.network_transaction_migrated = network_transaction_migrated;
}
pub fn build(self) -> RecordMigrationStatus {
RecordMigrationStatus {
card_migrated: self.card_migrated,
network_token_migrated: self.network_token_migrated,
connector_mandate_details_migrated: self.connector_mandate_details_migrated,
network_transaction_migrated: self.network_transaction_migrated,
}
}
}
impl Default for RecordMigrationStatusBuilder {
fn default() -> Self {
Self::new()
}
}
</file>
|
{
"crate": "payment_methods",
"file": "crates/payment_methods/src/core/migration.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2315
}
|
large_file_-6173627940170277159
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: payment_methods
File: crates/payment_methods/src/core/migration/payment_methods.rs
</path>
<file>
use std::str::FromStr;
#[cfg(feature = "v2")]
use api_models::enums as api_enums;
#[cfg(feature = "v1")]
use api_models::enums;
use api_models::payment_methods as pm_api;
#[cfg(feature = "v1")]
use common_utils::{
consts,
crypto::Encryptable,
ext_traits::{AsyncExt, ConfigExt},
generate_id,
};
use common_utils::{errors::CustomResult, id_type};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
api::ApplicationResponse, errors::api_error_response as errors, merchant_context,
};
#[cfg(feature = "v1")]
use hyperswitch_domain_models::{ext_traits::OptionExt, payment_methods as domain_pm};
use masking::PeekInterface;
#[cfg(feature = "v1")]
use masking::Secret;
#[cfg(feature = "v1")]
use router_env::{instrument, logger, tracing};
#[cfg(feature = "v1")]
use serde_json::json;
use storage_impl::cards_info;
#[cfg(feature = "v1")]
use crate::{
controller::create_encrypted_data,
core::migration,
helpers::{ForeignFrom, StorageErrorExt},
};
use crate::{controller::PaymentMethodsController, helpers::ForeignTryFrom, state};
#[cfg(feature = "v1")]
pub async fn migrate_payment_method(
state: &state::PaymentMethodsState,
req: pm_api::PaymentMethodMigrate,
merchant_id: &id_type::MerchantId,
merchant_context: &merchant_context::MerchantContext,
controller: &dyn PaymentMethodsController,
) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse>
{
let mut req = req;
let card_details = &req.card.get_required_value("card")?;
let card_number_validation_result =
cards::CardNumber::from_str(card_details.card_number.peek());
let card_bin_details = populate_bin_details_for_masked_card(
card_details,
&*state.store,
req.payment_method_type.as_ref(),
)
.await?;
req.card = Some(api_models::payment_methods::MigrateCardDetail {
card_issuing_country: card_bin_details.issuer_country.clone(),
card_network: card_bin_details.card_network.clone(),
card_issuer: card_bin_details.card_issuer.clone(),
card_type: card_bin_details.card_type.clone(),
..card_details.clone()
});
if let Some(connector_mandate_details) = &req.connector_mandate_details {
controller
.validate_merchant_connector_ids_in_connector_mandate_details(
merchant_context.get_merchant_key_store(),
connector_mandate_details,
merchant_id,
card_bin_details.card_network.clone(),
)
.await?;
};
let should_require_connector_mandate_details = req.network_token.is_none();
let mut migration_status = migration::RecordMigrationStatusBuilder::new();
let resp = match card_number_validation_result {
Ok(card_number) => {
let payment_method_create_request =
pm_api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate(
card_number,
&req,
);
logger::debug!("Storing the card in locker and migrating the payment method");
get_client_secret_or_add_payment_method_for_migration(
state,
payment_method_create_request,
merchant_context,
&mut migration_status,
controller,
)
.await?
}
Err(card_validation_error) => {
logger::debug!("Card number to be migrated is invalid, skip saving in locker {card_validation_error}");
skip_locker_call_and_migrate_payment_method(
state,
&req,
merchant_id.to_owned(),
merchant_context,
card_bin_details.clone(),
should_require_connector_mandate_details,
&mut migration_status,
controller,
)
.await?
}
};
let payment_method_response = match resp {
ApplicationResponse::Json(response) => response,
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the payment method response")?,
};
let pm_id = payment_method_response.payment_method_id.clone();
let network_token = req.network_token.clone();
let network_token_migrated = match network_token {
Some(nt_detail) => {
logger::debug!("Network token migration");
let network_token_requestor_ref_id = nt_detail.network_token_requestor_ref_id.clone();
let network_token_data = &nt_detail.network_token_data;
Some(
controller
.save_network_token_and_update_payment_method(
&req,
merchant_context.get_merchant_key_store(),
network_token_data,
network_token_requestor_ref_id,
pm_id,
)
.await
.map_err(|err| logger::error!(?err, "Failed to save network token"))
.ok()
.unwrap_or_default(),
)
}
None => {
logger::debug!("Network token data is not available");
None
}
};
migration_status.network_token_migrated(network_token_migrated);
let migrate_status = migration_status.build();
Ok(ApplicationResponse::Json(
pm_api::PaymentMethodMigrateResponse {
payment_method_response,
card_migrated: migrate_status.card_migrated,
network_token_migrated: migrate_status.network_token_migrated,
connector_mandate_details_migrated: migrate_status.connector_mandate_details_migrated,
network_transaction_id_migrated: migrate_status.network_transaction_migrated,
},
))
}
#[cfg(feature = "v2")]
pub async fn migrate_payment_method(
_state: &state::PaymentMethodsState,
_req: pm_api::PaymentMethodMigrate,
_merchant_id: &id_type::MerchantId,
_merchant_context: &merchant_context::MerchantContext,
_controller: &dyn PaymentMethodsController,
) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse>
{
todo!()
}
#[cfg(feature = "v1")]
pub async fn populate_bin_details_for_masked_card(
card_details: &api_models::payment_methods::MigrateCardDetail,
db: &dyn state::PaymentMethodsStorageInterface,
payment_method_type: Option<&enums::PaymentMethodType>,
) -> CustomResult<pm_api::CardDetailFromLocker, errors::ApiErrorResponse> {
if let Some(
// Cards
enums::PaymentMethodType::Credit
| enums::PaymentMethodType::Debit
// Wallets
| enums::PaymentMethodType::ApplePay
| enums::PaymentMethodType::GooglePay,
) = payment_method_type {
migration::validate_card_expiry(
&card_details.card_exp_month,
&card_details.card_exp_year,
)?;
}
let card_number = card_details.card_number.clone();
let (card_isin, _last4_digits) = get_card_bin_and_last4_digits_for_masked_card(
card_number.peek(),
)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid masked card number".to_string(),
})?;
let card_bin_details = if card_details.card_issuer.is_some()
&& card_details.card_network.is_some()
&& card_details.card_type.is_some()
&& card_details.card_issuing_country.is_some()
{
pm_api::CardDetailFromLocker::foreign_try_from((card_details, None))?
} else {
let card_info = db
.get_card_info(&card_isin)
.await
.map_err(|error| logger::error!(card_info_error=?error))
.ok()
.flatten();
pm_api::CardDetailFromLocker::foreign_try_from((card_details, card_info))?
};
Ok(card_bin_details)
}
#[cfg(feature = "v1")]
impl
ForeignTryFrom<(
&api_models::payment_methods::MigrateCardDetail,
Option<cards_info::CardInfo>,
)> for pm_api::CardDetailFromLocker
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
(card_details, card_info): (
&api_models::payment_methods::MigrateCardDetail,
Option<cards_info::CardInfo>,
),
) -> Result<Self, Self::Error> {
let (card_isin, last4_digits) =
get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid masked card number".to_string(),
})?;
if let Some(card_bin_info) = card_info {
Ok(Self {
scheme: card_details
.card_network
.clone()
.or(card_bin_info.card_network.clone())
.map(|card_network| card_network.to_string()),
last4_digits: Some(last4_digits.clone()),
issuer_country: card_details
.card_issuing_country
.clone()
.or(card_bin_info.card_issuing_country),
card_number: None,
expiry_month: Some(card_details.card_exp_month.clone()),
expiry_year: Some(card_details.card_exp_year.clone()),
card_token: None,
card_fingerprint: None,
card_holder_name: card_details.card_holder_name.clone(),
nick_name: card_details.nick_name.clone(),
card_isin: Some(card_isin.clone()),
card_issuer: card_details
.card_issuer
.clone()
.or(card_bin_info.card_issuer),
card_network: card_details
.card_network
.clone()
.or(card_bin_info.card_network),
card_type: card_details.card_type.clone().or(card_bin_info.card_type),
saved_to_locker: false,
})
} else {
Ok(Self {
scheme: card_details
.card_network
.clone()
.map(|card_network| card_network.to_string()),
last4_digits: Some(last4_digits.clone()),
issuer_country: card_details.card_issuing_country.clone(),
card_number: None,
expiry_month: Some(card_details.card_exp_month.clone()),
expiry_year: Some(card_details.card_exp_year.clone()),
card_token: None,
card_fingerprint: None,
card_holder_name: card_details.card_holder_name.clone(),
nick_name: card_details.nick_name.clone(),
card_isin: Some(card_isin.clone()),
card_issuer: card_details.card_issuer.clone(),
card_network: card_details.card_network.clone(),
card_type: card_details.card_type.clone(),
saved_to_locker: false,
})
}
}
}
#[cfg(feature = "v2")]
impl
ForeignTryFrom<(
&api_models::payment_methods::MigrateCardDetail,
Option<cards_info::CardInfo>,
)> for pm_api::CardDetailFromLocker
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
(card_details, card_info): (
&api_models::payment_methods::MigrateCardDetail,
Option<cards_info::CardInfo>,
),
) -> Result<Self, Self::Error> {
let (card_isin, last4_digits) =
get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid masked card number".to_string(),
})?;
if let Some(card_bin_info) = card_info {
Ok(Self {
last4_digits: Some(last4_digits.clone()),
issuer_country: card_details
.card_issuing_country
.as_ref()
.map(|c| api_enums::CountryAlpha2::from_str(c))
.transpose()
.ok()
.flatten()
.or(card_bin_info
.card_issuing_country
.as_ref()
.map(|c| api_enums::CountryAlpha2::from_str(c))
.transpose()
.ok()
.flatten()),
card_number: None,
expiry_month: Some(card_details.card_exp_month.clone()),
expiry_year: Some(card_details.card_exp_year.clone()),
card_fingerprint: None,
card_holder_name: card_details.card_holder_name.clone(),
nick_name: card_details.nick_name.clone(),
card_isin: Some(card_isin.clone()),
card_issuer: card_details
.card_issuer
.clone()
.or(card_bin_info.card_issuer),
card_network: card_details
.card_network
.clone()
.or(card_bin_info.card_network),
card_type: card_details.card_type.clone().or(card_bin_info.card_type),
saved_to_locker: false,
})
} else {
Ok(Self {
last4_digits: Some(last4_digits.clone()),
issuer_country: card_details
.card_issuing_country
.as_ref()
.map(|c| api_enums::CountryAlpha2::from_str(c))
.transpose()
.ok()
.flatten(),
card_number: None,
expiry_month: Some(card_details.card_exp_month.clone()),
expiry_year: Some(card_details.card_exp_year.clone()),
card_fingerprint: None,
card_holder_name: card_details.card_holder_name.clone(),
nick_name: card_details.nick_name.clone(),
card_isin: Some(card_isin.clone()),
card_issuer: card_details.card_issuer.clone(),
card_network: card_details.card_network.clone(),
card_type: card_details.card_type.clone(),
saved_to_locker: false,
})
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn get_client_secret_or_add_payment_method_for_migration(
state: &state::PaymentMethodsState,
req: pm_api::PaymentMethodCreate,
merchant_context: &merchant_context::MerchantContext,
migration_status: &mut migration::RecordMigrationStatusBuilder,
controller: &dyn PaymentMethodsController,
) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> {
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
#[cfg(not(feature = "payouts"))]
let condition = req.card.is_some();
#[cfg(feature = "payouts")]
let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();
let key_manager_state = &state.into();
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
.async_map(|billing| {
create_encrypted_data(
key_manager_state,
merchant_context.get_merchant_key_store(),
billing,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?;
let connector_mandate_details = req
.connector_mandate_details
.clone()
.map(serde_json::to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
if condition {
Box::pin(save_migration_payment_method(
req,
migration_status,
controller,
))
.await
} else {
let payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let res = controller
.create_payment_method(
&req,
&customer_id,
payment_method_id.as_str(),
None,
merchant_id,
None,
None,
None,
connector_mandate_details.clone(),
Some(enums::PaymentMethodStatus::AwaitingData),
None,
payment_method_billing_address,
None,
None,
None,
None,
Default::default(),
)
.await?;
migration_status.connector_mandate_details_migrated(
connector_mandate_details
.clone()
.and_then(|val| (val != json!({})).then_some(true))
.or_else(|| {
req.connector_mandate_details
.clone()
.and_then(|val| (!val.0.is_empty()).then_some(false))
}),
);
//card is not migrated in this case
migration_status.card_migrated(false);
if res.status == enums::PaymentMethodStatus::AwaitingData {
controller
.add_payment_method_status_update_task(
&res,
enums::PaymentMethodStatus::AwaitingData,
enums::PaymentMethodStatus::Inactive,
merchant_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to add payment method status update task in process tracker",
)?;
}
Ok(ApplicationResponse::Json(
pm_api::PaymentMethodResponse::foreign_from((None, res)),
))
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn skip_locker_call_and_migrate_payment_method(
state: &state::PaymentMethodsState,
req: &pm_api::PaymentMethodMigrate,
merchant_id: id_type::MerchantId,
merchant_context: &merchant_context::MerchantContext,
card: pm_api::CardDetailFromLocker,
should_require_connector_mandate_details: bool,
migration_status: &mut migration::RecordMigrationStatusBuilder,
controller: &dyn PaymentMethodsController,
) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> {
let db = &*state.store;
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
// In this case, since we do not have valid card details, recurring payments can only be done through connector mandate details.
//if network token data is present, then connector mandate details are not mandatory
let connector_mandate_details = if should_require_connector_mandate_details {
let connector_mandate_details_req = req
.connector_mandate_details
.clone()
.and_then(|c| c.payments)
.clone()
.get_required_value("connector mandate details")?;
Some(
serde_json::to_value(&connector_mandate_details_req)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse connector mandate details")?,
)
} else {
req.connector_mandate_details
.clone()
.and_then(|c| c.payments)
.map(|mandate_details_req| {
serde_json::to_value(&mandate_details_req)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse connector mandate details")
})
.transpose()?
};
let key_manager_state = &state.into();
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
.async_map(|billing| {
create_encrypted_data(
key_manager_state,
merchant_context.get_merchant_key_store(),
billing,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?;
let customer = db
.find_customer_by_customer_id_merchant_id(
&state.into(),
&customer_id,
&merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let payment_method_card_details = pm_api::PaymentMethodsData::Card(
pm_api::CardDetailsPaymentMethod::from((card.clone(), None)),
);
let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some(
create_encrypted_data(
&state.into(),
merchant_context.get_merchant_key_store(),
payment_method_card_details,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method card details")?,
);
let payment_method_metadata: Option<serde_json::Value> =
req.metadata.as_ref().map(|data| data.peek()).cloned();
let network_transaction_id = req.network_transaction_id.clone();
let payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let current_time = common_utils::date_time::now();
let response = db
.insert_payment_method(
&state.into(),
merchant_context.get_merchant_key_store(),
domain_pm::PaymentMethod {
customer_id: customer_id.to_owned(),
merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
locker_id: None,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
payment_method_issuer: req.payment_method_issuer.clone(),
scheme: req.card_network.clone().or(card.scheme.clone()),
metadata: payment_method_metadata.map(Secret::new),
payment_method_data: payment_method_data_encrypted,
connector_mandate_details: connector_mandate_details.clone(),
customer_acceptance: None,
client_secret: None,
status: enums::PaymentMethodStatus::Active,
network_transaction_id: network_transaction_id.clone(),
payment_method_issuer_code: None,
accepted_currency: None,
token: None,
cardholder_name: None,
issuer_name: None,
issuer_country: None,
payer_country: None,
is_stored: None,
swift_code: None,
direct_debit_token: None,
created_at: current_time,
last_modified: current_time,
last_used_at: current_time,
payment_method_billing_address,
updated_by: None,
version: common_types::consts::API_VERSION,
network_token_requestor_reference_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
vault_source_details: Default::default(),
},
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
logger::debug!("Payment method inserted in db");
migration_status.network_transaction_id_migrated(
network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)),
);
migration_status.connector_mandate_details_migrated(
connector_mandate_details
.clone()
.and_then(|val| if val == json!({}) { None } else { Some(true) })
.or_else(|| {
req.connector_mandate_details.clone().and_then(|val| {
val.payments
.and_then(|payin_val| (!payin_val.0.is_empty()).then_some(false))
})
}),
);
if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = controller
.set_default_payment_method(&merchant_id, &customer_id, payment_method_id.to_owned())
.await
.map_err(|error| logger::error!(?error, "Failed to set the payment method as default"));
}
Ok(ApplicationResponse::Json(
pm_api::PaymentMethodResponse::foreign_from((Some(card), response)),
))
}
// need to discuss regarding the migration APIs for v2
#[cfg(feature = "v2")]
pub async fn skip_locker_call_and_migrate_payment_method(
_state: state::PaymentMethodsState,
_req: &pm_api::PaymentMethodMigrate,
_merchant_id: id_type::MerchantId,
_merchant_context: &merchant_context::MerchantContext,
_card: pm_api::CardDetailFromLocker,
) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> {
todo!()
}
pub fn get_card_bin_and_last4_digits_for_masked_card(
masked_card_number: &str,
) -> Result<(String, String), cards::CardNumberValidationErr> {
let last4_digits = masked_card_number
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>();
let card_isin = masked_card_number.chars().take(6).collect::<String>();
cards::validate::validate_card_number_chars(&card_isin)
.and_then(|_| cards::validate::validate_card_number_chars(&last4_digits))?;
Ok((card_isin, last4_digits))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn save_migration_payment_method(
req: pm_api::PaymentMethodCreate,
migration_status: &mut migration::RecordMigrationStatusBuilder,
controller: &dyn PaymentMethodsController,
) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> {
let connector_mandate_details = req
.connector_mandate_details
.clone()
.map(serde_json::to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let network_transaction_id = req.network_transaction_id.clone();
let res = controller.add_payment_method(&req).await?;
migration_status.card_migrated(true);
migration_status.network_transaction_id_migrated(
network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)),
);
migration_status.connector_mandate_details_migrated(
connector_mandate_details
.and_then(|val| if val == json!({}) { None } else { Some(true) })
.or_else(|| {
req.connector_mandate_details
.and_then(|val| (!val.0.is_empty()).then_some(false))
}),
);
Ok(res)
}
</file>
|
{
"crate": "payment_methods",
"file": "crates/payment_methods/src/core/migration/payment_methods.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5513
}
|
large_file_8607188275135870085
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: pm_auth
File: crates/pm_auth/src/connector/plaid.rs
</path>
<file>
pub mod transformers;
use std::fmt::Debug;
use common_utils::{
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::ResultExt;
use masking::{Mask, Maskable};
use transformers as plaid;
use crate::{
core::errors,
types::{
self as auth_types,
api::{
auth_service::{
self, BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate,
},
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
},
},
};
#[derive(Debug, Clone)]
pub struct Plaid;
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &auth_types::PaymentAuthRouterData<Flow, Request, Response>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
"Content-Type".to_string(),
self.get_content_type().to_string().into(),
)];
let mut auth = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut auth);
Ok(header)
}
}
impl ConnectorCommon for Plaid {
fn id(&self) -> &'static str {
"plaid"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, _connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str {
"https://sandbox.plaid.com"
}
fn get_auth_header(
&self,
auth_type: &auth_types::ConnectorAuthType,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = plaid::PlaidAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let client_id = auth.client_id.into_masked();
let secret = auth.secret.into_masked();
Ok(vec![
("PLAID-CLIENT-ID".to_string(), client_id),
("PLAID-SECRET".to_string(), secret),
])
}
fn build_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
let response: plaid::PlaidErrorResponse =
res.response
.parse_struct("PlaidErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(auth_types::ErrorResponse {
status_code: res.status_code,
code: crate::consts::NO_ERROR_CODE.to_string(),
message: response.error_message,
reason: response.display_message,
})
}
}
impl auth_service::AuthService for Plaid {}
impl auth_service::PaymentInitiationRecipientCreate for Plaid {}
impl auth_service::PaymentInitiation for Plaid {}
impl auth_service::AuthServiceLinkToken for Plaid {}
impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse>
for Plaid
{
fn get_headers(
&self,
req: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/link/token/create"
))
}
fn get_request_body(
&self,
req: &auth_types::LinkTokenRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidLinkTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthLinkTokenType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthLinkTokenType::get_headers(
self, req, connectors,
)?)
.set_body(auth_types::PaymentAuthLinkTokenType::get_request_body(
self, req,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::LinkTokenRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::LinkTokenRouterData, errors::ConnectorError> {
let response: plaid::PlaidLinkTokenResponse = res
.response
.parse_struct("PlaidLinkTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::LinkTokenRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl auth_service::AuthServiceExchangeToken for Plaid {}
impl
ConnectorIntegration<
ExchangeToken,
auth_types::ExchangeTokenRequest,
auth_types::ExchangeTokenResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/item/public_token/exchange"
))
}
fn get_request_body(
&self,
req: &auth_types::ExchangeTokenRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidExchangeTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthExchangeTokenType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthExchangeTokenType::get_headers(
self, req, connectors,
)?)
.set_body(auth_types::PaymentAuthExchangeTokenType::get_request_body(
self, req,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::ExchangeTokenRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ExchangeTokenRouterData, errors::ConnectorError> {
let response: plaid::PlaidExchangeTokenResponse = res
.response
.parse_struct("PlaidExchangeTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::ExchangeTokenRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl auth_service::AuthServiceBankAccountCredentials for Plaid {}
impl
ConnectorIntegration<
BankAccountCredentials,
auth_types::BankAccountCredentialsRequest,
auth_types::BankAccountCredentialsResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/auth/get"))
}
fn get_request_body(
&self,
req: &auth_types::BankDetailsRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidBankAccountCredentialsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthBankAccountDetailsType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthBankAccountDetailsType::get_headers(
self, req, connectors,
)?)
.set_body(
auth_types::PaymentAuthBankAccountDetailsType::get_request_body(self, req)?,
)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::BankDetailsRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::BankDetailsRouterData, errors::ConnectorError> {
let response: plaid::PlaidBankAccountCredentialsResponse = res
.response
.parse_struct("PlaidBankAccountCredentialsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::BankDetailsRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl
ConnectorIntegration<
RecipientCreate,
auth_types::RecipientCreateRequest,
auth_types::RecipientCreateResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/payment_initiation/recipient/create"
))
}
fn get_request_body(
&self,
req: &auth_types::RecipientCreateRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidRecipientCreateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentInitiationRecipientCreateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(
auth_types::PaymentInitiationRecipientCreateType::get_headers(
self, req, connectors,
)?,
)
.set_body(
auth_types::PaymentInitiationRecipientCreateType::get_request_body(self, req)?,
)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::RecipientCreateRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::RecipientCreateRouterData, errors::ConnectorError> {
let response: plaid::PlaidRecipientCreateResponse = res
.response
.parse_struct("PlaidRecipientCreateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(<auth_types::RecipientCreateRouterData>::from(
auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
))
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
</file>
|
{
"crate": "pm_auth",
"file": "crates/pm_auth/src/connector/plaid.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3131
}
|
large_file_-5138947524878285212
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: pm_auth
File: crates/pm_auth/src/connector/plaid/transformers.rs
</path>
<file>
use std::collections::HashMap;
use common_enums::{PaymentMethod, PaymentMethodType};
use common_utils::{id_type, types as util_types};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{core::errors, types};
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidLinkTokenRequest {
client_name: String,
country_codes: Vec<String>,
language: String,
products: Vec<String>,
user: User,
android_package_name: Option<String>,
redirect_uri: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct User {
pub client_user_id: id_type::CustomerId,
}
impl TryFrom<&types::LinkTokenRouterData> for PlaidLinkTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::LinkTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
client_name: item.request.client_name.clone(),
country_codes: item.request.country_codes.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "country_codes",
},
)?,
language: item.request.language.clone().unwrap_or("en".to_string()),
products: vec!["auth".to_string()],
user: User {
client_user_id: item.request.user_info.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "country_codes",
},
)?,
},
android_package_name: match item.request.client_platform {
Some(api_models::enums::ClientPlatform::Android) => {
item.request.android_package_name.clone()
}
Some(api_models::enums::ClientPlatform::Ios)
| Some(api_models::enums::ClientPlatform::Web)
| Some(api_models::enums::ClientPlatform::Unknown)
| None => None,
},
redirect_uri: match item.request.client_platform {
Some(api_models::enums::ClientPlatform::Ios) => item.request.redirect_uri.clone(),
Some(api_models::enums::ClientPlatform::Android)
| Some(api_models::enums::ClientPlatform::Web)
| Some(api_models::enums::ClientPlatform::Unknown)
| None => None,
},
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidLinkTokenResponse {
link_token: String,
}
impl<F, T>
TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>>
for types::PaymentAuthRouterData<F, T, types::LinkTokenResponse>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::LinkTokenResponse {
link_token: item.response.link_token,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidExchangeTokenRequest {
public_token: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidExchangeTokenResponse {
pub access_token: String,
}
impl<F, T>
TryFrom<
types::ResponseRouterData<F, PlaidExchangeTokenResponse, T, types::ExchangeTokenResponse>,
> for types::PaymentAuthRouterData<F, T, types::ExchangeTokenResponse>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<
F,
PlaidExchangeTokenResponse,
T,
types::ExchangeTokenResponse,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::ExchangeTokenResponse {
access_token: item.response.access_token,
}),
..item.data
})
}
}
impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::ExchangeTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
public_token: item.request.public_token.clone(),
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PlaidRecipientCreateRequest {
pub name: String,
#[serde(flatten)]
pub account_data: PlaidRecipientAccountData,
pub address: Option<PlaidRecipientCreateAddress>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidRecipientCreateResponse {
pub recipient_id: String,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PlaidRecipientAccountData {
Iban(Secret<String>),
Bacs {
sort_code: Secret<String>,
account: Secret<String>,
},
}
impl TryFrom<&types::RecipientAccountData> for PlaidRecipientAccountData {
type Error = errors::ConnectorError;
fn try_from(item: &types::RecipientAccountData) -> Result<Self, Self::Error> {
match item {
types::RecipientAccountData::Iban(iban) => Ok(Self::Iban(iban.clone())),
types::RecipientAccountData::Bacs {
sort_code,
account_number,
} => Ok(Self::Bacs {
sort_code: sort_code.clone(),
account: account_number.clone(),
}),
types::RecipientAccountData::FasterPayments { .. }
| types::RecipientAccountData::Sepa(_)
| types::RecipientAccountData::SepaInstant(_)
| types::RecipientAccountData::Elixir { .. }
| types::RecipientAccountData::Bankgiro(_)
| types::RecipientAccountData::Plusgiro(_) => {
Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Invalid payment method selected. Only Iban, Bacs Supported",
})
}
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PlaidRecipientCreateAddress {
pub street: String,
pub city: String,
pub postal_code: String,
pub country: String,
}
impl From<&types::RecipientCreateAddress> for PlaidRecipientCreateAddress {
fn from(item: &types::RecipientCreateAddress) -> Self {
Self {
street: item.street.clone(),
city: item.city.clone(),
postal_code: item.postal_code.clone(),
country: common_enums::CountryAlpha2::to_string(&item.country),
}
}
}
impl TryFrom<&types::RecipientCreateRouterData> for PlaidRecipientCreateRequest {
type Error = errors::ConnectorError;
fn try_from(item: &types::RecipientCreateRouterData) -> Result<Self, Self::Error> {
Ok(Self {
name: item.request.name.clone(),
account_data: PlaidRecipientAccountData::try_from(&item.request.account_data)?,
address: item
.request
.address
.as_ref()
.map(PlaidRecipientCreateAddress::from),
})
}
}
impl<F, T>
From<
types::ResponseRouterData<
F,
PlaidRecipientCreateResponse,
T,
types::RecipientCreateResponse,
>,
> for types::PaymentAuthRouterData<F, T, types::RecipientCreateResponse>
{
fn from(
item: types::ResponseRouterData<
F,
PlaidRecipientCreateResponse,
T,
types::RecipientCreateResponse,
>,
) -> Self {
Self {
response: Ok(types::RecipientCreateResponse {
recipient_id: item.response.recipient_id,
}),
..item.data
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidBankAccountCredentialsRequest {
access_token: String,
options: Option<BankAccountCredentialsOptions>,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct PlaidBankAccountCredentialsResponse {
pub accounts: Vec<PlaidBankAccountCredentialsAccounts>,
pub numbers: PlaidBankAccountCredentialsNumbers,
// pub item: PlaidBankAccountCredentialsItem,
pub request_id: String,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct BankAccountCredentialsOptions {
account_ids: Vec<String>,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct PlaidBankAccountCredentialsAccounts {
pub account_id: String,
pub name: String,
pub subtype: Option<String>,
pub balances: Option<PlaidBankAccountCredentialsBalances>,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct PlaidBankAccountCredentialsBalances {
pub available: Option<util_types::FloatMajorUnit>,
pub current: Option<util_types::FloatMajorUnit>,
pub limit: Option<util_types::FloatMajorUnit>,
pub iso_currency_code: Option<String>,
pub unofficial_currency_code: Option<String>,
pub last_updated_datetime: Option<String>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsNumbers {
pub ach: Vec<PlaidBankAccountCredentialsACH>,
pub eft: Vec<PlaidBankAccountCredentialsEFT>,
pub international: Vec<PlaidBankAccountCredentialsInternational>,
pub bacs: Vec<PlaidBankAccountCredentialsBacs>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsItem {
pub item_id: String,
pub institution_id: Option<String>,
pub webhook: Option<String>,
pub error: Option<PlaidErrorResponse>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsACH {
pub account_id: String,
pub account: String,
pub routing: String,
pub wire_routing: Option<String>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsEFT {
pub account_id: String,
pub account: String,
pub institution: String,
pub branch: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsInternational {
pub account_id: String,
pub iban: String,
pub bic: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsBacs {
pub account_id: String,
pub account: String,
pub sort_code: String,
}
impl TryFrom<&types::BankDetailsRouterData> for PlaidBankAccountCredentialsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::BankDetailsRouterData) -> Result<Self, Self::Error> {
let options = item.request.optional_ids.as_ref().map(|bank_account_ids| {
let ids = bank_account_ids
.ids
.iter()
.map(|id| id.peek().to_string())
.collect::<Vec<_>>();
BankAccountCredentialsOptions { account_ids: ids }
});
Ok(Self {
access_token: item.request.access_token.peek().to_string(),
options,
})
}
}
impl<F, T>
TryFrom<
types::ResponseRouterData<
F,
PlaidBankAccountCredentialsResponse,
T,
types::BankAccountCredentialsResponse,
>,
> for types::PaymentAuthRouterData<F, T, types::BankAccountCredentialsResponse>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<
F,
PlaidBankAccountCredentialsResponse,
T,
types::BankAccountCredentialsResponse,
>,
) -> Result<Self, Self::Error> {
let (account_numbers, accounts_info) = (item.response.numbers, item.response.accounts);
let mut bank_account_vec = Vec::new();
let mut id_to_subtype = HashMap::new();
accounts_info.into_iter().for_each(|acc| {
id_to_subtype.insert(
acc.account_id,
(
acc.subtype,
acc.name,
acc.balances.and_then(|balance| balance.available),
),
);
});
account_numbers.ach.into_iter().for_each(|ach| {
let (acc_type, acc_name, available_balance) = if let Some((
_type,
name,
available_balance,
)) = id_to_subtype.get(&ach.account_id)
{
(_type.to_owned(), Some(name.clone()), *available_balance)
} else {
(None, None, None)
};
let account_details =
types::PaymentMethodTypeDetails::Ach(types::BankAccountDetailsAch {
account_number: Secret::new(ach.account),
routing_number: Secret::new(ach.routing),
});
let bank_details_new = types::BankAccountDetails {
account_name: acc_name,
account_details,
payment_method_type: PaymentMethodType::Ach,
payment_method: PaymentMethod::BankDebit,
account_id: ach.account_id.into(),
account_type: acc_type,
balance: available_balance,
};
bank_account_vec.push(bank_details_new);
});
account_numbers.bacs.into_iter().for_each(|bacs| {
let (acc_type, acc_name, available_balance) =
if let Some((_type, name, available_balance)) = id_to_subtype.get(&bacs.account_id)
{
(_type.to_owned(), Some(name.clone()), *available_balance)
} else {
(None, None, None)
};
let account_details =
types::PaymentMethodTypeDetails::Bacs(types::BankAccountDetailsBacs {
account_number: Secret::new(bacs.account),
sort_code: Secret::new(bacs.sort_code),
});
let bank_details_new = types::BankAccountDetails {
account_name: acc_name,
account_details,
payment_method_type: PaymentMethodType::Bacs,
payment_method: PaymentMethod::BankDebit,
account_id: bacs.account_id.into(),
account_type: acc_type,
balance: available_balance,
};
bank_account_vec.push(bank_details_new);
});
account_numbers.international.into_iter().for_each(|sepa| {
let (acc_type, acc_name, available_balance) =
if let Some((_type, name, available_balance)) = id_to_subtype.get(&sepa.account_id)
{
(_type.to_owned(), Some(name.clone()), *available_balance)
} else {
(None, None, None)
};
let account_details =
types::PaymentMethodTypeDetails::Sepa(types::BankAccountDetailsSepa {
iban: Secret::new(sepa.iban),
bic: Secret::new(sepa.bic),
});
let bank_details_new = types::BankAccountDetails {
account_name: acc_name,
account_details,
payment_method_type: PaymentMethodType::Sepa,
payment_method: PaymentMethod::BankDebit,
account_id: sepa.account_id.into(),
account_type: acc_type,
balance: available_balance,
};
bank_account_vec.push(bank_details_new);
});
Ok(Self {
response: Ok(types::BankAccountCredentialsResponse {
credentials: bank_account_vec,
}),
..item.data
})
}
}
pub struct PlaidAuthType {
pub client_id: Secret<String>,
pub secret: Secret<String>,
}
impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self {
client_id: client_id.to_owned(),
secret: secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidErrorResponse {
pub display_message: Option<String>,
pub error_code: Option<String>,
pub error_message: String,
pub error_type: Option<String>,
}
</file>
|
{
"crate": "pm_auth",
"file": "crates/pm_auth/src/connector/plaid/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3506
}
|
large_file_3622138983423742621
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: kgraph_utils
File: crates/kgraph_utils/src/transformers.rs
</path>
<file>
use api_models::enums as api_enums;
use euclid::{
backend::BackendInput,
dirval,
dssa::types::AnalysisErrorType,
frontend::{ast, dir},
types::{NumValue, StrValue},
};
use crate::error::KgraphError;
pub trait IntoContext {
fn into_context(self) -> Result<Vec<dir::DirValue>, KgraphError>;
}
impl IntoContext for BackendInput {
fn into_context(self) -> Result<Vec<dir::DirValue>, KgraphError> {
let mut ctx: Vec<dir::DirValue> = Vec::new();
ctx.push(dir::DirValue::PaymentAmount(NumValue {
number: self.payment.amount,
refinement: None,
}));
ctx.push(dir::DirValue::PaymentCurrency(self.payment.currency));
if let Some(auth_type) = self.payment.authentication_type {
ctx.push(dir::DirValue::AuthenticationType(auth_type));
}
if let Some(capture_method) = self.payment.capture_method {
ctx.push(dir::DirValue::CaptureMethod(capture_method));
}
if let Some(business_country) = self.payment.business_country {
ctx.push(dir::DirValue::BusinessCountry(business_country));
}
if let Some(business_label) = self.payment.business_label {
ctx.push(dir::DirValue::BusinessLabel(StrValue {
value: business_label,
}));
}
if let Some(billing_country) = self.payment.billing_country {
ctx.push(dir::DirValue::BillingCountry(billing_country));
}
if let Some(payment_method) = self.payment_method.payment_method {
ctx.push(dir::DirValue::PaymentMethod(payment_method));
}
if let (Some(pm_type), Some(payment_method)) = (
self.payment_method.payment_method_type,
self.payment_method.payment_method,
) {
ctx.push((pm_type, payment_method).into_dir_value()?)
}
if let Some(card_network) = self.payment_method.card_network {
ctx.push(dir::DirValue::CardNetwork(card_network));
}
if let Some(setup_future_usage) = self.payment.setup_future_usage {
ctx.push(dir::DirValue::SetupFutureUsage(setup_future_usage));
}
if let Some(mandate_acceptance_type) = self.mandate.mandate_acceptance_type {
ctx.push(dir::DirValue::MandateAcceptanceType(
mandate_acceptance_type,
));
}
if let Some(mandate_type) = self.mandate.mandate_type {
ctx.push(dir::DirValue::MandateType(mandate_type));
}
if let Some(payment_type) = self.mandate.payment_type {
ctx.push(dir::DirValue::PaymentType(payment_type));
}
Ok(ctx)
}
}
pub trait IntoDirValue {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError>;
}
impl IntoDirValue for ast::ConnectorChoice {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
Ok(dir::DirValue::Connector(Box::new(self)))
}
}
impl IntoDirValue for api_enums::PaymentMethod {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self {
Self::Card => Ok(dirval!(PaymentMethod = Card)),
Self::Wallet => Ok(dirval!(PaymentMethod = Wallet)),
Self::PayLater => Ok(dirval!(PaymentMethod = PayLater)),
Self::BankRedirect => Ok(dirval!(PaymentMethod = BankRedirect)),
Self::Crypto => Ok(dirval!(PaymentMethod = Crypto)),
Self::BankDebit => Ok(dirval!(PaymentMethod = BankDebit)),
Self::BankTransfer => Ok(dirval!(PaymentMethod = BankTransfer)),
Self::Reward => Ok(dirval!(PaymentMethod = Reward)),
Self::RealTimePayment => Ok(dirval!(PaymentMethod = RealTimePayment)),
Self::Upi => Ok(dirval!(PaymentMethod = Upi)),
Self::Voucher => Ok(dirval!(PaymentMethod = Voucher)),
Self::GiftCard => Ok(dirval!(PaymentMethod = GiftCard)),
Self::CardRedirect => Ok(dirval!(PaymentMethod = CardRedirect)),
Self::OpenBanking => Ok(dirval!(PaymentMethod = OpenBanking)),
Self::MobilePayment => Ok(dirval!(PaymentMethod = MobilePayment)),
}
}
}
impl IntoDirValue for api_enums::AuthenticationType {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self {
Self::ThreeDs => Ok(dirval!(AuthenticationType = ThreeDs)),
Self::NoThreeDs => Ok(dirval!(AuthenticationType = NoThreeDs)),
}
}
}
impl IntoDirValue for api_enums::FutureUsage {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self {
Self::OnSession => Ok(dirval!(SetupFutureUsage = OnSession)),
Self::OffSession => Ok(dirval!(SetupFutureUsage = OffSession)),
}
}
}
impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self.0 {
api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)),
api_enums::PaymentMethodType::Paysera => Ok(dirval!(WalletType = Paysera)),
api_enums::PaymentMethodType::Skrill => Ok(dirval!(WalletType = Skrill)),
api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)),
api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)),
#[cfg(feature = "v2")]
api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)),
api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)),
api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)),
api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)),
api_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)),
api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)),
api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)),
api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)),
api_enums::PaymentMethodType::AfterpayClearpay => {
Ok(dirval!(PayLaterType = AfterpayClearpay))
}
api_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)),
api_enums::PaymentMethodType::Bluecode => Ok(dirval!(WalletType = Bluecode)),
api_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)),
api_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)),
api_enums::PaymentMethodType::CryptoCurrency => {
Ok(dirval!(CryptoType = CryptoCurrency))
}
api_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)),
api_enums::PaymentMethodType::Ach => match self.1 {
api_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Ach)),
api_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Ach)),
api_enums::PaymentMethod::BankRedirect
| api_enums::PaymentMethod::Card
| api_enums::PaymentMethod::CardRedirect
| api_enums::PaymentMethod::PayLater
| api_enums::PaymentMethod::Wallet
| api_enums::PaymentMethod::Crypto
| api_enums::PaymentMethod::Reward
| api_enums::PaymentMethod::RealTimePayment
| api_enums::PaymentMethod::Upi
| api_enums::PaymentMethod::MobilePayment
| api_enums::PaymentMethod::Voucher
| api_enums::PaymentMethod::OpenBanking
| api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError(
Box::new(AnalysisErrorType::NotSupported),
)),
},
api_enums::PaymentMethodType::Bacs => match self.1 {
api_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Bacs)),
api_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Bacs)),
api_enums::PaymentMethod::BankRedirect
| api_enums::PaymentMethod::Card
| api_enums::PaymentMethod::CardRedirect
| api_enums::PaymentMethod::PayLater
| api_enums::PaymentMethod::Wallet
| api_enums::PaymentMethod::Crypto
| api_enums::PaymentMethod::Reward
| api_enums::PaymentMethod::RealTimePayment
| api_enums::PaymentMethod::Upi
| api_enums::PaymentMethod::MobilePayment
| api_enums::PaymentMethod::Voucher
| api_enums::PaymentMethod::OpenBanking
| api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError(
Box::new(AnalysisErrorType::NotSupported),
)),
},
api_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)),
api_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)),
api_enums::PaymentMethodType::SepaGuarenteedDebit => {
Ok(dirval!(BankDebitType = SepaGuarenteedDebit))
}
api_enums::PaymentMethodType::SepaBankTransfer => {
Ok(dirval!(BankTransferType = SepaBankTransfer))
}
api_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)),
api_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)),
api_enums::PaymentMethodType::BancontactCard => {
Ok(dirval!(BankRedirectType = BancontactCard))
}
api_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)),
api_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)),
api_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)),
api_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)),
api_enums::PaymentMethodType::Multibanco => Ok(dirval!(BankTransferType = Multibanco)),
api_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)),
api_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)),
api_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)),
api_enums::PaymentMethodType::OnlineBankingCzechRepublic => {
Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic))
}
api_enums::PaymentMethodType::OnlineBankingFinland => {
Ok(dirval!(BankRedirectType = OnlineBankingFinland))
}
api_enums::PaymentMethodType::OnlineBankingPoland => {
Ok(dirval!(BankRedirectType = OnlineBankingPoland))
}
api_enums::PaymentMethodType::OnlineBankingSlovakia => {
Ok(dirval!(BankRedirectType = OnlineBankingSlovakia))
}
api_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)),
api_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)),
api_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)),
api_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)),
api_enums::PaymentMethodType::Flexiti => Ok(dirval!(PayLaterType = Flexiti)),
api_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)),
api_enums::PaymentMethodType::Breadpay => Ok(dirval!(PayLaterType = Breadpay)),
api_enums::PaymentMethodType::Przelewy24 => Ok(dirval!(BankRedirectType = Przelewy24)),
api_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)),
api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)),
api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)),
api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)),
api_enums::PaymentMethodType::UpiQr => Ok(dirval!(UpiType = UpiQr)),
api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)),
api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)),
api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)),
api_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)),
api_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)),
api_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)),
api_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)),
api_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)),
api_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)),
api_enums::PaymentMethodType::OnlineBankingFpx => {
Ok(dirval!(BankRedirectType = OnlineBankingFpx))
}
api_enums::PaymentMethodType::LocalBankRedirect => {
Ok(dirval!(BankRedirectType = LocalBankRedirect))
}
api_enums::PaymentMethodType::OnlineBankingThailand => {
Ok(dirval!(BankRedirectType = OnlineBankingThailand))
}
api_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)),
api_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)),
api_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)),
api_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)),
api_enums::PaymentMethodType::PagoEfectivo => Ok(dirval!(VoucherType = PagoEfectivo)),
api_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)),
api_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)),
api_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)),
api_enums::PaymentMethodType::BcaBankTransfer => {
Ok(dirval!(BankTransferType = BcaBankTransfer))
}
api_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)),
api_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)),
api_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)),
api_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)),
api_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)),
api_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)),
api_enums::PaymentMethodType::LocalBankTransfer => {
Ok(dirval!(BankTransferType = LocalBankTransfer))
}
api_enums::PaymentMethodType::InstantBankTransfer => {
Ok(dirval!(BankTransferType = InstantBankTransfer))
}
api_enums::PaymentMethodType::InstantBankTransferFinland => {
Ok(dirval!(BankTransferType = InstantBankTransferFinland))
}
api_enums::PaymentMethodType::InstantBankTransferPoland => {
Ok(dirval!(BankTransferType = InstantBankTransferPoland))
}
api_enums::PaymentMethodType::PermataBankTransfer => {
Ok(dirval!(BankTransferType = PermataBankTransfer))
}
api_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)),
api_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)),
api_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)),
api_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)),
api_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)),
api_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)),
api_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)),
api_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)),
api_enums::PaymentMethodType::BhnCardNetwork => {
Ok(dirval!(GiftCardType = BhnCardNetwork))
}
api_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)),
api_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)),
api_enums::PaymentMethodType::OpenBankingUk => {
Ok(dirval!(BankRedirectType = OpenBankingUk))
}
api_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)),
api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)),
api_enums::PaymentMethodType::CardRedirect => {
Ok(dirval!(CardRedirectType = CardRedirect))
}
api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)),
api_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)),
api_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)),
api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)),
api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)),
api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)),
api_enums::PaymentMethodType::OpenBankingPIS => {
Ok(dirval!(OpenBankingType = OpenBankingPIS))
}
api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)),
api_enums::PaymentMethodType::DirectCarrierBilling => {
Ok(dirval!(MobilePaymentType = DirectCarrierBilling))
}
api_enums::PaymentMethodType::IndonesianBankTransfer => {
Ok(dirval!(BankTransferType = IndonesianBankTransfer))
}
}
}
}
impl IntoDirValue for api_enums::CardNetwork {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self {
Self::Visa => Ok(dirval!(CardNetwork = Visa)),
Self::Mastercard => Ok(dirval!(CardNetwork = Mastercard)),
Self::AmericanExpress => Ok(dirval!(CardNetwork = AmericanExpress)),
Self::JCB => Ok(dirval!(CardNetwork = JCB)),
Self::DinersClub => Ok(dirval!(CardNetwork = DinersClub)),
Self::Discover => Ok(dirval!(CardNetwork = Discover)),
Self::CartesBancaires => Ok(dirval!(CardNetwork = CartesBancaires)),
Self::UnionPay => Ok(dirval!(CardNetwork = UnionPay)),
Self::Interac => Ok(dirval!(CardNetwork = Interac)),
Self::RuPay => Ok(dirval!(CardNetwork = RuPay)),
Self::Maestro => Ok(dirval!(CardNetwork = Maestro)),
Self::Star => Ok(dirval!(CardNetwork = Star)),
Self::Accel => Ok(dirval!(CardNetwork = Accel)),
Self::Pulse => Ok(dirval!(CardNetwork = Pulse)),
Self::Nyce => Ok(dirval!(CardNetwork = Nyce)),
}
}
}
impl IntoDirValue for api_enums::Currency {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self {
Self::AED => Ok(dirval!(PaymentCurrency = AED)),
Self::AFN => Ok(dirval!(PaymentCurrency = AFN)),
Self::ALL => Ok(dirval!(PaymentCurrency = ALL)),
Self::AMD => Ok(dirval!(PaymentCurrency = AMD)),
Self::ANG => Ok(dirval!(PaymentCurrency = ANG)),
Self::AOA => Ok(dirval!(PaymentCurrency = AOA)),
Self::ARS => Ok(dirval!(PaymentCurrency = ARS)),
Self::AUD => Ok(dirval!(PaymentCurrency = AUD)),
Self::AWG => Ok(dirval!(PaymentCurrency = AWG)),
Self::AZN => Ok(dirval!(PaymentCurrency = AZN)),
Self::BAM => Ok(dirval!(PaymentCurrency = BAM)),
Self::BBD => Ok(dirval!(PaymentCurrency = BBD)),
Self::BDT => Ok(dirval!(PaymentCurrency = BDT)),
Self::BGN => Ok(dirval!(PaymentCurrency = BGN)),
Self::BHD => Ok(dirval!(PaymentCurrency = BHD)),
Self::BIF => Ok(dirval!(PaymentCurrency = BIF)),
Self::BMD => Ok(dirval!(PaymentCurrency = BMD)),
Self::BND => Ok(dirval!(PaymentCurrency = BND)),
Self::BOB => Ok(dirval!(PaymentCurrency = BOB)),
Self::BRL => Ok(dirval!(PaymentCurrency = BRL)),
Self::BSD => Ok(dirval!(PaymentCurrency = BSD)),
Self::BTN => Ok(dirval!(PaymentCurrency = BTN)),
Self::BWP => Ok(dirval!(PaymentCurrency = BWP)),
Self::BYN => Ok(dirval!(PaymentCurrency = BYN)),
Self::BZD => Ok(dirval!(PaymentCurrency = BZD)),
Self::CAD => Ok(dirval!(PaymentCurrency = CAD)),
Self::CDF => Ok(dirval!(PaymentCurrency = CDF)),
Self::CHF => Ok(dirval!(PaymentCurrency = CHF)),
Self::CLF => Ok(dirval!(PaymentCurrency = CLF)),
Self::CLP => Ok(dirval!(PaymentCurrency = CLP)),
Self::CNY => Ok(dirval!(PaymentCurrency = CNY)),
Self::COP => Ok(dirval!(PaymentCurrency = COP)),
Self::CRC => Ok(dirval!(PaymentCurrency = CRC)),
Self::CUC => Ok(dirval!(PaymentCurrency = CUC)),
Self::CUP => Ok(dirval!(PaymentCurrency = CUP)),
Self::CVE => Ok(dirval!(PaymentCurrency = CVE)),
Self::CZK => Ok(dirval!(PaymentCurrency = CZK)),
Self::DJF => Ok(dirval!(PaymentCurrency = DJF)),
Self::DKK => Ok(dirval!(PaymentCurrency = DKK)),
Self::DOP => Ok(dirval!(PaymentCurrency = DOP)),
Self::DZD => Ok(dirval!(PaymentCurrency = DZD)),
Self::EGP => Ok(dirval!(PaymentCurrency = EGP)),
Self::ERN => Ok(dirval!(PaymentCurrency = ERN)),
Self::ETB => Ok(dirval!(PaymentCurrency = ETB)),
Self::EUR => Ok(dirval!(PaymentCurrency = EUR)),
Self::FJD => Ok(dirval!(PaymentCurrency = FJD)),
Self::FKP => Ok(dirval!(PaymentCurrency = FKP)),
Self::GBP => Ok(dirval!(PaymentCurrency = GBP)),
Self::GEL => Ok(dirval!(PaymentCurrency = GEL)),
Self::GHS => Ok(dirval!(PaymentCurrency = GHS)),
Self::GIP => Ok(dirval!(PaymentCurrency = GIP)),
Self::GMD => Ok(dirval!(PaymentCurrency = GMD)),
Self::GNF => Ok(dirval!(PaymentCurrency = GNF)),
Self::GTQ => Ok(dirval!(PaymentCurrency = GTQ)),
Self::GYD => Ok(dirval!(PaymentCurrency = GYD)),
Self::HKD => Ok(dirval!(PaymentCurrency = HKD)),
Self::HNL => Ok(dirval!(PaymentCurrency = HNL)),
Self::HRK => Ok(dirval!(PaymentCurrency = HRK)),
Self::HTG => Ok(dirval!(PaymentCurrency = HTG)),
Self::HUF => Ok(dirval!(PaymentCurrency = HUF)),
Self::IDR => Ok(dirval!(PaymentCurrency = IDR)),
Self::ILS => Ok(dirval!(PaymentCurrency = ILS)),
Self::INR => Ok(dirval!(PaymentCurrency = INR)),
Self::IQD => Ok(dirval!(PaymentCurrency = IQD)),
Self::IRR => Ok(dirval!(PaymentCurrency = IRR)),
Self::ISK => Ok(dirval!(PaymentCurrency = ISK)),
Self::JMD => Ok(dirval!(PaymentCurrency = JMD)),
Self::JOD => Ok(dirval!(PaymentCurrency = JOD)),
Self::JPY => Ok(dirval!(PaymentCurrency = JPY)),
Self::KES => Ok(dirval!(PaymentCurrency = KES)),
Self::KGS => Ok(dirval!(PaymentCurrency = KGS)),
Self::KHR => Ok(dirval!(PaymentCurrency = KHR)),
Self::KMF => Ok(dirval!(PaymentCurrency = KMF)),
Self::KPW => Ok(dirval!(PaymentCurrency = KPW)),
Self::KRW => Ok(dirval!(PaymentCurrency = KRW)),
Self::KWD => Ok(dirval!(PaymentCurrency = KWD)),
Self::KYD => Ok(dirval!(PaymentCurrency = KYD)),
Self::KZT => Ok(dirval!(PaymentCurrency = KZT)),
Self::LAK => Ok(dirval!(PaymentCurrency = LAK)),
Self::LBP => Ok(dirval!(PaymentCurrency = LBP)),
Self::LKR => Ok(dirval!(PaymentCurrency = LKR)),
Self::LRD => Ok(dirval!(PaymentCurrency = LRD)),
Self::LSL => Ok(dirval!(PaymentCurrency = LSL)),
Self::LYD => Ok(dirval!(PaymentCurrency = LYD)),
Self::MAD => Ok(dirval!(PaymentCurrency = MAD)),
Self::MDL => Ok(dirval!(PaymentCurrency = MDL)),
Self::MGA => Ok(dirval!(PaymentCurrency = MGA)),
Self::MKD => Ok(dirval!(PaymentCurrency = MKD)),
Self::MMK => Ok(dirval!(PaymentCurrency = MMK)),
Self::MNT => Ok(dirval!(PaymentCurrency = MNT)),
Self::MOP => Ok(dirval!(PaymentCurrency = MOP)),
Self::MRU => Ok(dirval!(PaymentCurrency = MRU)),
Self::MUR => Ok(dirval!(PaymentCurrency = MUR)),
Self::MVR => Ok(dirval!(PaymentCurrency = MVR)),
Self::MWK => Ok(dirval!(PaymentCurrency = MWK)),
Self::MXN => Ok(dirval!(PaymentCurrency = MXN)),
Self::MYR => Ok(dirval!(PaymentCurrency = MYR)),
Self::MZN => Ok(dirval!(PaymentCurrency = MZN)),
Self::NAD => Ok(dirval!(PaymentCurrency = NAD)),
Self::NGN => Ok(dirval!(PaymentCurrency = NGN)),
Self::NIO => Ok(dirval!(PaymentCurrency = NIO)),
Self::NOK => Ok(dirval!(PaymentCurrency = NOK)),
Self::NPR => Ok(dirval!(PaymentCurrency = NPR)),
Self::NZD => Ok(dirval!(PaymentCurrency = NZD)),
Self::OMR => Ok(dirval!(PaymentCurrency = OMR)),
Self::PAB => Ok(dirval!(PaymentCurrency = PAB)),
Self::PEN => Ok(dirval!(PaymentCurrency = PEN)),
Self::PGK => Ok(dirval!(PaymentCurrency = PGK)),
Self::PHP => Ok(dirval!(PaymentCurrency = PHP)),
Self::PKR => Ok(dirval!(PaymentCurrency = PKR)),
Self::PLN => Ok(dirval!(PaymentCurrency = PLN)),
Self::PYG => Ok(dirval!(PaymentCurrency = PYG)),
Self::QAR => Ok(dirval!(PaymentCurrency = QAR)),
Self::RON => Ok(dirval!(PaymentCurrency = RON)),
Self::RSD => Ok(dirval!(PaymentCurrency = RSD)),
Self::RUB => Ok(dirval!(PaymentCurrency = RUB)),
Self::RWF => Ok(dirval!(PaymentCurrency = RWF)),
Self::SAR => Ok(dirval!(PaymentCurrency = SAR)),
Self::SBD => Ok(dirval!(PaymentCurrency = SBD)),
Self::SCR => Ok(dirval!(PaymentCurrency = SCR)),
Self::SDG => Ok(dirval!(PaymentCurrency = SDG)),
Self::SEK => Ok(dirval!(PaymentCurrency = SEK)),
Self::SGD => Ok(dirval!(PaymentCurrency = SGD)),
Self::SHP => Ok(dirval!(PaymentCurrency = SHP)),
Self::SLE => Ok(dirval!(PaymentCurrency = SLE)),
Self::SLL => Ok(dirval!(PaymentCurrency = SLL)),
Self::SOS => Ok(dirval!(PaymentCurrency = SOS)),
Self::SRD => Ok(dirval!(PaymentCurrency = SRD)),
Self::SSP => Ok(dirval!(PaymentCurrency = SSP)),
Self::STD => Ok(dirval!(PaymentCurrency = STD)),
Self::STN => Ok(dirval!(PaymentCurrency = STN)),
Self::SVC => Ok(dirval!(PaymentCurrency = SVC)),
Self::SYP => Ok(dirval!(PaymentCurrency = SYP)),
Self::SZL => Ok(dirval!(PaymentCurrency = SZL)),
Self::THB => Ok(dirval!(PaymentCurrency = THB)),
Self::TJS => Ok(dirval!(PaymentCurrency = TJS)),
Self::TMT => Ok(dirval!(PaymentCurrency = TMT)),
Self::TND => Ok(dirval!(PaymentCurrency = TND)),
Self::TOP => Ok(dirval!(PaymentCurrency = TOP)),
Self::TRY => Ok(dirval!(PaymentCurrency = TRY)),
Self::TTD => Ok(dirval!(PaymentCurrency = TTD)),
Self::TWD => Ok(dirval!(PaymentCurrency = TWD)),
Self::TZS => Ok(dirval!(PaymentCurrency = TZS)),
Self::UAH => Ok(dirval!(PaymentCurrency = UAH)),
Self::UGX => Ok(dirval!(PaymentCurrency = UGX)),
Self::USD => Ok(dirval!(PaymentCurrency = USD)),
Self::UYU => Ok(dirval!(PaymentCurrency = UYU)),
Self::UZS => Ok(dirval!(PaymentCurrency = UZS)),
Self::VES => Ok(dirval!(PaymentCurrency = VES)),
Self::VND => Ok(dirval!(PaymentCurrency = VND)),
Self::VUV => Ok(dirval!(PaymentCurrency = VUV)),
Self::WST => Ok(dirval!(PaymentCurrency = WST)),
Self::XAF => Ok(dirval!(PaymentCurrency = XAF)),
Self::XCD => Ok(dirval!(PaymentCurrency = XCD)),
Self::XOF => Ok(dirval!(PaymentCurrency = XOF)),
Self::XPF => Ok(dirval!(PaymentCurrency = XPF)),
Self::YER => Ok(dirval!(PaymentCurrency = YER)),
Self::ZAR => Ok(dirval!(PaymentCurrency = ZAR)),
Self::ZMW => Ok(dirval!(PaymentCurrency = ZMW)),
Self::ZWL => Ok(dirval!(PaymentCurrency = ZWL)),
}
}
}
pub fn get_dir_country_dir_value(c: api_enums::Country) -> dir::enums::Country {
match c {
api_enums::Country::Afghanistan => dir::enums::Country::Afghanistan,
api_enums::Country::AlandIslands => dir::enums::Country::AlandIslands,
api_enums::Country::Albania => dir::enums::Country::Albania,
api_enums::Country::Algeria => dir::enums::Country::Algeria,
api_enums::Country::AmericanSamoa => dir::enums::Country::AmericanSamoa,
api_enums::Country::Andorra => dir::enums::Country::Andorra,
api_enums::Country::Angola => dir::enums::Country::Angola,
api_enums::Country::Anguilla => dir::enums::Country::Anguilla,
api_enums::Country::Antarctica => dir::enums::Country::Antarctica,
api_enums::Country::AntiguaAndBarbuda => dir::enums::Country::AntiguaAndBarbuda,
api_enums::Country::Argentina => dir::enums::Country::Argentina,
api_enums::Country::Armenia => dir::enums::Country::Armenia,
api_enums::Country::Aruba => dir::enums::Country::Aruba,
api_enums::Country::Australia => dir::enums::Country::Australia,
api_enums::Country::Austria => dir::enums::Country::Austria,
api_enums::Country::Azerbaijan => dir::enums::Country::Azerbaijan,
api_enums::Country::Bahamas => dir::enums::Country::Bahamas,
api_enums::Country::Bahrain => dir::enums::Country::Bahrain,
api_enums::Country::Bangladesh => dir::enums::Country::Bangladesh,
api_enums::Country::Barbados => dir::enums::Country::Barbados,
api_enums::Country::Belarus => dir::enums::Country::Belarus,
api_enums::Country::Belgium => dir::enums::Country::Belgium,
api_enums::Country::Belize => dir::enums::Country::Belize,
api_enums::Country::Benin => dir::enums::Country::Benin,
api_enums::Country::Bermuda => dir::enums::Country::Bermuda,
api_enums::Country::Bhutan => dir::enums::Country::Bhutan,
api_enums::Country::BoliviaPlurinationalState => {
dir::enums::Country::BoliviaPlurinationalState
}
api_enums::Country::BonaireSintEustatiusAndSaba => {
dir::enums::Country::BonaireSintEustatiusAndSaba
}
api_enums::Country::BosniaAndHerzegovina => dir::enums::Country::BosniaAndHerzegovina,
api_enums::Country::Botswana => dir::enums::Country::Botswana,
api_enums::Country::BouvetIsland => dir::enums::Country::BouvetIsland,
api_enums::Country::Brazil => dir::enums::Country::Brazil,
api_enums::Country::BritishIndianOceanTerritory => {
dir::enums::Country::BritishIndianOceanTerritory
}
api_enums::Country::BruneiDarussalam => dir::enums::Country::BruneiDarussalam,
api_enums::Country::Bulgaria => dir::enums::Country::Bulgaria,
api_enums::Country::BurkinaFaso => dir::enums::Country::BurkinaFaso,
api_enums::Country::Burundi => dir::enums::Country::Burundi,
api_enums::Country::CaboVerde => dir::enums::Country::CaboVerde,
api_enums::Country::Cambodia => dir::enums::Country::Cambodia,
api_enums::Country::Cameroon => dir::enums::Country::Cameroon,
api_enums::Country::Canada => dir::enums::Country::Canada,
api_enums::Country::CaymanIslands => dir::enums::Country::CaymanIslands,
api_enums::Country::CentralAfricanRepublic => dir::enums::Country::CentralAfricanRepublic,
api_enums::Country::Chad => dir::enums::Country::Chad,
api_enums::Country::Chile => dir::enums::Country::Chile,
api_enums::Country::China => dir::enums::Country::China,
api_enums::Country::ChristmasIsland => dir::enums::Country::ChristmasIsland,
api_enums::Country::CocosKeelingIslands => dir::enums::Country::CocosKeelingIslands,
api_enums::Country::Colombia => dir::enums::Country::Colombia,
api_enums::Country::Comoros => dir::enums::Country::Comoros,
api_enums::Country::Congo => dir::enums::Country::Congo,
api_enums::Country::CongoDemocraticRepublic => dir::enums::Country::CongoDemocraticRepublic,
api_enums::Country::CookIslands => dir::enums::Country::CookIslands,
api_enums::Country::CostaRica => dir::enums::Country::CostaRica,
api_enums::Country::CotedIvoire => dir::enums::Country::CotedIvoire,
api_enums::Country::Croatia => dir::enums::Country::Croatia,
api_enums::Country::Cuba => dir::enums::Country::Cuba,
api_enums::Country::Curacao => dir::enums::Country::Curacao,
api_enums::Country::Cyprus => dir::enums::Country::Cyprus,
api_enums::Country::Czechia => dir::enums::Country::Czechia,
api_enums::Country::Denmark => dir::enums::Country::Denmark,
api_enums::Country::Djibouti => dir::enums::Country::Djibouti,
api_enums::Country::Dominica => dir::enums::Country::Dominica,
api_enums::Country::DominicanRepublic => dir::enums::Country::DominicanRepublic,
api_enums::Country::Ecuador => dir::enums::Country::Ecuador,
api_enums::Country::Egypt => dir::enums::Country::Egypt,
api_enums::Country::ElSalvador => dir::enums::Country::ElSalvador,
api_enums::Country::EquatorialGuinea => dir::enums::Country::EquatorialGuinea,
api_enums::Country::Eritrea => dir::enums::Country::Eritrea,
api_enums::Country::Estonia => dir::enums::Country::Estonia,
api_enums::Country::Ethiopia => dir::enums::Country::Ethiopia,
api_enums::Country::FalklandIslandsMalvinas => dir::enums::Country::FalklandIslandsMalvinas,
api_enums::Country::FaroeIslands => dir::enums::Country::FaroeIslands,
api_enums::Country::Fiji => dir::enums::Country::Fiji,
api_enums::Country::Finland => dir::enums::Country::Finland,
api_enums::Country::France => dir::enums::Country::France,
api_enums::Country::FrenchGuiana => dir::enums::Country::FrenchGuiana,
api_enums::Country::FrenchPolynesia => dir::enums::Country::FrenchPolynesia,
api_enums::Country::FrenchSouthernTerritories => {
dir::enums::Country::FrenchSouthernTerritories
}
api_enums::Country::Gabon => dir::enums::Country::Gabon,
api_enums::Country::Gambia => dir::enums::Country::Gambia,
api_enums::Country::Georgia => dir::enums::Country::Georgia,
api_enums::Country::Germany => dir::enums::Country::Germany,
api_enums::Country::Ghana => dir::enums::Country::Ghana,
api_enums::Country::Gibraltar => dir::enums::Country::Gibraltar,
api_enums::Country::Greece => dir::enums::Country::Greece,
api_enums::Country::Greenland => dir::enums::Country::Greenland,
api_enums::Country::Grenada => dir::enums::Country::Grenada,
api_enums::Country::Guadeloupe => dir::enums::Country::Guadeloupe,
api_enums::Country::Guam => dir::enums::Country::Guam,
api_enums::Country::Guatemala => dir::enums::Country::Guatemala,
api_enums::Country::Guernsey => dir::enums::Country::Guernsey,
api_enums::Country::Guinea => dir::enums::Country::Guinea,
api_enums::Country::GuineaBissau => dir::enums::Country::GuineaBissau,
api_enums::Country::Guyana => dir::enums::Country::Guyana,
api_enums::Country::Haiti => dir::enums::Country::Haiti,
api_enums::Country::HeardIslandAndMcDonaldIslands => {
dir::enums::Country::HeardIslandAndMcDonaldIslands
}
api_enums::Country::HolySee => dir::enums::Country::HolySee,
api_enums::Country::Honduras => dir::enums::Country::Honduras,
api_enums::Country::HongKong => dir::enums::Country::HongKong,
api_enums::Country::Hungary => dir::enums::Country::Hungary,
api_enums::Country::Iceland => dir::enums::Country::Iceland,
api_enums::Country::India => dir::enums::Country::India,
api_enums::Country::Indonesia => dir::enums::Country::Indonesia,
api_enums::Country::IranIslamicRepublic => dir::enums::Country::IranIslamicRepublic,
api_enums::Country::Iraq => dir::enums::Country::Iraq,
api_enums::Country::Ireland => dir::enums::Country::Ireland,
api_enums::Country::IsleOfMan => dir::enums::Country::IsleOfMan,
api_enums::Country::Israel => dir::enums::Country::Israel,
api_enums::Country::Italy => dir::enums::Country::Italy,
api_enums::Country::Jamaica => dir::enums::Country::Jamaica,
api_enums::Country::Japan => dir::enums::Country::Japan,
api_enums::Country::Jersey => dir::enums::Country::Jersey,
api_enums::Country::Jordan => dir::enums::Country::Jordan,
api_enums::Country::Kazakhstan => dir::enums::Country::Kazakhstan,
api_enums::Country::Kenya => dir::enums::Country::Kenya,
api_enums::Country::Kiribati => dir::enums::Country::Kiribati,
api_enums::Country::KoreaDemocraticPeoplesRepublic => {
dir::enums::Country::KoreaDemocraticPeoplesRepublic
}
api_enums::Country::KoreaRepublic => dir::enums::Country::KoreaRepublic,
api_enums::Country::Kuwait => dir::enums::Country::Kuwait,
api_enums::Country::Kyrgyzstan => dir::enums::Country::Kyrgyzstan,
api_enums::Country::LaoPeoplesDemocraticRepublic => {
dir::enums::Country::LaoPeoplesDemocraticRepublic
}
api_enums::Country::Latvia => dir::enums::Country::Latvia,
api_enums::Country::Lebanon => dir::enums::Country::Lebanon,
api_enums::Country::Lesotho => dir::enums::Country::Lesotho,
api_enums::Country::Liberia => dir::enums::Country::Liberia,
api_enums::Country::Libya => dir::enums::Country::Libya,
api_enums::Country::Liechtenstein => dir::enums::Country::Liechtenstein,
api_enums::Country::Lithuania => dir::enums::Country::Lithuania,
api_enums::Country::Luxembourg => dir::enums::Country::Luxembourg,
api_enums::Country::Macao => dir::enums::Country::Macao,
api_enums::Country::MacedoniaTheFormerYugoslavRepublic => {
dir::enums::Country::MacedoniaTheFormerYugoslavRepublic
}
api_enums::Country::Madagascar => dir::enums::Country::Madagascar,
api_enums::Country::Malawi => dir::enums::Country::Malawi,
api_enums::Country::Malaysia => dir::enums::Country::Malaysia,
api_enums::Country::Maldives => dir::enums::Country::Maldives,
api_enums::Country::Mali => dir::enums::Country::Mali,
api_enums::Country::Malta => dir::enums::Country::Malta,
api_enums::Country::MarshallIslands => dir::enums::Country::MarshallIslands,
api_enums::Country::Martinique => dir::enums::Country::Martinique,
api_enums::Country::Mauritania => dir::enums::Country::Mauritania,
api_enums::Country::Mauritius => dir::enums::Country::Mauritius,
api_enums::Country::Mayotte => dir::enums::Country::Mayotte,
api_enums::Country::Mexico => dir::enums::Country::Mexico,
api_enums::Country::MicronesiaFederatedStates => {
dir::enums::Country::MicronesiaFederatedStates
}
api_enums::Country::MoldovaRepublic => dir::enums::Country::MoldovaRepublic,
api_enums::Country::Monaco => dir::enums::Country::Monaco,
api_enums::Country::Mongolia => dir::enums::Country::Mongolia,
api_enums::Country::Montenegro => dir::enums::Country::Montenegro,
api_enums::Country::Montserrat => dir::enums::Country::Montserrat,
api_enums::Country::Morocco => dir::enums::Country::Morocco,
api_enums::Country::Mozambique => dir::enums::Country::Mozambique,
api_enums::Country::Myanmar => dir::enums::Country::Myanmar,
api_enums::Country::Namibia => dir::enums::Country::Namibia,
api_enums::Country::Nauru => dir::enums::Country::Nauru,
api_enums::Country::Nepal => dir::enums::Country::Nepal,
api_enums::Country::Netherlands => dir::enums::Country::Netherlands,
api_enums::Country::NewCaledonia => dir::enums::Country::NewCaledonia,
api_enums::Country::NewZealand => dir::enums::Country::NewZealand,
api_enums::Country::Nicaragua => dir::enums::Country::Nicaragua,
api_enums::Country::Niger => dir::enums::Country::Niger,
api_enums::Country::Nigeria => dir::enums::Country::Nigeria,
api_enums::Country::Niue => dir::enums::Country::Niue,
api_enums::Country::NorfolkIsland => dir::enums::Country::NorfolkIsland,
api_enums::Country::NorthernMarianaIslands => dir::enums::Country::NorthernMarianaIslands,
api_enums::Country::Norway => dir::enums::Country::Norway,
api_enums::Country::Oman => dir::enums::Country::Oman,
api_enums::Country::Pakistan => dir::enums::Country::Pakistan,
api_enums::Country::Palau => dir::enums::Country::Palau,
api_enums::Country::PalestineState => dir::enums::Country::PalestineState,
api_enums::Country::Panama => dir::enums::Country::Panama,
api_enums::Country::PapuaNewGuinea => dir::enums::Country::PapuaNewGuinea,
api_enums::Country::Paraguay => dir::enums::Country::Paraguay,
api_enums::Country::Peru => dir::enums::Country::Peru,
api_enums::Country::Philippines => dir::enums::Country::Philippines,
api_enums::Country::Pitcairn => dir::enums::Country::Pitcairn,
api_enums::Country::Poland => dir::enums::Country::Poland,
api_enums::Country::Portugal => dir::enums::Country::Portugal,
api_enums::Country::PuertoRico => dir::enums::Country::PuertoRico,
api_enums::Country::Qatar => dir::enums::Country::Qatar,
api_enums::Country::Reunion => dir::enums::Country::Reunion,
api_enums::Country::Romania => dir::enums::Country::Romania,
api_enums::Country::RussianFederation => dir::enums::Country::RussianFederation,
api_enums::Country::Rwanda => dir::enums::Country::Rwanda,
api_enums::Country::SaintBarthelemy => dir::enums::Country::SaintBarthelemy,
api_enums::Country::SaintHelenaAscensionAndTristandaCunha => {
dir::enums::Country::SaintHelenaAscensionAndTristandaCunha
}
api_enums::Country::SaintKittsAndNevis => dir::enums::Country::SaintKittsAndNevis,
api_enums::Country::SaintLucia => dir::enums::Country::SaintLucia,
api_enums::Country::SaintMartinFrenchpart => dir::enums::Country::SaintMartinFrenchpart,
api_enums::Country::SaintPierreAndMiquelon => dir::enums::Country::SaintPierreAndMiquelon,
api_enums::Country::SaintVincentAndTheGrenadines => {
dir::enums::Country::SaintVincentAndTheGrenadines
}
api_enums::Country::Samoa => dir::enums::Country::Samoa,
api_enums::Country::SanMarino => dir::enums::Country::SanMarino,
api_enums::Country::SaoTomeAndPrincipe => dir::enums::Country::SaoTomeAndPrincipe,
api_enums::Country::SaudiArabia => dir::enums::Country::SaudiArabia,
api_enums::Country::Senegal => dir::enums::Country::Senegal,
api_enums::Country::Serbia => dir::enums::Country::Serbia,
api_enums::Country::Seychelles => dir::enums::Country::Seychelles,
api_enums::Country::SierraLeone => dir::enums::Country::SierraLeone,
api_enums::Country::Singapore => dir::enums::Country::Singapore,
api_enums::Country::SintMaartenDutchpart => dir::enums::Country::SintMaartenDutchpart,
api_enums::Country::Slovakia => dir::enums::Country::Slovakia,
api_enums::Country::Slovenia => dir::enums::Country::Slovenia,
api_enums::Country::SolomonIslands => dir::enums::Country::SolomonIslands,
api_enums::Country::Somalia => dir::enums::Country::Somalia,
api_enums::Country::SouthAfrica => dir::enums::Country::SouthAfrica,
api_enums::Country::SouthGeorgiaAndTheSouthSandwichIslands => {
dir::enums::Country::SouthGeorgiaAndTheSouthSandwichIslands
}
api_enums::Country::SouthSudan => dir::enums::Country::SouthSudan,
api_enums::Country::Spain => dir::enums::Country::Spain,
api_enums::Country::SriLanka => dir::enums::Country::SriLanka,
api_enums::Country::Sudan => dir::enums::Country::Sudan,
api_enums::Country::Suriname => dir::enums::Country::Suriname,
api_enums::Country::SvalbardAndJanMayen => dir::enums::Country::SvalbardAndJanMayen,
api_enums::Country::Swaziland => dir::enums::Country::Swaziland,
api_enums::Country::Sweden => dir::enums::Country::Sweden,
api_enums::Country::Switzerland => dir::enums::Country::Switzerland,
api_enums::Country::SyrianArabRepublic => dir::enums::Country::SyrianArabRepublic,
api_enums::Country::TaiwanProvinceOfChina => dir::enums::Country::TaiwanProvinceOfChina,
api_enums::Country::Tajikistan => dir::enums::Country::Tajikistan,
api_enums::Country::TanzaniaUnitedRepublic => dir::enums::Country::TanzaniaUnitedRepublic,
api_enums::Country::Thailand => dir::enums::Country::Thailand,
api_enums::Country::TimorLeste => dir::enums::Country::TimorLeste,
api_enums::Country::Togo => dir::enums::Country::Togo,
api_enums::Country::Tokelau => dir::enums::Country::Tokelau,
api_enums::Country::Tonga => dir::enums::Country::Tonga,
api_enums::Country::TrinidadAndTobago => dir::enums::Country::TrinidadAndTobago,
api_enums::Country::Tunisia => dir::enums::Country::Tunisia,
api_enums::Country::Turkey => dir::enums::Country::Turkey,
api_enums::Country::Turkmenistan => dir::enums::Country::Turkmenistan,
api_enums::Country::TurksAndCaicosIslands => dir::enums::Country::TurksAndCaicosIslands,
api_enums::Country::Tuvalu => dir::enums::Country::Tuvalu,
api_enums::Country::Uganda => dir::enums::Country::Uganda,
api_enums::Country::Ukraine => dir::enums::Country::Ukraine,
api_enums::Country::UnitedArabEmirates => dir::enums::Country::UnitedArabEmirates,
api_enums::Country::UnitedKingdomOfGreatBritainAndNorthernIreland => {
dir::enums::Country::UnitedKingdomOfGreatBritainAndNorthernIreland
}
api_enums::Country::UnitedStatesOfAmerica => dir::enums::Country::UnitedStatesOfAmerica,
api_enums::Country::UnitedStatesMinorOutlyingIslands => {
dir::enums::Country::UnitedStatesMinorOutlyingIslands
}
api_enums::Country::Uruguay => dir::enums::Country::Uruguay,
api_enums::Country::Uzbekistan => dir::enums::Country::Uzbekistan,
api_enums::Country::Vanuatu => dir::enums::Country::Vanuatu,
api_enums::Country::VenezuelaBolivarianRepublic => {
dir::enums::Country::VenezuelaBolivarianRepublic
}
api_enums::Country::Vietnam => dir::enums::Country::Vietnam,
api_enums::Country::VirginIslandsBritish => dir::enums::Country::VirginIslandsBritish,
api_enums::Country::VirginIslandsUS => dir::enums::Country::VirginIslandsUS,
api_enums::Country::WallisAndFutuna => dir::enums::Country::WallisAndFutuna,
api_enums::Country::WesternSahara => dir::enums::Country::WesternSahara,
api_enums::Country::Yemen => dir::enums::Country::Yemen,
api_enums::Country::Zambia => dir::enums::Country::Zambia,
api_enums::Country::Zimbabwe => dir::enums::Country::Zimbabwe,
}
}
pub fn business_country_to_dir_value(c: api_enums::Country) -> dir::DirValue {
dir::DirValue::BusinessCountry(get_dir_country_dir_value(c))
}
pub fn billing_country_to_dir_value(c: api_enums::Country) -> dir::DirValue {
dir::DirValue::BillingCountry(get_dir_country_dir_value(c))
}
</file>
|
{
"crate": "kgraph_utils",
"file": "crates/kgraph_utils/src/transformers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 12758
}
|
large_file_-5166369294655725811
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: kgraph_utils
File: crates/kgraph_utils/src/mca.rs
</path>
<file>
#[cfg(feature = "v1")]
use std::str::FromStr;
#[cfg(feature = "v1")]
use api_models::payment_methods::RequestPaymentMethodTypes;
use api_models::{admin as admin_api, enums as api_enums, refunds::MinorUnit};
use euclid::{
dirval,
frontend::{ast, dir},
types::{NumValue, NumValueRefinement},
};
use hyperswitch_constraint_graph as cgraph;
use strum::IntoEnumIterator;
use crate::{error::KgraphError, transformers::IntoDirValue, types as kgraph_types};
pub const DOMAIN_IDENTIFIER: &str = "payment_methods_enabled_for_merchantconnectoraccount";
// #[cfg(feature = "v1")]
fn get_dir_value_payment_method(
from: api_enums::PaymentMethodType,
) -> Result<dir::DirValue, KgraphError> {
match from {
api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)),
api_enums::PaymentMethodType::Skrill => Ok(dirval!(WalletType = Skrill)),
api_enums::PaymentMethodType::Paysera => Ok(dirval!(WalletType = Paysera)),
api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)),
api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)),
#[cfg(feature = "v2")]
api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)),
api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)),
api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)),
api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)),
api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)),
api_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)),
api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)),
api_enums::PaymentMethodType::Flexiti => Ok(dirval!(PayLaterType = Flexiti)),
api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)),
api_enums::PaymentMethodType::AfterpayClearpay => {
Ok(dirval!(PayLaterType = AfterpayClearpay))
}
api_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)),
api_enums::PaymentMethodType::Bluecode => Ok(dirval!(WalletType = Bluecode)),
api_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)),
api_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)),
api_enums::PaymentMethodType::CryptoCurrency => Ok(dirval!(CryptoType = CryptoCurrency)),
api_enums::PaymentMethodType::Ach => Ok(dirval!(BankDebitType = Ach)),
api_enums::PaymentMethodType::Bacs => Ok(dirval!(BankDebitType = Bacs)),
api_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)),
api_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)),
api_enums::PaymentMethodType::SepaGuarenteedDebit => {
Ok(dirval!(BankDebitType = SepaGuarenteedDebit))
}
api_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)),
api_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)),
api_enums::PaymentMethodType::BancontactCard => {
Ok(dirval!(BankRedirectType = BancontactCard))
}
api_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)),
api_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)),
api_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)),
api_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)),
api_enums::PaymentMethodType::Multibanco => Ok(dirval!(BankTransferType = Multibanco)),
api_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)),
api_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)),
api_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)),
api_enums::PaymentMethodType::OnlineBankingCzechRepublic => {
Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic))
}
api_enums::PaymentMethodType::OnlineBankingFinland => {
Ok(dirval!(BankRedirectType = OnlineBankingFinland))
}
api_enums::PaymentMethodType::OnlineBankingPoland => {
Ok(dirval!(BankRedirectType = OnlineBankingPoland))
}
api_enums::PaymentMethodType::OnlineBankingSlovakia => {
Ok(dirval!(BankRedirectType = OnlineBankingSlovakia))
}
api_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)),
api_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)),
api_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)),
api_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)),
api_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)),
api_enums::PaymentMethodType::Przelewy24 => Ok(dirval!(BankRedirectType = Przelewy24)),
api_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)),
api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)),
api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)),
api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)),
api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)),
api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)),
api_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)),
api_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)),
api_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)),
api_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)),
api_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)),
api_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)),
api_enums::PaymentMethodType::OnlineBankingFpx => {
Ok(dirval!(BankRedirectType = OnlineBankingFpx))
}
api_enums::PaymentMethodType::OnlineBankingThailand => {
Ok(dirval!(BankRedirectType = OnlineBankingThailand))
}
api_enums::PaymentMethodType::LocalBankRedirect => {
Ok(dirval!(BankRedirectType = LocalBankRedirect))
}
api_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)),
api_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)),
api_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)),
api_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)),
api_enums::PaymentMethodType::PagoEfectivo => Ok(dirval!(VoucherType = PagoEfectivo)),
api_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)),
api_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)),
api_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)),
api_enums::PaymentMethodType::BcaBankTransfer => {
Ok(dirval!(BankTransferType = BcaBankTransfer))
}
api_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)),
api_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)),
api_enums::PaymentMethodType::Breadpay => Ok(dirval!(PayLaterType = Breadpay)),
api_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)),
api_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)),
api_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)),
api_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)),
api_enums::PaymentMethodType::LocalBankTransfer => {
Ok(dirval!(BankTransferType = LocalBankTransfer))
}
api_enums::PaymentMethodType::InstantBankTransfer => {
Ok(dirval!(BankTransferType = InstantBankTransfer))
}
api_enums::PaymentMethodType::InstantBankTransferFinland => {
Ok(dirval!(BankTransferType = InstantBankTransferFinland))
}
api_enums::PaymentMethodType::InstantBankTransferPoland => {
Ok(dirval!(BankTransferType = InstantBankTransferPoland))
}
api_enums::PaymentMethodType::SepaBankTransfer => {
Ok(dirval!(BankTransferType = SepaBankTransfer))
}
api_enums::PaymentMethodType::PermataBankTransfer => {
Ok(dirval!(BankTransferType = PermataBankTransfer))
}
api_enums::PaymentMethodType::IndonesianBankTransfer => {
Ok(dirval!(BankTransferType = IndonesianBankTransfer))
}
api_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)),
api_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)),
api_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)),
api_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)),
api_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)),
api_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)),
api_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)),
api_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)),
api_enums::PaymentMethodType::BhnCardNetwork => Ok(dirval!(GiftCardType = BhnCardNetwork)),
api_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)),
api_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)),
api_enums::PaymentMethodType::OpenBankingUk => {
Ok(dirval!(BankRedirectType = OpenBankingUk))
}
api_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)),
api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)),
api_enums::PaymentMethodType::CardRedirect => Ok(dirval!(CardRedirectType = CardRedirect)),
api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)),
api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)),
api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
api_enums::PaymentMethodType::UpiQr => Ok(dirval!(UpiType = UpiQr)),
api_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)),
api_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)),
api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)),
api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)),
api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)),
api_enums::PaymentMethodType::OpenBankingPIS => {
Ok(dirval!(OpenBankingType = OpenBankingPIS))
}
api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)),
api_enums::PaymentMethodType::DirectCarrierBilling => {
Ok(dirval!(MobilePaymentType = DirectCarrierBilling))
}
api_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)),
}
}
#[cfg(feature = "v2")]
fn compile_request_pm_types(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
pm_types: common_types::payment_methods::RequestPaymentMethodTypes,
pm: api_enums::PaymentMethod,
) -> Result<cgraph::NodeId, KgraphError> {
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
let pmt_info = "PaymentMethodType";
let pmt_id = builder.make_value_node(
(pm_types.payment_method_subtype, pm)
.into_dir_value()
.map(Into::into)?,
Some(pmt_info),
None::<()>,
);
agg_nodes.push((
pmt_id,
cgraph::Relation::Positive,
match pm_types.payment_method_subtype {
api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
cgraph::Strength::Weak
}
_ => cgraph::Strength::Strong,
},
));
if let Some(card_networks) = pm_types.card_networks {
if !card_networks.is_empty() {
let dir_vals: Vec<dir::DirValue> = card_networks
.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()?;
let card_network_info = "Card Networks";
let card_network_id = builder
.make_in_aggregator(dir_vals, Some(card_network_info), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
card_network_id,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
));
}
}
let currencies_data = pm_types
.accepted_currencies
.and_then(|accepted_currencies| match accepted_currencies {
common_types::payment_methods::AcceptedCurrencies::EnableOnly(curr)
if !curr.is_empty() =>
{
Some((
curr.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()
.ok()?,
cgraph::Relation::Positive,
))
}
common_types::payment_methods::AcceptedCurrencies::DisableOnly(curr)
if !curr.is_empty() =>
{
Some((
curr.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()
.ok()?,
cgraph::Relation::Negative,
))
}
_ => None,
});
if let Some((currencies, relation)) = currencies_data {
let accepted_currencies_info = "Accepted Currencies";
let accepted_currencies_id = builder
.make_in_aggregator(currencies, Some(accepted_currencies_info), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((accepted_currencies_id, relation, cgraph::Strength::Strong));
}
let mut amount_nodes = Vec::with_capacity(2);
if let Some(min_amt) = pm_types.minimum_amount {
let num_val = NumValue {
number: min_amt,
refinement: Some(NumValueRefinement::GreaterThanEqual),
};
let min_amt_info = "Minimum Amount";
let min_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(num_val).into(),
Some(min_amt_info),
None::<()>,
);
amount_nodes.push(min_amt_id);
}
if let Some(max_amt) = pm_types.maximum_amount {
let num_val = NumValue {
number: max_amt,
refinement: Some(NumValueRefinement::LessThanEqual),
};
let max_amt_info = "Maximum Amount";
let max_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(num_val).into(),
Some(max_amt_info),
None::<()>,
);
amount_nodes.push(max_amt_id);
}
if !amount_nodes.is_empty() {
let zero_num_val = NumValue {
number: MinorUnit::zero(),
refinement: None,
};
let zero_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(zero_num_val).into(),
Some("zero_amount"),
None::<()>,
);
let or_node_neighbor_id = if amount_nodes.len() == 1 {
amount_nodes
.first()
.copied()
.ok_or(KgraphError::IndexingError)?
} else {
let nodes = amount_nodes
.iter()
.copied()
.map(|node_id| {
(
node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
)
})
.collect::<Vec<_>>();
builder
.make_all_aggregator(
&nodes,
Some("amount_constraint_aggregator"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?
};
let any_aggregator = builder
.make_any_aggregator(
&[
(
zero_amt_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
(
or_node_neighbor_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
Some("zero_plus_limits_amount_aggregator"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
any_aggregator,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
let pmt_all_aggregator_info = "All Aggregator for PaymentMethodType";
builder
.make_all_aggregator(&agg_nodes, Some(pmt_all_aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)
}
#[cfg(feature = "v1")]
fn compile_request_pm_types(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
pm_types: RequestPaymentMethodTypes,
pm: api_enums::PaymentMethod,
) -> Result<cgraph::NodeId, KgraphError> {
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
let pmt_info = "PaymentMethodType";
let pmt_id = builder.make_value_node(
(pm_types.payment_method_type, pm)
.into_dir_value()
.map(Into::into)?,
Some(pmt_info),
None::<()>,
);
agg_nodes.push((
pmt_id,
cgraph::Relation::Positive,
match pm_types.payment_method_type {
api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
cgraph::Strength::Weak
}
_ => cgraph::Strength::Strong,
},
));
if let Some(card_networks) = pm_types.card_networks {
if !card_networks.is_empty() {
let dir_vals: Vec<dir::DirValue> = card_networks
.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()?;
let card_network_info = "Card Networks";
let card_network_id = builder
.make_in_aggregator(dir_vals, Some(card_network_info), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
card_network_id,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
));
}
}
let currencies_data = pm_types
.accepted_currencies
.and_then(|accepted_currencies| match accepted_currencies {
admin_api::AcceptedCurrencies::EnableOnly(curr) if !curr.is_empty() => Some((
curr.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()
.ok()?,
cgraph::Relation::Positive,
)),
admin_api::AcceptedCurrencies::DisableOnly(curr) if !curr.is_empty() => Some((
curr.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<_, _>>()
.ok()?,
cgraph::Relation::Negative,
)),
_ => None,
});
if let Some((currencies, relation)) = currencies_data {
let accepted_currencies_info = "Accepted Currencies";
let accepted_currencies_id = builder
.make_in_aggregator(currencies, Some(accepted_currencies_info), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((accepted_currencies_id, relation, cgraph::Strength::Strong));
}
let mut amount_nodes = Vec::with_capacity(2);
if let Some(min_amt) = pm_types.minimum_amount {
let num_val = NumValue {
number: min_amt,
refinement: Some(NumValueRefinement::GreaterThanEqual),
};
let min_amt_info = "Minimum Amount";
let min_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(num_val).into(),
Some(min_amt_info),
None::<()>,
);
amount_nodes.push(min_amt_id);
}
if let Some(max_amt) = pm_types.maximum_amount {
let num_val = NumValue {
number: max_amt,
refinement: Some(NumValueRefinement::LessThanEqual),
};
let max_amt_info = "Maximum Amount";
let max_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(num_val).into(),
Some(max_amt_info),
None::<()>,
);
amount_nodes.push(max_amt_id);
}
if !amount_nodes.is_empty() {
let zero_num_val = NumValue {
number: MinorUnit::zero(),
refinement: None,
};
let zero_amt_id = builder.make_value_node(
dir::DirValue::PaymentAmount(zero_num_val).into(),
Some("zero_amount"),
None::<()>,
);
let or_node_neighbor_id = if amount_nodes.len() == 1 {
amount_nodes
.first()
.copied()
.ok_or(KgraphError::IndexingError)?
} else {
let nodes = amount_nodes
.iter()
.copied()
.map(|node_id| {
(
node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
)
})
.collect::<Vec<_>>();
builder
.make_all_aggregator(
&nodes,
Some("amount_constraint_aggregator"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?
};
let any_aggregator = builder
.make_any_aggregator(
&[
(
zero_amt_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
(
or_node_neighbor_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
Some("zero_plus_limits_amount_aggregator"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
any_aggregator,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
let pmt_all_aggregator_info = "All Aggregator for PaymentMethodType";
builder
.make_all_aggregator(&agg_nodes, Some(pmt_all_aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)
}
#[cfg(feature = "v2")]
fn compile_payment_method_enabled(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
enabled: common_types::payment_methods::PaymentMethodsEnabled,
) -> Result<Option<cgraph::NodeId>, KgraphError> {
let agg_id = if !enabled
.payment_method_subtypes
.as_ref()
.map(|v| v.is_empty())
.unwrap_or(true)
{
let pm_info = "PaymentMethod";
let pm_id = builder.make_value_node(
enabled
.payment_method_type
.into_dir_value()
.map(Into::into)?,
Some(pm_info),
None::<()>,
);
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
if let Some(pm_types) = enabled.payment_method_subtypes {
for pm_type in pm_types {
let node_id =
compile_request_pm_types(builder, pm_type, enabled.payment_method_type)?;
agg_nodes.push((
node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
}
let any_aggregator_info = "Any aggregation for PaymentMethodsType";
let pm_type_agg_id = builder
.make_any_aggregator(&agg_nodes, Some(any_aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)?;
let all_aggregator_info = "All aggregation for PaymentMethod";
let enabled_pm_agg_id = builder
.make_all_aggregator(
&[
(pm_id, cgraph::Relation::Positive, cgraph::Strength::Strong),
(
pm_type_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
Some(all_aggregator_info),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
Some(enabled_pm_agg_id)
} else {
None
};
Ok(agg_id)
}
#[cfg(feature = "v1")]
fn compile_payment_method_enabled(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
enabled: admin_api::PaymentMethodsEnabled,
) -> Result<Option<cgraph::NodeId>, KgraphError> {
let agg_id = if !enabled
.payment_method_types
.as_ref()
.map(|v| v.is_empty())
.unwrap_or(true)
{
let pm_info = "PaymentMethod";
let pm_id = builder.make_value_node(
enabled.payment_method.into_dir_value().map(Into::into)?,
Some(pm_info),
None::<()>,
);
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
if let Some(pm_types) = enabled.payment_method_types {
for pm_type in pm_types {
let node_id = compile_request_pm_types(builder, pm_type, enabled.payment_method)?;
agg_nodes.push((
node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
}
let any_aggregator_info = "Any aggregation for PaymentMethodsType";
let pm_type_agg_id = builder
.make_any_aggregator(&agg_nodes, Some(any_aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)?;
let all_aggregator_info = "All aggregation for PaymentMethod";
let enabled_pm_agg_id = builder
.make_all_aggregator(
&[
(pm_id, cgraph::Relation::Positive, cgraph::Strength::Strong),
(
pm_type_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
Some(all_aggregator_info),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
Some(enabled_pm_agg_id)
} else {
None
};
Ok(agg_id)
}
macro_rules! collect_global_variants {
($parent_enum:ident) => {
&mut dir::enums::$parent_enum::iter()
.map(dir::DirValue::$parent_enum)
.collect::<Vec<_>>()
};
}
// #[cfg(feature = "v1")]
fn global_vec_pmt(
enabled_pmt: Vec<dir::DirValue>,
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
) -> Vec<cgraph::NodeId> {
let mut global_vector: Vec<dir::DirValue> = Vec::new();
global_vector.append(collect_global_variants!(PayLaterType));
global_vector.append(collect_global_variants!(WalletType));
global_vector.append(collect_global_variants!(BankRedirectType));
global_vector.append(collect_global_variants!(BankDebitType));
global_vector.append(collect_global_variants!(CryptoType));
global_vector.append(collect_global_variants!(RewardType));
global_vector.append(collect_global_variants!(RealTimePaymentType));
global_vector.append(collect_global_variants!(UpiType));
global_vector.append(collect_global_variants!(VoucherType));
global_vector.append(collect_global_variants!(GiftCardType));
global_vector.append(collect_global_variants!(BankTransferType));
global_vector.append(collect_global_variants!(CardRedirectType));
global_vector.append(collect_global_variants!(OpenBankingType));
global_vector.append(collect_global_variants!(MobilePaymentType));
global_vector.push(dir::DirValue::PaymentMethod(
dir::enums::PaymentMethod::Card,
));
let global_vector = global_vector
.into_iter()
.filter(|global_value| !enabled_pmt.contains(global_value))
.collect::<Vec<_>>();
global_vector
.into_iter()
.map(|dir_v| {
builder.make_value_node(
cgraph::NodeValue::Value(dir_v),
Some("Payment Method Type"),
None::<()>,
)
})
.collect::<Vec<_>>()
}
fn compile_graph_for_countries_and_currencies(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
config: &kgraph_types::CurrencyCountryFlowFilter,
payment_method_type_node: cgraph::NodeId,
) -> Result<cgraph::NodeId, KgraphError> {
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
agg_nodes.push((
payment_method_type_node,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
));
if let Some(country) = config.country.clone() {
let node_country = country
.into_iter()
.map(|country| dir::DirValue::BillingCountry(api_enums::Country::from_alpha2(country)))
.collect();
let country_agg = builder
.make_in_aggregator(node_country, Some("Configs for Country"), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
country_agg,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
))
}
if let Some(currency) = config.currency.clone() {
let node_currency = currency
.into_iter()
.map(IntoDirValue::into_dir_value)
.collect::<Result<Vec<_>, _>>()?;
let currency_agg = builder
.make_in_aggregator(node_currency, Some("Configs for Currency"), None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
currency_agg,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
))
}
if let Some(capture_method) = config
.not_available_flows
.and_then(|naf| naf.capture_method)
{
let make_capture_node = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(capture_method)),
Some("Configs for CaptureMethod"),
None::<()>,
);
agg_nodes.push((
make_capture_node,
cgraph::Relation::Negative,
cgraph::Strength::Normal,
))
}
builder
.make_all_aggregator(
&agg_nodes,
Some("Country & Currency Configs With Payment Method Type"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)
}
// #[cfg(feature = "v1")]
fn compile_config_graph(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
config: &kgraph_types::CountryCurrencyFilter,
connector: api_enums::RoutableConnectors,
) -> Result<cgraph::NodeId, KgraphError> {
let mut agg_node_id: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
let mut pmt_enabled: Vec<dir::DirValue> = Vec::new();
if let Some(pmt) = config
.connector_configs
.get(&connector)
.or(config.default_configs.as_ref())
.map(|inner| inner.0.clone())
{
for pm_filter_key in pmt {
match pm_filter_key {
(kgraph_types::PaymentMethodFilterKey::PaymentMethodType(pm), filter) => {
let dir_val_pm = get_dir_value_payment_method(pm)?;
let pm_node = if pm == api_enums::PaymentMethodType::Credit
|| pm == api_enums::PaymentMethodType::Debit
{
pmt_enabled
.push(dir::DirValue::PaymentMethod(api_enums::PaymentMethod::Card));
builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(
dir::enums::PaymentMethod::Card,
)),
Some("PaymentMethod"),
None::<()>,
)
} else {
pmt_enabled.push(dir_val_pm.clone());
builder.make_value_node(
cgraph::NodeValue::Value(dir_val_pm),
Some("PaymentMethodType"),
None::<()>,
)
};
let node_config =
compile_graph_for_countries_and_currencies(builder, &filter, pm_node)?;
agg_node_id.push((
node_config,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
));
}
(kgraph_types::PaymentMethodFilterKey::CardNetwork(cn), filter) => {
let dir_val_cn = cn.clone().into_dir_value()?;
pmt_enabled.push(dir_val_cn);
let cn_node = builder.make_value_node(
cn.clone().into_dir_value().map(Into::into)?,
Some("CardNetwork"),
None::<()>,
);
let node_config =
compile_graph_for_countries_and_currencies(builder, &filter, cn_node)?;
agg_node_id.push((
node_config,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
));
}
}
}
}
let global_vector_pmt: Vec<cgraph::NodeId> = global_vec_pmt(pmt_enabled, builder);
let any_agg_pmt: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = global_vector_pmt
.into_iter()
.map(|node| (node, cgraph::Relation::Positive, cgraph::Strength::Normal))
.collect::<Vec<_>>();
let any_agg_node = builder
.make_any_aggregator(
&any_agg_pmt,
Some("Any Aggregator For Payment Method Types"),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
agg_node_id.push((
any_agg_node,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
));
builder
.make_any_aggregator(&agg_node_id, Some("Configs"), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)
}
#[cfg(feature = "v2")]
fn compile_merchant_connector_graph(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
mca: admin_api::MerchantConnectorResponse,
config: &kgraph_types::CountryCurrencyFilter,
) -> Result<(), KgraphError> {
let connector = common_enums::RoutableConnectors::try_from(mca.connector_name)
.map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name))?;
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
if let Some(pms_enabled) = mca.payment_methods_enabled.clone() {
for pm_enabled in pms_enabled {
let maybe_pm_enabled_id = compile_payment_method_enabled(builder, pm_enabled)?;
if let Some(pm_enabled_id) = maybe_pm_enabled_id {
agg_nodes.push((
pm_enabled_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
}
}
let aggregator_info = "Available Payment methods for connector";
let pms_enabled_agg_id = builder
.make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)?;
let config_info = "Config for respective PaymentMethodType for the connector";
let config_enabled_agg_id = compile_config_graph(builder, config, connector)?;
let domain_level_node_id = builder
.make_all_aggregator(
&[
(
config_enabled_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
),
(
pms_enabled_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
),
],
Some(config_info),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
let connector_dir_val = dir::DirValue::Connector(Box::new(ast::ConnectorChoice { connector }));
let connector_info = "Connector";
let connector_node_id =
builder.make_value_node(connector_dir_val.into(), Some(connector_info), None::<()>);
builder
.make_edge(
domain_level_node_id,
connector_node_id,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.map_err(KgraphError::GraphConstructionError)?;
Ok(())
}
#[cfg(feature = "v1")]
fn compile_merchant_connector_graph(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
mca: admin_api::MerchantConnectorResponse,
config: &kgraph_types::CountryCurrencyFilter,
) -> Result<(), KgraphError> {
let connector = common_enums::RoutableConnectors::from_str(&mca.connector_name)
.map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name.clone()))?;
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
if let Some(pms_enabled) = mca.payment_methods_enabled.clone() {
for pm_enabled in pms_enabled {
let maybe_pm_enabled_id = compile_payment_method_enabled(builder, pm_enabled)?;
if let Some(pm_enabled_id) = maybe_pm_enabled_id {
agg_nodes.push((
pm_enabled_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
}
}
let aggregator_info = "Available Payment methods for connector";
let pms_enabled_agg_id = builder
.make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)?;
let config_info = "Config for respective PaymentMethodType for the connector";
let config_enabled_agg_id = compile_config_graph(builder, config, connector)?;
let domain_level_node_id = builder
.make_all_aggregator(
&[
(
config_enabled_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
),
(
pms_enabled_agg_id,
cgraph::Relation::Positive,
cgraph::Strength::Normal,
),
],
Some(config_info),
None::<()>,
None,
)
.map_err(KgraphError::GraphConstructionError)?;
let connector_dir_val = dir::DirValue::Connector(Box::new(ast::ConnectorChoice { connector }));
let connector_info = "Connector";
let connector_node_id =
builder.make_value_node(connector_dir_val.into(), Some(connector_info), None::<()>);
builder
.make_edge(
domain_level_node_id,
connector_node_id,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.map_err(KgraphError::GraphConstructionError)?;
Ok(())
}
// #[cfg(feature = "v1")]
pub fn make_mca_graph(
accts: Vec<admin_api::MerchantConnectorResponse>,
config: &kgraph_types::CountryCurrencyFilter,
) -> Result<cgraph::ConstraintGraph<dir::DirValue>, KgraphError> {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _domain = builder.make_domain(
DOMAIN_IDENTIFIER.to_string(),
"Payment methods enabled for MerchantConnectorAccount",
);
for acct in accts {
compile_merchant_connector_graph(&mut builder, acct, config)?;
}
Ok(builder.build())
}
#[cfg(feature = "v1")]
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used)]
use std::collections::{HashMap, HashSet};
use api_models::enums as api_enums;
use euclid::{
dirval,
dssa::graph::{AnalysisContext, CgraphExt},
};
use hyperswitch_constraint_graph::{ConstraintGraph, CycleCheck, Memoization};
use super::*;
use crate::types as kgraph_types;
fn build_test_data() -> ConstraintGraph<dir::DirValue> {
use api_models::{admin::*, payment_methods::*};
let profile_id = common_utils::generate_profile_id_of_default_length();
// #[cfg(feature = "v2")]
// let stripe_account = MerchantConnectorResponse {
// connector_type: api_enums::ConnectorType::FizOperations,
// connector_name: "stripe".to_string(),
// id: common_utils::generate_merchant_connector_account_id_of_default_length(),
// connector_label: Some("something".to_string()),
// connector_account_details: masking::Secret::new(serde_json::json!({})),
// disabled: None,
// metadata: None,
// payment_methods_enabled: Some(vec![PaymentMethodsEnabled {
// payment_method: api_enums::PaymentMethod::Card,
// payment_method_types: Some(vec![
// RequestPaymentMethodTypes {
// payment_method_type: api_enums::PaymentMethodType::Credit,
// payment_experience: None,
// card_networks: Some(vec![
// api_enums::CardNetwork::Visa,
// api_enums::CardNetwork::Mastercard,
// ]),
// accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![
// api_enums::Currency::INR,
// ])),
// accepted_countries: None,
// minimum_amount: Some(MinorUnit::new(10)),
// maximum_amount: Some(MinorUnit::new(1000)),
// recurring_enabled: true,
// installment_payment_enabled: true,
// },
// RequestPaymentMethodTypes {
// payment_method_type: api_enums::PaymentMethodType::Debit,
// payment_experience: None,
// card_networks: Some(vec![
// api_enums::CardNetwork::Maestro,
// api_enums::CardNetwork::JCB,
// ]),
// accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![
// api_enums::Currency::GBP,
// ])),
// accepted_countries: None,
// minimum_amount: Some(MinorUnit::new(10)),
// maximum_amount: Some(MinorUnit::new(1000)),
// recurring_enabled: true,
// installment_payment_enabled: true,
// },
// ]),
// }]),
// frm_configs: None,
// connector_webhook_details: None,
// profile_id,
// applepay_verified_domains: None,
// pm_auth_config: None,
// status: api_enums::ConnectorStatus::Inactive,
// additional_merchant_data: None,
// connector_wallets_details: None,
// };
#[cfg(feature = "v1")]
let stripe_account = MerchantConnectorResponse {
connector_type: api_enums::ConnectorType::FizOperations,
connector_name: "stripe".to_string(),
merchant_connector_id:
common_utils::generate_merchant_connector_account_id_of_default_length(),
business_country: Some(api_enums::CountryAlpha2::US),
connector_label: Some("something".to_string()),
business_label: Some("food".to_string()),
business_sub_label: None,
connector_account_details: masking::Secret::new(serde_json::json!({})),
test_mode: None,
disabled: None,
metadata: None,
payment_methods_enabled: Some(vec![PaymentMethodsEnabled {
payment_method: api_enums::PaymentMethod::Card,
payment_method_types: Some(vec![
RequestPaymentMethodTypes {
payment_method_type: api_enums::PaymentMethodType::Credit,
payment_experience: None,
card_networks: Some(vec![
api_enums::CardNetwork::Visa,
api_enums::CardNetwork::Mastercard,
]),
accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![
api_enums::Currency::INR,
])),
accepted_countries: None,
minimum_amount: Some(MinorUnit::new(10)),
maximum_amount: Some(MinorUnit::new(1000)),
recurring_enabled: Some(true),
installment_payment_enabled: Some(true),
},
RequestPaymentMethodTypes {
payment_method_type: api_enums::PaymentMethodType::Debit,
payment_experience: None,
card_networks: Some(vec![
api_enums::CardNetwork::Maestro,
api_enums::CardNetwork::JCB,
]),
accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![
api_enums::Currency::GBP,
])),
accepted_countries: None,
minimum_amount: Some(MinorUnit::new(10)),
maximum_amount: Some(MinorUnit::new(1000)),
recurring_enabled: Some(true),
installment_payment_enabled: Some(true),
},
]),
}]),
frm_configs: None,
connector_webhook_details: None,
profile_id,
applepay_verified_domains: None,
pm_auth_config: None,
status: api_enums::ConnectorStatus::Inactive,
additional_merchant_data: None,
connector_wallets_details: None,
};
let config_map = kgraph_types::CountryCurrencyFilter {
connector_configs: HashMap::from([(
api_enums::RoutableConnectors::Stripe,
kgraph_types::PaymentMethodFilters(HashMap::from([
(
kgraph_types::PaymentMethodFilterKey::PaymentMethodType(
api_enums::PaymentMethodType::Credit,
),
kgraph_types::CurrencyCountryFlowFilter {
currency: Some(HashSet::from([
api_enums::Currency::INR,
api_enums::Currency::USD,
])),
country: Some(HashSet::from([api_enums::CountryAlpha2::IN])),
not_available_flows: Some(kgraph_types::NotAvailableFlows {
capture_method: Some(api_enums::CaptureMethod::Manual),
}),
},
),
(
kgraph_types::PaymentMethodFilterKey::PaymentMethodType(
api_enums::PaymentMethodType::Debit,
),
kgraph_types::CurrencyCountryFlowFilter {
currency: Some(HashSet::from([
api_enums::Currency::GBP,
api_enums::Currency::PHP,
])),
country: Some(HashSet::from([api_enums::CountryAlpha2::IN])),
not_available_flows: Some(kgraph_types::NotAvailableFlows {
capture_method: Some(api_enums::CaptureMethod::Manual),
}),
},
),
])),
)]),
default_configs: None,
};
make_mca_graph(vec![stripe_account], &config_map).expect("Failed graph construction")
}
#[test]
fn test_credit_card_success_case() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Credit),
dirval!(CardNetwork = Visa),
dirval!(PaymentCurrency = INR),
dirval!(PaymentAmount = 101),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_debit_card_success_case() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Debit),
dirval!(CardNetwork = Maestro),
dirval!(PaymentCurrency = GBP),
dirval!(PaymentAmount = 100),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_single_mismatch_failure_case() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Debit),
dirval!(CardNetwork = Maestro),
dirval!(PaymentCurrency = PHP),
dirval!(PaymentAmount = 100),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_amount_mismatch_failure_case() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Debit),
dirval!(CardNetwork = Visa),
dirval!(PaymentCurrency = GBP),
dirval!(PaymentAmount = 7),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_incomplete_data_failure_case() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Debit),
dirval!(PaymentCurrency = GBP),
dirval!(PaymentAmount = 7),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
//println!("{:#?}", result);
//println!("{}", serde_json::to_string_pretty(&result).expect("Hello"));
assert!(result.is_err());
}
#[test]
fn test_incomplete_data_failure_case2() {
let graph = build_test_data();
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(CardType = Debit),
dirval!(CardNetwork = Visa),
dirval!(PaymentCurrency = GBP),
dirval!(PaymentAmount = 100),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
//println!("{:#?}", result);
//println!("{}", serde_json::to_string_pretty(&result).expect("Hello"));
assert!(result.is_err());
}
#[test]
fn test_sandbox_applepay_bug_usecase() {
let value = serde_json::json!([
{
"connector_type": "payment_processor",
"connector_name": "bluesnap",
"merchant_connector_id": "REDACTED",
"status": "inactive",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "REDACTED",
"key1": "REDACTED"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Mastercard",
"Visa",
"AmericanExpress",
"JCB",
"DinersClub",
"Discover",
"CartesBancaires",
"UnionPay"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Mastercard",
"Visa",
"Interac",
"AmericanExpress",
"JCB",
"DinersClub",
"Discover",
"CartesBancaires",
"UnionPay"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {},
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"frm_configs": null
},
{
"connector_type": "payment_processor",
"connector_name": "stripe",
"merchant_connector_id": "REDACTED",
"status": "inactive",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": "REDACTED"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Mastercard",
"Visa",
"AmericanExpress",
"JCB",
"DinersClub",
"Discover",
"CartesBancaires",
"UnionPay"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Mastercard",
"Visa",
"Interac",
"AmericanExpress",
"JCB",
"DinersClub",
"Discover",
"CartesBancaires",
"UnionPay"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": []
}
],
"metadata": {},
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"frm_configs": null
}
]);
let data: Vec<admin_api::MerchantConnectorResponse> =
serde_json::from_value(value).expect("data");
let config = kgraph_types::CountryCurrencyFilter {
connector_configs: HashMap::new(),
default_configs: None,
};
let graph = make_mca_graph(data, &config).expect("graph");
let context = AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentAmount = 212),
dirval!(PaymentCurrency = ILS),
dirval!(PaymentMethod = Wallet),
dirval!(WalletType = ApplePay),
]);
let result = graph.key_value_analysis(
dirval!(Connector = Stripe),
&context,
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok(), "stripe validation failed");
let result = graph.key_value_analysis(
dirval!(Connector = Bluesnap),
&context,
&mut Memoization::new(),
&mut CycleCheck::new(),
None,
);
assert!(result.is_err(), "bluesnap validation failed");
}
}
</file>
|
{
"crate": "kgraph_utils",
"file": "crates/kgraph_utils/src/mca.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 13092
}
|
large_file_1480219942177711650
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: external_services
File: crates/external_services/src/grpc_client/unified_connector_service.rs
</path>
<file>
use std::collections::{HashMap, HashSet};
use common_enums::connector_enums::Connector;
use common_utils::{consts as common_utils_consts, errors::CustomResult, types::Url};
use error_stack::ResultExt;
pub use hyperswitch_interfaces::unified_connector_service::transformers::UnifiedConnectorServiceError;
use masking::{PeekInterface, Secret};
use router_env::logger;
use tokio::time::{timeout, Duration};
use tonic::{
metadata::{MetadataMap, MetadataValue},
transport::Uri,
};
use unified_connector_service_client::payments::{
self as payments_grpc, payment_service_client::PaymentServiceClient,
PaymentServiceAuthorizeResponse, PaymentServiceTransformRequest,
PaymentServiceTransformResponse,
};
use crate::{
consts,
grpc_client::{GrpcClientSettings, GrpcHeadersUcs},
utils::deserialize_hashset,
};
/// Result type for Dynamic Routing
pub type UnifiedConnectorServiceResult<T> = CustomResult<T, UnifiedConnectorServiceError>;
/// Contains the Unified Connector Service client
#[derive(Debug, Clone)]
pub struct UnifiedConnectorServiceClient {
/// The Unified Connector Service Client
pub client: PaymentServiceClient<tonic::transport::Channel>,
}
/// Contains the Unified Connector Service Client config
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct UnifiedConnectorServiceClientConfig {
/// Base URL of the gRPC Server
pub base_url: Url,
/// Contains the connection timeout duration in seconds
pub connection_timeout: u64,
/// Set of external services/connectors available for the unified connector service
#[serde(default, deserialize_with = "deserialize_hashset")]
pub ucs_only_connectors: HashSet<Connector>,
/// Set of connectors for which psync is disabled in unified connector service
#[serde(default, deserialize_with = "deserialize_hashset")]
pub ucs_psync_disabled_connectors: HashSet<Connector>,
}
/// Contains the Connector Auth Type and related authentication data.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct ConnectorAuthMetadata {
/// Name of the connector (e.g., "stripe", "paypal").
pub connector_name: String,
/// Type of authentication used (e.g., "HeaderKey", "BodyKey", "SignatureKey").
pub auth_type: String,
/// Optional API key used for authentication.
pub api_key: Option<Secret<String>>,
/// Optional additional key used by some authentication types.
pub key1: Option<Secret<String>>,
/// Optional API secret used for signature or secure authentication.
pub api_secret: Option<Secret<String>>,
/// Optional auth_key_map used for authentication.
pub auth_key_map:
Option<HashMap<common_enums::enums::Currency, common_utils::pii::SecretSerdeValue>>,
/// Id of the merchant.
pub merchant_id: Secret<String>,
}
/// External Vault Proxy Related Metadata
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum ExternalVaultProxyMetadata {
/// VGS proxy data variant
VgsMetadata(VgsMetadata),
}
/// VGS proxy data
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct VgsMetadata {
/// External vault url
pub proxy_url: Url,
/// CA certificates to verify the vault server
pub certificate: Secret<String>,
}
impl UnifiedConnectorServiceClient {
/// Builds the connection to the gRPC service
pub async fn build_connections(config: &GrpcClientSettings) -> Option<Self> {
match &config.unified_connector_service {
Some(unified_connector_service_client_config) => {
let uri: Uri = match unified_connector_service_client_config
.base_url
.get_string_repr()
.parse()
{
Ok(parsed_uri) => parsed_uri,
Err(err) => {
logger::error!(error = ?err, "Failed to parse URI for Unified Connector Service");
return None;
}
};
let connect_result = timeout(
Duration::from_secs(unified_connector_service_client_config.connection_timeout),
PaymentServiceClient::connect(uri),
)
.await;
match connect_result {
Ok(Ok(client)) => {
logger::info!("Successfully connected to Unified Connector Service");
Some(Self { client })
}
Ok(Err(err)) => {
logger::error!(error = ?err, "Failed to connect to Unified Connector Service");
None
}
Err(err) => {
logger::error!(error = ?err, "Connection to Unified Connector Service timed out");
None
}
}
}
None => {
router_env::logger::error!(?config.unified_connector_service, "Unified Connector Service config is missing");
None
}
}
}
/// Performs Payment Authorize
pub async fn payment_authorize(
&self,
payment_authorize_request: payments_grpc::PaymentServiceAuthorizeRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<PaymentServiceAuthorizeResponse>> {
let mut request = tonic::Request::new(payment_authorize_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.authorize(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentAuthorizeFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_authorize",
connector_name=?connector_name,
"UCS payment authorize gRPC call failed"
)
})
}
/// Performs Payment Sync/Get
pub async fn payment_get(
&self,
payment_get_request: payments_grpc::PaymentServiceGetRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PaymentServiceGetResponse>>
{
let mut request = tonic::Request::new(payment_get_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.get(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentGetFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_get",
connector_name=?connector_name,
"UCS payment get/sync gRPC call failed"
)
})
}
/// Performs Payment Setup Mandate
pub async fn payment_setup_mandate(
&self,
payment_register_request: payments_grpc::PaymentServiceRegisterRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PaymentServiceRegisterResponse>>
{
let mut request = tonic::Request::new(payment_register_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.register(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentRegisterFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_setup_mandate",
connector_name=?connector_name,
"UCS payment setup mandate gRPC call failed"
)
})
}
/// Performs Payment repeat (MIT - Merchant Initiated Transaction).
pub async fn payment_repeat(
&self,
payment_repeat_request: payments_grpc::PaymentServiceRepeatEverythingRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServiceRepeatEverythingResponse>,
> {
let mut request = tonic::Request::new(payment_repeat_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.repeat_everything(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentRepeatEverythingFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_repeat",
connector_name=?connector_name,
"UCS payment repeat gRPC call failed"
)
})
}
/// Transforms incoming webhook through UCS
pub async fn transform_incoming_webhook(
&self,
webhook_transform_request: PaymentServiceTransformRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<PaymentServiceTransformResponse>> {
let mut request = tonic::Request::new(webhook_transform_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.transform(request)
.await
.change_context(UnifiedConnectorServiceError::WebhookTransformFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="transform_incoming_webhook",
connector_name=?connector_name,
"UCS webhook transform gRPC call failed"
)
})
}
}
/// Build the gRPC Headers for Unified Connector Service Request
pub fn build_unified_connector_service_grpc_headers(
meta: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> Result<MetadataMap, UnifiedConnectorServiceError> {
let mut metadata = MetadataMap::new();
let parse =
|key: &str, value: &str| -> Result<MetadataValue<_>, UnifiedConnectorServiceError> {
value.parse::<MetadataValue<_>>().map_err(|error| {
logger::error!(?error);
UnifiedConnectorServiceError::HeaderInjectionFailed(key.to_string())
})
};
metadata.append(
consts::UCS_HEADER_CONNECTOR,
parse("connector", &meta.connector_name)?,
);
metadata.append(
consts::UCS_HEADER_AUTH_TYPE,
parse("auth_type", &meta.auth_type)?,
);
if let Some(api_key) = meta.api_key {
metadata.append(
consts::UCS_HEADER_API_KEY,
parse("api_key", api_key.peek())?,
);
}
if let Some(key1) = meta.key1 {
metadata.append(consts::UCS_HEADER_KEY1, parse("key1", key1.peek())?);
}
if let Some(api_secret) = meta.api_secret {
metadata.append(
consts::UCS_HEADER_API_SECRET,
parse("api_secret", api_secret.peek())?,
);
}
if let Some(auth_key_map) = meta.auth_key_map {
let auth_key_map_str = serde_json::to_string(&auth_key_map).map_err(|error| {
logger::error!(?error);
UnifiedConnectorServiceError::ParsingFailed
})?;
metadata.append(
consts::UCS_HEADER_AUTH_KEY_MAP,
parse("auth_key_map", &auth_key_map_str)?,
);
}
metadata.append(
common_utils_consts::X_MERCHANT_ID,
parse(common_utils_consts::X_MERCHANT_ID, meta.merchant_id.peek())?,
);
if let Some(external_vault_proxy_metadata) = grpc_headers.external_vault_proxy_metadata {
metadata.append(
consts::UCS_HEADER_EXTERNAL_VAULT_METADATA,
parse("external_vault_metadata", &external_vault_proxy_metadata)?,
);
};
let lineage_ids_str = grpc_headers
.lineage_ids
.get_url_encoded_string()
.map_err(|err| {
logger::error!(?err);
UnifiedConnectorServiceError::HeaderInjectionFailed(consts::UCS_LINEAGE_IDS.to_string())
})?;
metadata.append(
consts::UCS_LINEAGE_IDS,
parse(consts::UCS_LINEAGE_IDS, &lineage_ids_str)?,
);
if let Some(reference_id) = grpc_headers.merchant_reference_id {
metadata.append(
consts::UCS_HEADER_REFERENCE_ID,
parse(
consts::UCS_HEADER_REFERENCE_ID,
reference_id.get_string_repr(),
)?,
);
};
if let Some(request_id) = grpc_headers.request_id {
metadata.append(
common_utils_consts::X_REQUEST_ID,
parse(common_utils_consts::X_REQUEST_ID, &request_id)?,
);
};
if let Some(shadow_mode) = grpc_headers.shadow_mode {
metadata.append(
common_utils_consts::X_UNIFIED_CONNECTOR_SERVICE_MODE,
parse(
common_utils_consts::X_UNIFIED_CONNECTOR_SERVICE_MODE,
&shadow_mode.to_string(),
)?,
);
}
if let Err(err) = grpc_headers
.tenant_id
.parse()
.map(|tenant_id| metadata.append(common_utils_consts::TENANT_HEADER, tenant_id))
{
logger::error!(
header_parse_error=?err,
tenant_id=?grpc_headers.tenant_id,
"Failed to parse tenant_id header for UCS gRPC request: {}",
common_utils_consts::TENANT_HEADER
);
}
Ok(metadata)
}
</file>
|
{
"crate": "external_services",
"file": "crates/external_services/src/grpc_client/unified_connector_service.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2927
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.