text
stringlengths
70
351k
source
stringclasses
4 values
<file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=macro_def,use_site use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![status]: HList![Status] = <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![status]: HList![Status] = <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=use_site,macro_def use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=macro_def,use_site use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=macro_def,use_site use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![merchant_id, api_key]: HList![MerchantId, ApiKey] = <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![merchant_id, api_key]: HList![MerchantId, ApiKey] = <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=use_site,macro_def use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![payment_id]: HList![PaymentId] = <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![payment_id]: HList![PaymentId] = <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=use_site,macro_def use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![payment_id]: HList![PaymentId] = <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![payment_id]: HList![PaymentId] = <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=use_site,macro_def use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![status]: HList![Status] = <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![status]: HList![Status] = <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=use_site,macro_def use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=macro_def,use_site use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=macro_def,use_site use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![merchant_id, _api_key]: HList![MerchantId, ApiKey] = admin_client <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![merchant_id, _api_key]: HList![MerchantId, ApiKey] = admin_client <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=use_site,macro_def use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![merchant_id, api_key]: HList![MerchantId, ApiKey] = <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> let hlist_pat![merchant_id, api_key]: HList![MerchantId, ApiKey] = <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=use_site,macro_def use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> <|fim_prefix|> #![allow( dead_code, clippy::expect_used, clippy::missing_panics_doc, clippy::unwrap_used )] use actix_http::{ <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=macro_def,use_site use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/utils.rs" crate="router" role="macro_def"> macro_rules! HList { () => { $crate::utils::HNil }; ($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> }; } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/tests/utils.rs<|crate|> router macro=HList roles=macro_def,use_site use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/tests/integration_demo.rs" crate="router" role="use_site"> <|fim_prefix|> async fn exceed_refund() { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" crate="router" role="use_site"> ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, (theme, DEFAULT_BACKGROUND_COLOR.to_string()), (logo, DEFAULT_MERCHANT_LOGO.to_string()), (seller_name, merchant_name.clone()), (sdk_layout, DEFAULT_SDK_LAYOUT.to_owned()), (display_sdk_only, DEFAULT_DISPLAY_SDK_ONLY), ( enabled_saved_payment_method, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD ), (hide_card_nickname_field, DEFAULT_HIDE_CARD_NICKNAME_FIELD), (show_card_form_by_default, DEFAULT_SHOW_CARD_FORM), ( enable_button_only_on_form_ready, DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY ) ); <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" crate="router" role="use_site"> ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, (theme, DEFAULT_BACKGROUND_COLOR.to_string()), (logo, DEFAULT_MERCHANT_LOGO.to_string()), (seller_name, merchant_name.clone()), (sdk_layout, DEFAULT_SDK_LAYOUT.to_owned()), (display_sdk_only, DEFAULT_DISPLAY_SDK_ONLY), ( enabled_saved_payment_method, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD ), (hide_card_nickname_field, DEFAULT_HIDE_CARD_NICKNAME_FIELD), (show_card_form_by_default, DEFAULT_SHOW_CARD_FORM), ( enable_button_only_on_form_ready, DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY ) ); <file_sep path="hyperswitch/crates/router/src/macros.rs" crate="router" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/src/macros.rs<|crate|> router macro=get_payment_link_config_value roles=use_site,macro_def use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub use common_utils::{ <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/src/macros.rs" crate="router" role="macro_def"> <|fim_prefix|> pub use common_utils::{ <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" crate="router" role="use_site"> ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, (details_layout), (background_image, |background_image| background_image .foreign_into()), (payment_button_text), (custom_message_for_card_terms), (payment_button_colour), (skip_status_screen), (background_colour), (payment_button_text_colour), (sdk_ui_rules), (payment_link_ui_rules), ); <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" crate="router" role="use_site"> ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, (details_layout), (background_image, |background_image| background_image .foreign_into()), (payment_button_text), (custom_message_for_card_terms), (payment_button_colour), (skip_status_screen), (background_colour), (payment_button_text_colour), (sdk_ui_rules), (payment_link_ui_rules), ); <file_sep path="hyperswitch/crates/router/src/macros.rs" crate="router" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/src/macros.rs<|crate|> router macro=get_payment_link_config_value roles=use_site,macro_def use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub use common_utils::{ <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/src/macros.rs" crate="router" role="macro_def"> <|fim_prefix|> pub use common_utils::{ <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/macros.rs" crate="router" role="macro_def"> macro_rules! get_payment_link_config_value { ($config:expr, $business_config:expr, $(($field:ident, $default:expr)),*) => { ( $(get_payment_link_config_value_based_on_priority!($config, $business_config, $field, $default)),* ) }; ($config:expr, $business_config:expr, $(($field:ident)),*) => { ( $( $config .as_ref() .and_then(|pc_config| pc_config.theme_config.$field.clone()) .or_else(|| { $business_config .as_ref() .and_then(|business_config| business_config.$field.clone()) }) ),* ) }; ($config:expr, $business_config:expr, $(($field:ident $(, $transform:expr)?)),* $(,)?) => { ( $( $config .as_ref() .and_then(|pc_config| pc_config.theme_config.$field.clone()) .or_else(|| { $business_config .as_ref() .and_then(|business_config| { let value = business_config.$field.clone(); $(let value = value.map($transform);)? value }) }) ),* ) }; } <file_sep path="hyperswitch/crates/router/src/macros.rs" crate="router" role="macro_def"> macro_rules! get_payment_link_config_value { ($config:expr, $business_config:expr, $(($field:ident, $default:expr)),*) => { ( $(get_payment_link_config_value_based_on_priority!($config, $business_config, $field, $default)),* ) }; ($config:expr, $business_config:expr, $(($field:ident)),*) => { ( $( $config .as_ref() .and_then(|pc_config| pc_config.theme_config.$field.clone()) .or_else(|| { $business_config .as_ref() .and_then(|business_config| business_config.$field.clone()) }) ),* ) }; ($config:expr, $business_config:expr, $(($field:ident $(, $transform:expr)?)),* $(,)?) => { ( $( $config .as_ref() .and_then(|pc_config| pc_config.theme_config.$field.clone()) .or_else(|| { $business_config .as_ref() .and_then(|business_config| { let value = business_config.$field.clone(); $(let value = value.map($transform);)? value }) }) ),* ) }; } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/src/macros.rs<|crate|> router macro=get_payment_link_config_value roles=macro_def,use_site use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn get_payment_link_config_based_on_priority( payment_create_link_config: Option<api_models::payments::PaymentCreatePaymentLinkConfig>, business_link_config: Option<diesel_models::business_profile::BusinessPaymentLinkConfig>, merchant_name: String, default_domain_name: String, payment_link_config_id: Option<String>, ) -> Result<(PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>> { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" crate="router" role="use_site"> <|fim_prefix|> pub fn get_payment_link_config_based_on_priority( payment_create_link_config: Option<api_models::payments::PaymentCreatePaymentLinkConfig>, business_link_config: Option<diesel_models::business_profile::BusinessPaymentLinkConfig>, merchant_name: String, default_domain_name: String, payment_link_config_id: Option<String>, ) -> Result<(PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>> { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/connector/payone.rs" crate="router" role="use_site"> let date_header = get_formatted_date_time!( "[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT" )?; <file_sep path="hyperswitch/crates/router/src/connector/payone.rs" crate="router" role="use_site"> let date_header = get_formatted_date_time!( "[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT" )?; <file_sep path="hyperswitch/crates/router/src/macros.rs" crate="router" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/src/macros.rs<|crate|> router macro=get_formatted_date_time roles=use_site,macro_def use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub use common_utils::{ <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/src/macros.rs" crate="router" role="macro_def"> <|fim_prefix|> pub use common_utils::{ <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch/crates/router/src/macros.rs" crate="router" role="macro_def"> macro_rules! get_formatted_date_time { ($date_format:tt) => {{ let format = time::macros::format_description!($date_format); time::OffsetDateTime::now_utc() .format(&format) .change_context($crate::core::errors::ConnectorError::InvalidDateFormat) }}; } <file_sep path="hyperswitch/crates/router/src/macros.rs" crate="router" role="macro_def"> macro_rules! get_formatted_date_time { ($date_format:tt) => {{ let format = time::macros::format_description!($date_format); time::OffsetDateTime::now_utc() .format(&format) .change_context($crate::core::errors::ConnectorError::InvalidDateFormat) }}; } <file_sep path="hyperswitch/crates/router/src/connector/payone.rs" crate="router" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch/crates/router/src/macros.rs<|crate|> router macro=get_formatted_date_time roles=macro_def,use_site use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch/crates/router/src/connector/payone.rs" crate="router" role="use_site"> <|fim_prefix|> fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch-card-vault/benches/hashing.rs" crate="benches" role="macro_def"> macro_rules! const_iter { ($algo:ident, $body:block, $key:ident, $($ty:expr),*) => { $( let $algo = $ty($key.clone()); $body )* }; } <file_sep path="hyperswitch-card-vault/benches/hashing.rs" crate="benches" role="macro_def"> macro_rules! const_iter { ($algo:ident, $body:block, $key:ident, $($ty:expr),*) => { $( let $algo = $ty($key.clone()); $body )* }; } <file_sep path="hyperswitch-card-vault/benches/hashing.rs" crate="benches" role="use_site"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch-card-vault/benches/hashing.rs<|crate|> benches macro=const_iter roles=macro_def,use_site use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> pub fn criterion_hmac_sha512(c: &mut Criterion) { <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch-card-vault/benches/hashing.rs" crate="benches" role="use_site"> <|fim_prefix|> pub fn criterion_hmac_sha512(c: &mut Criterion) { <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<file_sep path="hyperswitch-card-vault/benches/hashing.rs" crate="benches" role="use_site"> const_iter!( algo, { let mut group = c.benchmark_group(format!("{}", algo)); (1..ITERATION).for_each(|po| { let max: u64 = (2_u64).pow(po); let value = (0..max).map(|_| rand::random::<u8>()).collect::<Vec<_>>(); let hashed = algo .encode(value.clone().into()) .expect("Failed while hashing"); group.throughput(criterion::Throughput::Bytes(max)); group.bench_with_input( criterion::BenchmarkId::from_parameter(format!("{}", max)), &value, |b, value| { b.iter(|| { black_box( algo.encode(black_box(value.clone().into())) .expect("Failed while hashing") == hashed, ) }) }, ); }) }, key, HmacSha512::<1>::new, HmacSha512::<10>::new, HmacSha512::<100>::new, HmacSha512::<1000>::new ); <file_sep path="hyperswitch-card-vault/benches/hashing.rs" crate="benches" role="use_site"> const_iter!( algo, { let mut group = c.benchmark_group(format!("{}", algo)); (1..ITERATION).for_each(|po| { let max: u64 = (2_u64).pow(po); let value = (0..max).map(|_| rand::random::<u8>()).collect::<Vec<_>>(); let hashed = algo .encode(value.clone().into()) .expect("Failed while hashing"); group.throughput(criterion::Throughput::Bytes(max)); group.bench_with_input( criterion::BenchmarkId::from_parameter(format!("{}", max)), &value, |b, value| { b.iter(|| { black_box( algo.encode(black_box(value.clone().into())) .expect("Failed while hashing") == hashed, ) }) }, ); }) }, key, HmacSha512::<1>::new, HmacSha512::<10>::new, HmacSha512::<100>::new, HmacSha512::<1000>::new ); <file_sep path="hyperswitch-card-vault/benches/hashing.rs" crate="benches" role="macro_def"> <|fim_prefix|> <|meta_start|><|file|> hyperswitch-card-vault/benches/hashing.rs<|crate|> benches macro=const_iter roles=use_site,macro_def use=invoke item=fn pack=proc_macro_neighborhoods lang=rust<|meta_end|> #![allow(clippy::expect_used)] #![allow(clippy::missing_panics_doc)] use criterion::{ <|fim_suffix|> <|fim_middle|> } <file_sep path="hyperswitch-card-vault/benches/hashing.rs" crate="benches" role="macro_def"> <|fim_prefix|> #![allow(clippy::expect_used)] #![allow(clippy::missing_panics_doc)] use criterion::{ <|fim_suffix|> <|fim_middle|> }
proc_macro_neighborhoods
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/authentication.rs<|crate|> router<|op|> select entity=authentication repo=hyperswitch tables=authentication joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="authentication" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/authentication.rs" use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; 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: String, pub merchant_id: common_utils::id_type::MerchantId, pub authentication_connector: 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: 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, } impl Authentication { pub fn is_separate_authn_required(&self) -> bool { self.maximum_supported_version .as_ref() .is_some_and(|version| version.get_major() == 2) } } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Insertable)] #[diesel(table_name = authentication)] pub struct AuthenticationNew { pub authentication_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub authentication_connector: 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: 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, } #[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>, }, AuthenticationUpdate { authentication_value: Option<String>, 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>, }, PostAuthenticationUpdate { trans_status: common_enums::TransactionStatus, authentication_value: Option<String>, eci: Option<String>, authentication_status: common_enums::AuthenticationStatus, }, 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 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 ds_trans_id: Option<String>, pub directory_server_id: Option<String>, pub acquirer_country_code: Option<String>, pub service_details: Option<serde_json::Value>, } 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(), cavv: 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(), } } } 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, cavv, 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, } = 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), cavv: cavv.or(source.cavv), 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), ..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, } => 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, ..Default::default() }, AuthenticationUpdate::AuthenticationUpdate { authentication_value, trans_status, authentication_type, acs_url, challenge_request, acs_reference_number, acs_trans_id, acs_signed_content, connector_metadata, authentication_status, ds_trans_id, } => Self { cavv: authentication_value, 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, ..Default::default() }, AuthenticationUpdate::PostAuthenticationUpdate { trans_status, authentication_value, eci, authentication_status, } => Self { trans_status: Some(trans_status), cavv: authentication_value, eci, authentication_status: Some(authentication_status), ..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_sep> pack="QBP-A" entity="authentication" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/authentication.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ authentication::{ Authentication, AuthenticationNew, AuthenticationUpdate, AuthenticationUpdateInternal, }, errors, schema::authentication::dsl, PgPooledConn, StorageResult, }; impl AuthenticationNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authentication> { generics::generic_insert(conn, self).await } } impl Authentication { pub async fn update_by_merchant_id_authentication_id( conn: &PgPooledConn, merchant_id: common_utils::id_type::MerchantId, authentication_id: String, authorization_update: AuthenticationUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::authentication_id.eq(authentication_id.to_owned())), AuthenticationUpdateInternal::from(authorization_update), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NotFound => Err(error.attach_printable( "Authentication with the given Authentication ID does not exist", )), errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::authentication_id.eq(authentication_id.to_owned())), ) .await } _ => Err(error), }, result => result, } } pub async fn find_by_merchant_id_authentication_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, authentication_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::authentication_id.eq(authentication_id.to_owned())), ) .await } pub async fn find_authentication_by_merchant_id_connector_authentication_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_authentication_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_authentication_id.eq(connector_authentication_id.to_owned())), ) .await } } <file_sep> pack="QBP-A" entity="authentication" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/authentication.rs" use diesel_models::authentication::AuthenticationUpdateInternal; use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait AuthenticationInterface { async fn insert_authentication( &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError>; async fn find_authentication_by_merchant_id_authentication_id( &self, merchant_id: &common_utils::id_type::MerchantId, authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError>; async fn find_authentication_by_merchant_id_connector_authentication_id( &self, merchant_id: common_utils::id_type::MerchantId, connector_authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError>; async fn update_authentication_by_merchant_id_authentication_id( &self, previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError>; } #[async_trait::async_trait] impl AuthenticationInterface for Store { #[instrument(skip_all)] async fn insert_authentication( &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; authentication .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_authentication_by_merchant_id_authentication_id( &self, merchant_id: &common_utils::id_type::MerchantId, authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Authentication::find_by_merchant_id_authentication_id( &conn, merchant_id, &authentication_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_authentication_by_merchant_id_connector_authentication_id( &self, merchant_id: common_utils::id_type::MerchantId, connector_authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Authentication::find_authentication_by_merchant_id_connector_authentication_id( &conn, &merchant_id, &connector_authentication_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_authentication_by_merchant_id_authentication_id( &self, previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Authentication::update_by_merchant_id_authentication_id( &conn, previous_state.merchant_id, previous_state.authentication_id, authentication_update, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl AuthenticationInterface for MockDb { async fn insert_authentication( &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError> { let mut authentications = self.authentications.lock().await; if authentications.iter().any(|authentication_inner| { authentication_inner.authentication_id == authentication.authentication_id }) { Err(errors::StorageError::DuplicateValue { entity: "authentication_id", key: Some(authentication.authentication_id.clone()), })? } let authentication = storage::Authentication { created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), authentication_id: authentication.authentication_id, merchant_id: authentication.merchant_id, authentication_status: authentication.authentication_status, authentication_connector: authentication.authentication_connector, connector_authentication_id: authentication.connector_authentication_id, authentication_data: None, payment_method_id: authentication.payment_method_id, authentication_type: authentication.authentication_type, authentication_lifecycle_status: authentication.authentication_lifecycle_status, error_code: authentication.error_code, error_message: authentication.error_message, connector_metadata: authentication.connector_metadata, maximum_supported_version: authentication.maximum_supported_version, threeds_server_transaction_id: authentication.threeds_server_transaction_id, cavv: authentication.cavv, authentication_flow_type: authentication.authentication_flow_type, message_version: authentication.message_version, eci: authentication.eci, trans_status: authentication.trans_status, acquirer_bin: authentication.acquirer_bin, acquirer_merchant_id: authentication.acquirer_merchant_id, three_ds_method_data: authentication.three_ds_method_data, three_ds_method_url: authentication.three_ds_method_url, acs_url: authentication.acs_url, challenge_request: authentication.challenge_request, acs_reference_number: authentication.acs_reference_number, acs_trans_id: authentication.acs_trans_id, acs_signed_content: authentication.acs_signed_content, profile_id: authentication.profile_id, payment_id: authentication.payment_id, merchant_connector_id: authentication.merchant_connector_id, ds_trans_id: authentication.ds_trans_id, directory_server_id: authentication.directory_server_id, acquirer_country_code: authentication.acquirer_country_code, service_details: authentication.service_details, organization_id: authentication.organization_id, }; authentications.push(authentication.clone()); Ok(authentication) } async fn find_authentication_by_merchant_id_authentication_id( &self, merchant_id: &common_utils::id_type::MerchantId, authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { let authentications = self.authentications.lock().await; authentications .iter() .find(|a| a.merchant_id == *merchant_id && a.authentication_id == authentication_id) .ok_or( errors::StorageError::ValueNotFound(format!( "cannot find authentication for authentication_id = {authentication_id} and merchant_id = {merchant_id:?}" )).into(), ).cloned() } async fn find_authentication_by_merchant_id_connector_authentication_id( &self, _merchant_id: common_utils::id_type::MerchantId, _connector_authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_authentication_by_merchant_id_authentication_id( &self, previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError> { let mut authentications = self.authentications.lock().await; let authentication_id = previous_state.authentication_id.clone(); let merchant_id = previous_state.merchant_id.clone(); authentications .iter_mut() .find(|authentication| authentication.authentication_id == authentication_id && authentication.merchant_id == merchant_id) .map(|authentication| { let authentication_update_internal = AuthenticationUpdateInternal::from(authentication_update); let updated_authentication = authentication_update_internal.apply_changeset(previous_state); *authentication = updated_authentication.clone(); updated_authentication }) .ok_or( errors::StorageError::ValueNotFound(format!( "cannot find authentication for authentication_id = {authentication_id} and merchant_id = {merchant_id:?}" )) .into(), ) } } <file_sep> pack="QBP-A" entity="authentication" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-05-115544_add-service-details/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE authentication DROP COLUMN IF EXISTS service_details; <file_sep> pack="QBP-A" entity="authentication" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-01-30-111507_add_organization_id_in_authentication/up.sql" -- Your SQL goes here ALTER TABLE authentication ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org'; <file_sep> pack="QBP-A" entity="authentication" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-01-30-111507_add_organization_id_in_authentication/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE authentication DROP COLUMN IF EXISTS organization_id; <file_sep> pack="QBP-A" entity="authentication" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_authentication.rs" // schema snippet for entity=authentication repo=hyperswitch // table: authentication columns: [] entities: [authentication] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/authorization.rs<|crate|> router<|op|> select entity=authorization repo=hyperswitch tables=authorization joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="authorization" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/authorization.rs" use common_utils::types::MinorUnit; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::incremental_authorization}; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, Hash, )] #[diesel(table_name = incremental_authorization, primary_key(authorization_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct Authorization { pub authorization_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: common_utils::id_type::PaymentId, pub amount: MinorUnit, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub status: storage_enums::AuthorizationStatus, pub error_code: Option<String>, pub error_message: Option<String>, pub connector_authorization_id: Option<String>, pub previously_authorized_amount: MinorUnit, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = incremental_authorization)] pub struct AuthorizationNew { pub authorization_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: common_utils::id_type::PaymentId, pub amount: MinorUnit, pub status: storage_enums::AuthorizationStatus, pub error_code: Option<String>, pub error_message: Option<String>, pub connector_authorization_id: Option<String>, pub previously_authorized_amount: MinorUnit, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum AuthorizationUpdate { StatusUpdate { status: storage_enums::AuthorizationStatus, error_code: Option<String>, error_message: Option<String>, connector_authorization_id: Option<String>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = incremental_authorization)] pub struct AuthorizationUpdateInternal { pub status: Option<storage_enums::AuthorizationStatus>, pub error_code: Option<String>, pub error_message: Option<String>, pub modified_at: Option<PrimitiveDateTime>, pub connector_authorization_id: Option<String>, } impl AuthorizationUpdateInternal { pub fn create_authorization(self, source: Authorization) -> Authorization { Authorization { status: self.status.unwrap_or(source.status), error_code: self.error_code.or(source.error_code), error_message: self.error_message.or(source.error_message), modified_at: self.modified_at.unwrap_or(common_utils::date_time::now()), connector_authorization_id: self .connector_authorization_id .or(source.connector_authorization_id), ..source } } } impl From<AuthorizationUpdate> for AuthorizationUpdateInternal { fn from(authorization_child_update: AuthorizationUpdate) -> Self { let now = Some(common_utils::date_time::now()); match authorization_child_update { AuthorizationUpdate::StatusUpdate { status, error_code, error_message, connector_authorization_id, } => Self { status: Some(status), error_code, error_message, connector_authorization_id, modified_at: now, }, } } } <file_sep> pack="QBP-A" entity="authorization" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/authorization.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ authorization::{ Authorization, AuthorizationNew, AuthorizationUpdate, AuthorizationUpdateInternal, }, errors, schema::incremental_authorization::dsl, PgPooledConn, StorageResult, }; impl AuthorizationNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authorization> { generics::generic_insert(conn, self).await } } impl Authorization { pub async fn update_by_merchant_id_authorization_id( conn: &PgPooledConn, merchant_id: common_utils::id_type::MerchantId, authorization_id: String, authorization_update: AuthorizationUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::authorization_id.eq(authorization_id.to_owned())), AuthorizationUpdateInternal::from(authorization_update), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NotFound => Err(error.attach_printable( "Authorization with the given Authorization ID does not exist", )), errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::authorization_id.eq(authorization_id.to_owned())), ) .await } _ => Err(error), }, result => result, } } 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, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), None, None, Some(dsl::created_at.asc()), ) .await } } <file_sep> pack="QBP-A" entity="authorization" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/authorization.rs" use diesel_models::authorization::AuthorizationUpdateInternal; use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait AuthorizationInterface { async fn insert_authorization( &self, authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError>; async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError>; async fn update_authorization_by_merchant_id_authorization_id( &self, merchant_id: common_utils::id_type::MerchantId, authorization_id: String, authorization: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError>; } #[async_trait::async_trait] impl AuthorizationInterface for Store { #[instrument(skip_all)] async fn insert_authorization( &self, authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; authorization .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Authorization::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_authorization_by_merchant_id_authorization_id( &self, merchant_id: common_utils::id_type::MerchantId, authorization_id: String, authorization: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Authorization::update_by_merchant_id_authorization_id( &conn, merchant_id, authorization_id, authorization, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl AuthorizationInterface for MockDb { async fn insert_authorization( &self, authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError> { let mut authorizations = self.authorizations.lock().await; if authorizations.iter().any(|authorization_inner| { authorization_inner.authorization_id == authorization.authorization_id }) { Err(errors::StorageError::DuplicateValue { entity: "authorization_id", key: None, })? } let authorization = storage::Authorization { authorization_id: authorization.authorization_id, merchant_id: authorization.merchant_id, payment_id: authorization.payment_id, amount: authorization.amount, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), status: authorization.status, error_code: authorization.error_code, error_message: authorization.error_message, connector_authorization_id: authorization.connector_authorization_id, previously_authorized_amount: authorization.previously_authorized_amount, }; authorizations.push(authorization.clone()); Ok(authorization) } async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> { let authorizations = self.authorizations.lock().await; let authorizations_found: Vec<storage::Authorization> = authorizations .iter() .filter(|a| a.merchant_id == *merchant_id && a.payment_id == *payment_id) .cloned() .collect(); Ok(authorizations_found) } async fn update_authorization_by_merchant_id_authorization_id( &self, merchant_id: common_utils::id_type::MerchantId, authorization_id: String, authorization_update: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError> { let mut authorizations = self.authorizations.lock().await; authorizations .iter_mut() .find(|authorization| authorization.authorization_id == authorization_id && authorization.merchant_id == merchant_id) .map(|authorization| { let authorization_updated = AuthorizationUpdateInternal::from(authorization_update) .create_authorization(authorization.clone()); *authorization = authorization_updated.clone(); authorization_updated }) .ok_or( errors::StorageError::ValueNotFound(format!( "cannot find authorization for authorization_id = {authorization_id} and merchant_id = {merchant_id:?}" )) .into(), ) } } <file_sep> pack="QBP-A" entity="authorization" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-11-30-170902_add-authorizations-table/up.sql" -- Your SQL goes here CREATE TABLE IF NOT EXISTS incremental_authorization ( authorization_id VARCHAR(64) NOT NULL, merchant_id VARCHAR(64) NOT NULL, payment_id VARCHAR(64) NOT NULL, amount BIGINT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, modified_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, status VARCHAR(64) NOT NULL, error_code VARCHAR(255), error_message TEXT, connector_authorization_id VARCHAR(64), previously_authorized_amount BIGINT NOT NULL, PRIMARY KEY (authorization_id, merchant_id) ); <file_sep> pack="QBP-A" entity="authorization" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-11-30-170902_add-authorizations-table/down.sql" -- This file should undo anything in `up.sql` DROP TABLE IF EXISTS incremental_authorization; <file_sep> pack="QBP-A" entity="authorization" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_authorization.rs" // schema snippet for entity=authorization repo=hyperswitch // table: incremental_authorization columns: [] entities: [authorization] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/blocklist.rs<|crate|> router<|op|> select entity=blocklist repo=hyperswitch tables=blocklist joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="blocklist" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/blocklist.rs" use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::blocklist; #[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] #[diesel(table_name = blocklist)] pub struct BlocklistNew { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint_id: String, pub data_kind: common_enums::BlocklistDataKind, pub metadata: Option<serde_json::Value>, pub created_at: time::PrimitiveDateTime, } #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize, )] #[diesel(table_name = blocklist, primary_key(merchant_id, fingerprint_id), check_for_backend(diesel::pg::Pg))] pub struct Blocklist { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint_id: String, pub data_kind: common_enums::BlocklistDataKind, pub metadata: Option<serde_json::Value>, pub created_at: time::PrimitiveDateTime, } <file_sep> pack="QBP-A" entity="blocklist" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/blocklist.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ blocklist::{Blocklist, BlocklistNew}, schema::blocklist::dsl, PgPooledConn, StorageResult, }; impl BlocklistNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Blocklist> { generics::generic_insert(conn, self).await } } impl Blocklist { pub async fn find_by_merchant_id_fingerprint_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), ) .await } pub async fn list_by_merchant_id_data_kind( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, data_kind: common_enums::BlocklistDataKind, limit: i64, offset: i64, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::data_kind.eq(data_kind.to_owned())), Some(limit), Some(offset), Some(dsl::created_at.desc()), ) .await } pub async fn list_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), None, None, Some(dsl::created_at.desc()), ) .await } pub async fn delete_by_merchant_id_fingerprint_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), ) .await } } <file_sep> pack="QBP-A" entity="blocklist" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/blocklist.rs" use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait BlocklistInterface { async fn insert_blocklist_entry( &self, pm_blocklist_new: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError>; async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError>; async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError>; async fn list_blocklist_entries_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>; async fn list_blocklist_entries_by_merchant_id_data_kind( &self, merchant_id: &common_utils::id_type::MerchantId, data_kind: common_enums::BlocklistDataKind, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>; } #[async_trait::async_trait] impl BlocklistInterface for Store { #[instrument(skip_all)] async fn insert_blocklist_entry( &self, pm_blocklist: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; pm_blocklist .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::find_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::list_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id_data_kind( &self, merchant_id: &common_utils::id_type::MerchantId, data_kind: common_enums::BlocklistDataKind, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::list_by_merchant_id_data_kind( &conn, merchant_id, data_kind, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::delete_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl BlocklistInterface for MockDb { #[instrument(skip_all)] async fn insert_blocklist_entry( &self, _pm_blocklist: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn list_blocklist_entries_by_merchant_id( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn list_blocklist_entries_by_merchant_id_data_kind( &self, _merchant_id: &common_utils::id_type::MerchantId, _data_kind: common_enums::BlocklistDataKind, _limit: i64, _offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl BlocklistInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_entry( &self, pm_blocklist: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError> { self.diesel_store.insert_blocklist_entry(pm_blocklist).await } #[instrument(skip_all)] async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { self.diesel_store .find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint) .await } #[instrument(skip_all)] async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { self.diesel_store .delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint) .await } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id_data_kind( &self, merchant_id: &common_utils::id_type::MerchantId, data_kind: common_enums::BlocklistDataKind, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { self.diesel_store .list_blocklist_entries_by_merchant_id_data_kind(merchant_id, data_kind, limit, offset) .await } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { self.diesel_store .list_blocklist_entries_by_merchant_id(merchant_id) .await } } <file_sep> pack="QBP-A" entity="blocklist" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/up.sql" -- Your SQL goes here -- The below query will lock the blocklist table -- Running this query is not necessary on higher environments -- as the application will work fine without these queries being run -- This query should be run after the new version of application is deployed ALTER TABLE blocklist DROP CONSTRAINT blocklist_pkey; -- Use the `merchant_id, fingerprint_id` columns as primary key -- These are already unique, not null columns -- So this query should not fail for not null or duplicate value reasons ALTER TABLE blocklist ADD PRIMARY KEY (merchant_id, fingerprint_id); <file_sep> pack="QBP-A" entity="blocklist" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE blocklist DROP CONSTRAINT blocklist_pkey; ALTER TABLE blocklist ADD PRIMARY KEY (id); <file_sep> pack="QBP-A" entity="blocklist" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/down.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR(64)` column for tables that had it removed. -- It must be ensured that the deployed version of the application includes the `id` column in any of its queries. -- Re-create the id column as this was used as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account ADD COLUMN id VARCHAR(64); ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account ADD COLUMN id VARCHAR(64); ------------------------ Customers ----------------------- ALTER TABLE customers ADD COLUMN id VARCHAR(64); ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent ADD COLUMN id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt ADD COLUMN id VARCHAR(64); ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods ADD COLUMN id VARCHAR(64); ------------------------ Address ----------------------- ALTER TABLE address ADD COLUMN id VARCHAR(64); ------------------------ Dispute ----------------------- ALTER TABLE dispute ADD COLUMN id VARCHAR(64); ------------------------ Mandate ----------------------- ALTER TABLE mandate ADD COLUMN id VARCHAR(64); ------------------------ Refund ----------------------- ALTER TABLE refund ADD COLUMN id VARCHAR(64); ------------------------ BlockList ----------------------- ALTER TABLE blocklist ADD COLUMN id VARCHAR(64); ------------------------ Roles ----------------------- ALTER TABLE roles ADD COLUMN id VARCHAR(64); ------------------------ Users ----------------------- ALTER TABLE users ADD COLUMN id VARCHAR(64); <file_sep> pack="QBP-A" entity="blocklist" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_blocklist.rs" // schema snippet for entity=blocklist repo=hyperswitch // table: blocklist columns: [] entities: [blocklist] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/blocklist_fingerprint.rs<|crate|> router<|op|> select entity=blocklist_fingerprint repo=hyperswitch tables=blocklist_fingerprint joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="blocklist_fingerprint" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/blocklist_fingerprint.rs" use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::blocklist_fingerprint; #[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] #[diesel(table_name = blocklist_fingerprint)] pub struct BlocklistFingerprintNew { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint_id: String, pub data_kind: common_enums::BlocklistDataKind, pub encrypted_fingerprint: String, pub created_at: time::PrimitiveDateTime, } #[derive( Clone, Debug, Eq, PartialEq, Queryable, Identifiable, Selectable, Deserialize, Serialize, )] #[diesel(table_name = blocklist_fingerprint, primary_key(merchant_id, fingerprint_id), check_for_backend(diesel::pg::Pg))] pub struct BlocklistFingerprint { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint_id: String, pub data_kind: common_enums::BlocklistDataKind, pub encrypted_fingerprint: String, pub created_at: time::PrimitiveDateTime, } <file_sep> pack="QBP-A" entity="blocklist_fingerprint" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/blocklist_fingerprint.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ blocklist_fingerprint::{BlocklistFingerprint, BlocklistFingerprintNew}, schema::blocklist_fingerprint::dsl, PgPooledConn, StorageResult, }; impl BlocklistFingerprintNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistFingerprint> { generics::generic_insert(conn, self).await } } impl BlocklistFingerprint { pub async fn find_by_merchant_id_fingerprint_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), ) .await } } <file_sep> pack="QBP-A" entity="blocklist_fingerprint" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/blocklist_fingerprint.rs" use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait BlocklistFingerprintInterface { async fn insert_blocklist_fingerprint_entry( &self, pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>; async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>; } #[async_trait::async_trait] impl BlocklistFingerprintInterface for Store { #[instrument(skip_all)] async fn insert_blocklist_fingerprint_entry( &self, pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; pm_fingerprint_new .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::BlocklistFingerprint::find_by_merchant_id_fingerprint_id( &conn, merchant_id, fingerprint_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl BlocklistFingerprintInterface for MockDb { async fn insert_blocklist_fingerprint_entry( &self, _pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint_id: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl BlocklistFingerprintInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_fingerprint_entry( &self, pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { self.diesel_store .insert_blocklist_fingerprint_entry(pm_fingerprint_new) .await } #[instrument(skip_all)] async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { self.diesel_store .find_blocklist_fingerprint_by_merchant_id_fingerprint_id(merchant_id, fingerprint) .await } } <file_sep> pack="QBP-A" entity="blocklist_fingerprint" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-12-11-075542_create_pm_fingerprint_table/up.sql" -- Your SQL goes here CREATE TYPE "BlocklistDataKind" AS ENUM ( 'payment_method', 'card_bin', 'extended_card_bin' ); CREATE TABLE blocklist_fingerprint ( id SERIAL PRIMARY KEY, merchant_id VARCHAR(64) NOT NULL, fingerprint_id VARCHAR(64) NOT NULL, data_kind "BlocklistDataKind" NOT NULL, encrypted_fingerprint TEXT NOT NULL, created_at TIMESTAMP NOT NULL ); CREATE UNIQUE INDEX blocklist_fingerprint_merchant_id_fingerprint_id_index ON blocklist_fingerprint (merchant_id, fingerprint_id); <file_sep> pack="QBP-A" entity="blocklist_fingerprint" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-12-11-075542_create_pm_fingerprint_table/down.sql" -- This file should undo anything in `up.sql` DROP TABLE blocklist_fingerprint; DROP TYPE "BlocklistDataKind"; <file_sep> pack="QBP-A" entity="blocklist_fingerprint" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_blocklist_fingerprint.rs" // schema snippet for entity=blocklist_fingerprint repo=hyperswitch // table: blocklist_fingerprint columns: [] entities: [blocklist_fingerprint] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/blocklist_lookup.rs<|crate|> router<|op|> select entity=blocklist_lookup repo=hyperswitch tables=blocklist_lookup joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="blocklist_lookup" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/blocklist_lookup.rs" use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::blocklist_lookup; #[derive(Default, Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] #[diesel(table_name = blocklist_lookup)] pub struct BlocklistLookupNew { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint: String, } #[derive( Default, Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize, )] #[diesel(table_name = blocklist_lookup, primary_key(merchant_id, fingerprint), check_for_backend(diesel::pg::Pg))] pub struct BlocklistLookup { pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint: String, } <file_sep> pack="QBP-A" entity="blocklist_lookup" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/blocklist_lookup.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ blocklist_lookup::{BlocklistLookup, BlocklistLookupNew}, schema::blocklist_lookup::dsl, PgPooledConn, StorageResult, }; impl BlocklistLookupNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistLookup> { generics::generic_insert(conn, self).await } } impl BlocklistLookup { pub async fn find_by_merchant_id_fingerprint( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint.eq(fingerprint.to_owned())), ) .await } pub async fn delete_by_merchant_id_fingerprint( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::fingerprint.eq(fingerprint.to_owned())), ) .await } } <file_sep> pack="QBP-A" entity="blocklist_lookup" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/blocklist_lookup.rs" use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait BlocklistLookupInterface { async fn insert_blocklist_lookup_entry( &self, blocklist_lookup_new: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; } #[async_trait::async_trait] impl BlocklistLookupInterface for Store { #[instrument(skip_all)] async fn insert_blocklist_lookup_entry( &self, blocklist_lookup_entry: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; blocklist_lookup_entry .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::BlocklistLookup::find_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::BlocklistLookup::delete_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl BlocklistLookupInterface for MockDb { #[instrument(skip_all)] async fn insert_blocklist_lookup_entry( &self, _blocklist_lookup_entry: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl BlocklistLookupInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_lookup_entry( &self, blocklist_lookup_entry: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { self.diesel_store .insert_blocklist_lookup_entry(blocklist_lookup_entry) .await } #[instrument(skip_all)] async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { self.diesel_store .find_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint) .await } #[instrument(skip_all)] async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { self.diesel_store .delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint) .await } } <file_sep> pack="QBP-A" entity="blocklist_lookup" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-12-18-062613_create_blocklist_lookup_table/up.sql" -- Your SQL goes here CREATE TABLE blocklist_lookup ( id SERIAL PRIMARY KEY, merchant_id VARCHAR(64) NOT NULL, fingerprint TEXT NOT NULL ); CREATE UNIQUE INDEX blocklist_lookup_merchant_id_fingerprint_index ON blocklist_lookup (merchant_id, fingerprint); <file_sep> pack="QBP-A" entity="blocklist_lookup" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-12-18-062613_create_blocklist_lookup_table/down.sql" -- This file should undo anything in `up.sql` DROP TABLE blocklist_lookup; <file_sep> pack="QBP-A" entity="blocklist_lookup" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_blocklist_lookup.rs" // schema snippet for entity=blocklist_lookup repo=hyperswitch // table: blocklist_lookup columns: [] entities: [blocklist_lookup] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/callback_mapper.rs<|crate|> router<|op|> select entity=callback_mapper repo=hyperswitch tables=callback_mapper joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="callback_mapper" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/callback_mapper.rs" use common_utils::pii; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::callback_mapper; #[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)] #[diesel(table_name = callback_mapper, primary_key(id, type_), check_for_backend(diesel::pg::Pg))] pub struct CallbackMapper { pub id: String, pub type_: String, pub data: pii::SecretSerdeValue, pub created_at: time::PrimitiveDateTime, pub last_modified_at: time::PrimitiveDateTime, } <file_sep> pack="QBP-A" entity="callback_mapper" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/callback_mapper.rs" use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ callback_mapper::CallbackMapper, schema::callback_mapper::dsl, PgPooledConn, StorageResult, }; impl CallbackMapper { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } } <file_sep> pack="QBP-A" entity="callback_mapper" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/callback_mapper.rs" use error_stack::report; use hyperswitch_domain_models::callback_mapper as domain; use router_env::{instrument, tracing}; use storage_impl::DataModelExt; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait CallbackMapperInterface { async fn insert_call_back_mapper( &self, call_back_mapper: domain::CallbackMapper, ) -> CustomResult<domain::CallbackMapper, errors::StorageError>; async fn find_call_back_mapper_by_id( &self, id: &str, ) -> CustomResult<domain::CallbackMapper, errors::StorageError>; } #[async_trait::async_trait] impl CallbackMapperInterface for Store { #[instrument(skip_all)] async fn insert_call_back_mapper( &self, call_back_mapper: domain::CallbackMapper, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; call_back_mapper .to_storage_model() .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .map(domain::CallbackMapper::from_storage_model) } #[instrument(skip_all)] async fn find_call_back_mapper_by_id( &self, id: &str, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::CallbackMapper::find_by_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) .map(domain::CallbackMapper::from_storage_model) } } <file_sep> pack="QBP-A" entity="callback_mapper" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-11-13-105952_add_call-back-mapper_table/up.sql" -- Your SQL goes here CREATE TABLE IF NOT EXISTS callback_mapper ( id VARCHAR(128) NOT NULL, type VARCHAR(64) NOT NULL, data JSONB NOT NULL, created_at TIMESTAMP NOT NULL, last_modified_at TIMESTAMP NOT NULL, PRIMARY KEY (id, type) ); <file_sep> pack="QBP-A" entity="callback_mapper" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-11-13-105952_add_call-back-mapper_table/down.sql" -- This file should undo anything in `up.sql` DROP TABLE IF EXISTS callback_mapper; <file_sep> pack="QBP-A" entity="callback_mapper" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_callback_mapper.rs" // schema snippet for entity=callback_mapper repo=hyperswitch // table: callback_mapper columns: [] entities: [callback_mapper] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/callback_mapper.rs<|crate|> storage_impl<|op|> select entity=callback_mapper repo=hyperswitch tables=callback_mapper joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="callback_mapper" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/callback_mapper.rs" use common_utils::pii; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::callback_mapper; #[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)] #[diesel(table_name = callback_mapper, primary_key(id, type_), check_for_backend(diesel::pg::Pg))] pub struct CallbackMapper { pub id: String, pub type_: String, pub data: pii::SecretSerdeValue, pub created_at: time::PrimitiveDateTime, pub last_modified_at: time::PrimitiveDateTime, } <file_sep> pack="QBP-B" entity="callback_mapper" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/callback_mapper.rs" use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ callback_mapper::CallbackMapper, schema::callback_mapper::dsl, PgPooledConn, StorageResult, }; impl CallbackMapper { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } } <file_sep> pack="QBP-B" entity="callback_mapper" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/callback_mapper.rs" use diesel_models::callback_mapper::CallbackMapper as DieselCallbackMapper; use hyperswitch_domain_models::callback_mapper::CallbackMapper; use crate::DataModelExt; impl DataModelExt for CallbackMapper { type StorageModel = DieselCallbackMapper; fn to_storage_model(self) -> Self::StorageModel { DieselCallbackMapper { id: self.id, type_: self.type_, data: self.data, created_at: self.created_at, last_modified_at: self.last_modified_at, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { id: storage_model.id, type_: storage_model.type_, data: storage_model.data, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at, } } } <file_sep> pack="QBP-B" entity="callback_mapper" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-11-13-105952_add_call-back-mapper_table/up.sql" -- Your SQL goes here CREATE TABLE IF NOT EXISTS callback_mapper ( id VARCHAR(128) NOT NULL, type VARCHAR(64) NOT NULL, data JSONB NOT NULL, created_at TIMESTAMP NOT NULL, last_modified_at TIMESTAMP NOT NULL, PRIMARY KEY (id, type) ); <file_sep> pack="QBP-B" entity="callback_mapper" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-11-13-105952_add_call-back-mapper_table/down.sql" -- This file should undo anything in `up.sql` DROP TABLE IF EXISTS callback_mapper; <file_sep> pack="QBP-B" entity="callback_mapper" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_callback_mapper.rs" // schema snippet for entity=callback_mapper repo=hyperswitch // table: callback_mapper columns: [] entities: [callback_mapper] sources: [migration, model_or_query]
query_boundary
<file_sep> pack="QBP-A" entity="cards_info" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/cards_info.rs" use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::cards_info}; #[derive( Clone, Debug, Queryable, Identifiable, Selectable, serde::Deserialize, serde::Serialize, Insertable, )] #[diesel(table_name = cards_info, primary_key(card_iin), check_for_backend(diesel::pg::Pg))] pub struct CardInfo { pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<storage_enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub date_created: PrimitiveDateTime, pub last_updated: Option<PrimitiveDateTime>, pub last_updated_provider: Option<String>, } #[derive( Clone, Debug, PartialEq, Eq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, )] #[diesel(table_name = cards_info)] pub struct UpdateCardInfo { pub card_issuer: Option<String>, pub card_network: Option<storage_enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub last_updated: Option<PrimitiveDateTime>, pub last_updated_provider: Option<String>, } <file_sep> pack="QBP-A" entity="cards_info" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/cards_info.rs" use diesel::{associations::HasTable, ExpressionMethods}; use error_stack::report; use crate::{ cards_info::{CardInfo, UpdateCardInfo}, errors, query::generics, schema::cards_info::dsl, PgPooledConn, StorageResult, }; impl CardInfo { pub async fn find_by_iin(conn: &PgPooledConn, card_iin: &str) -> StorageResult<Option<Self>> { generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>( conn, card_iin.to_owned(), ) .await } pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn update( conn: &PgPooledConn, card_iin: String, data: UpdateCardInfo, ) -> StorageResult<Self> { <fim_prefix> <|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/cards_info.rs<|crate|> router<|op|> update entity=cards_info repo=hyperswitch tables=cards_info joins=none pack=query_boundary lang=rust_sql<|meta_end|> generics::generic_update_with_results::<<Self as HasTable>::Table, UpdateCardInfo, _, _>( conn, dsl::card_iin.eq(card_iin), data, ) .await? .first() <fim_suffix> .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating card_info entry") }) } } <fim_middle> <file_sep> pack="QBP-A" entity="cards_info" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/cards_info.rs" use error_stack::report; use router_env::{instrument, tracing}; use crate::{ connection, core::errors::{self, CustomResult}, db::MockDb, services::Store, types::storage::cards_info::{CardInfo, UpdateCardInfo}, }; #[async_trait::async_trait] pub trait CardsInfoInterface { async fn get_card_info( &self, _card_iin: &str, ) -> CustomResult<Option<CardInfo>, errors::StorageError>; async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, errors::StorageError>; async fn update_card_info( &self, card_iin: String, data: UpdateCardInfo, ) -> CustomResult<CardInfo, errors::StorageError>; } #[async_trait::async_trait] impl CardsInfoInterface for Store { #[instrument(skip_all)] async fn get_card_info( &self, card_iin: &str, ) -> CustomResult<Option<CardInfo>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; CardInfo::find_by_iin(&conn, card_iin) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; data.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_card_info( &self, card_iin: String, data: UpdateCardInfo, ) -> CustomResult<CardInfo, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; CardInfo::update(&conn, card_iin, data) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl CardsInfoInterface for MockDb { #[instrument(skip_all)] async fn get_card_info( &self, card_iin: &str, ) -> CustomResult<Option<CardInfo>, errors::StorageError> { Ok(self .cards_info .lock() .await .iter() .find(|ci| ci.card_iin == card_iin) .cloned()) } async fn add_card_info(&self, _data: CardInfo) -> CustomResult<CardInfo, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_card_info( &self, _card_iin: String, _data: UpdateCardInfo, ) -> CustomResult<CardInfo, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } <file_sep> pack="QBP-A" entity="cards_info" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-03-14-123541_add_cards_info_table/up.sql" -- Your SQL goes here CREATE TABLE cards_info ( card_iin VARCHAR(16) PRIMARY KEY, card_issuer TEXT, card_network TEXT, card_type TEXT, card_subtype TEXT, card_issuing_country TEXT, bank_code_id VARCHAR(32), bank_code VARCHAR(32), country_code VARCHAR(32), date_created TIMESTAMP NOT NULL, last_updated TIMESTAMP, last_updated_provider TEXT ) <file_sep> pack="QBP-A" entity="cards_info" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-03-14-123541_add_cards_info_table/down.sql" -- This file should undo anything in `up.sql` DROP TABLE IF EXISTS cards_info; <file_sep> pack="QBP-A" entity="cards_info" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_cards_info.rs" // schema snippet for entity=cards_info repo=hyperswitch // table: cards_info columns: [] entities: [cards_info] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/configs.rs<|crate|> router<|op|> select entity=configs repo=hyperswitch tables=configs joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="configs" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/configs.rs" use std::convert::From; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::schema::configs; #[derive(Default, Clone, Debug, Insertable, Serialize, Deserialize)] #[diesel(table_name = configs)] pub struct ConfigNew { pub key: String, pub config: String, } #[derive(Default, Clone, Debug, Identifiable, Queryable, Selectable, Deserialize, Serialize)] #[diesel(table_name = configs, primary_key(key), check_for_backend(diesel::pg::Pg))] pub struct Config { pub key: String, pub config: String, } #[derive(Debug)] pub enum ConfigUpdate { Update { config: Option<String> }, } #[derive(Clone, Debug, AsChangeset, Default)] #[diesel(table_name = configs)] pub struct ConfigUpdateInternal { config: Option<String>, } impl ConfigUpdateInternal { pub fn create_config(self, source: Config) -> Config { Config { ..source } } } impl From<ConfigUpdate> for ConfigUpdateInternal { fn from(config_update: ConfigUpdate) -> Self { match config_update { ConfigUpdate::Update { config } => Self { config }, } } } impl From<ConfigNew> for Config { fn from(config_new: ConfigNew) -> Self { Self { key: config_new.key, config: config_new.config, } } } <file_sep> pack="QBP-A" entity="configs" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/configs.rs" use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ configs::{Config, ConfigNew, ConfigUpdate, ConfigUpdateInternal}, errors, schema::configs::dsl, PgPooledConn, StorageResult, }; impl ConfigNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Config> { generics::generic_insert(conn, self).await } } impl Config { pub async fn find_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, key.to_owned()).await } pub async fn update_by_key( conn: &PgPooledConn, key: &str, config_update: ConfigUpdate, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, key.to_owned(), ConfigUpdateInternal::from(config_update), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>( conn, key.to_owned(), ) .await } _ => Err(error), }, result => result, } } pub async fn delete_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::key.eq(key.to_owned()), ) .await } } <file_sep> pack="QBP-A" entity="configs" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/configs.rs" use diesel_models::configs::ConfigUpdateInternal; use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::redis::cache::{self, CacheKind, CONFIG_CACHE}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, db::StorageInterface, types::storage, }; #[async_trait::async_trait] pub trait ConfigInterface { async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, errors::StorageError>; async fn find_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError>; async fn find_config_by_key_unwrap_or( &self, key: &str, // If the config is not found it will be created with the default value. default_config: Option<String>, ) -> CustomResult<storage::Config, errors::StorageError>; async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError>; async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError>; async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError>; async fn delete_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError>; } #[async_trait::async_trait] impl ConfigInterface for Store { #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let inserted = config .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))?; cache::redact_from_redis_and_publish( self.get_cache_store().as_ref(), [CacheKind::Config((&inserted.key).into())], ) .await?; Ok(inserted) } #[instrument(skip_all)] async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Config::update_by_key(&conn, key, config_update) .await .map_err(|error| report!(errors::StorageError::from(error))) } //update in DB and remove in redis and cache #[instrument(skip_all)] async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { cache::publish_and_redact(self, CacheKind::Config(key.into()), || { self.update_config_in_database(key, config_update) }) .await } #[instrument(skip_all)] async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(errors::StorageError::from(error))) } //check in cache, then redis then finally DB, and on the way back populate redis and cache #[instrument(skip_all)] async fn find_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { let find_config_by_key_from_db = || async { let conn = connection::pg_connection_write(self).await?; storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(errors::StorageError::from(error))) }; cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).await } #[instrument(skip_all)] async fn find_config_by_key_unwrap_or( &self, key: &str, // If the config is not found it will be cached with the default value. default_config: Option<String>, ) -> CustomResult<storage::Config, errors::StorageError> { let find_else_unwrap_or = || async { let conn = connection::pg_connection_write(self).await?; match storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(errors::StorageError::from(error))) { Ok(a) => Ok(a), Err(err) => { if err.current_context().is_db_not_found() { default_config .map(|c| { storage::ConfigNew { key: key.to_string(), config: c, } .into() }) .ok_or(err) } else { Err(err) } } } }; cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await } #[instrument(skip_all)] async fn delete_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let deleted = storage::Config::delete_by_key(&conn, key) .await .map_err(|error| report!(errors::StorageError::from(error)))?; cache::redact_from_redis_and_publish( self.get_cache_store().as_ref(), [CacheKind::Config((&deleted.key).into())], ) .await?; Ok(deleted) } } #[async_trait::async_trait] impl ConfigInterface for MockDb { #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, errors::StorageError> { let mut configs = self.configs.lock().await; let config_new = storage::Config { key: config.key, config: config.config, }; configs.push(config_new.clone()); Ok(config_new) } async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { self.update_config_by_key(key, config_update).await } async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { let result = self .configs .lock() .await .iter_mut() .find(|c| c.key == key) .ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find config to update".to_string()) .into() }) .map(|c| { let config_updated = ConfigUpdateInternal::from(config_update).create_config(c.clone()); *c = config_updated.clone(); config_updated }); result } async fn delete_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { let mut configs = self.configs.lock().await; let result = configs .iter() .position(|c| c.key == key) .map(|index| configs.remove(index)) .ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find config to delete".to_string()) .into() }); result } async fn find_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { let configs = self.configs.lock().await; let config = configs.iter().find(|c| c.key == key).cloned(); config.ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find config".to_string()).into() }) } async fn find_config_by_key_unwrap_or( &self, key: &str, _default_config: Option<String>, ) -> CustomResult<storage::Config, errors::StorageError> { self.find_config_by_key(key).await } async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { self.find_config_by_key(key).await } } <file_sep> pack="QBP-A" entity="configs" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2022-09-29-084920_create_initial_tables/up.sql" -- Types CREATE TYPE "AttemptStatus" AS ENUM ( 'started', 'authentication_failed', 'juspay_declined', 'pending_vbv', 'vbv_successful', 'authorized', 'authorization_failed', 'charged', 'authorizing', 'cod_initiated', 'voided', 'void_initiated', 'capture_initiated', 'capture_failed', 'void_failed', 'auto_refunded', 'partial_charged', 'pending', 'failure', 'payment_method_awaited', 'confirmation_awaited' ); CREATE TYPE "AuthenticationType" AS ENUM ('three_ds', 'no_three_ds'); CREATE TYPE "CaptureMethod" AS ENUM ('automatic', 'manual', 'scheduled'); CREATE TYPE "ConnectorType" AS ENUM ( 'payment_processor', 'payment_vas', 'fin_operations', 'fiz_operations', 'networks', 'banking_entities', 'non_banking_finance' ); CREATE TYPE "Currency" AS ENUM ( 'AED', 'ALL', 'AMD', 'ARS', 'AUD', 'AWG', 'AZN', 'BBD', 'BDT', 'BHD', 'BMD', 'BND', 'BOB', 'BRL', 'BSD', 'BWP', 'BZD', 'CAD', 'CHF', 'CNY', 'COP', 'CRC', 'CUP', 'CZK', 'DKK', 'DOP', 'DZD', 'EGP', 'ETB', 'EUR', 'FJD', 'GBP', 'GHS', 'GIP', 'GMD', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', 'INR', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'MAD', 'MDL', 'MKD', 'MMK', 'MNT', 'MOP', 'MUR', 'MVR', 'MWK', 'MXN', 'MYR', 'NAD', 'NGN', 'NIO', 'NOK', 'NPR', 'NZD', 'OMR', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'QAR', 'RUB', 'SAR', 'SCR', 'SEK', 'SGD', 'SLL', 'SOS', 'SSP', 'SVC', 'SZL', 'THB', 'TTD', 'TWD', 'TZS', 'USD', 'UYU', 'UZS', 'YER', 'ZAR' ); CREATE TYPE "EventClass" AS ENUM ('payments'); CREATE TYPE "EventObjectType" AS ENUM ('payment_details'); CREATE TYPE "EventType" AS ENUM ('payment_succeeded'); CREATE TYPE "FutureUsage" AS ENUM ('on_session', 'off_session'); CREATE TYPE "IntentStatus" AS ENUM ( 'succeeded', 'failed', 'processing', 'requires_customer_action', 'requires_payment_method', 'requires_confirmation' ); CREATE TYPE "MandateStatus" AS ENUM ( 'active', 'inactive', 'pending', 'revoked' ); CREATE TYPE "MandateType" AS ENUM ('single_use', 'multi_use'); CREATE TYPE "PaymentFlow" AS ENUM ( 'vsc', 'emi', 'otp', 'upi_intent', 'upi_collect', 'upi_scan_and_pay', 'sdk' ); CREATE TYPE "PaymentMethodIssuerCode" AS ENUM ( 'jp_hdfc', 'jp_icici', 'jp_googlepay', 'jp_applepay', 'jp_phonepe', 'jp_wechat', 'jp_sofort', 'jp_giropay', 'jp_sepa', 'jp_bacs' ); CREATE TYPE "PaymentMethodSubType" AS ENUM ( 'credit', 'debit', 'upi_intent', 'upi_collect', 'credit_card_installments', 'pay_later_installments' ); CREATE TYPE "PaymentMethodType" AS ENUM ( 'card', 'bank_transfer', 'netbanking', 'upi', 'open_banking', 'consumer_finance', 'wallet', 'payment_container', 'bank_debit', 'pay_later' ); CREATE TYPE "ProcessTrackerStatus" AS ENUM ( 'processing', 'new', 'pending', 'process_started', 'finish' ); CREATE TYPE "RefundStatus" AS ENUM ( 'failure', 'manual_review', 'pending', 'success', 'transaction_failure' ); CREATE TYPE "RefundType" AS ENUM ( 'instant_refund', 'regular_refund', 'retry_refund' ); CREATE TYPE "RoutingAlgorithm" AS ENUM ( 'round_robin', 'max_conversion', 'min_cost', 'custom' ); -- Tables CREATE TABLE address ( id SERIAL, address_id VARCHAR(255) PRIMARY KEY, city VARCHAR(255), country VARCHAR(255), line1 VARCHAR(255), line2 VARCHAR(255), line3 VARCHAR(255), state VARCHAR(255), zip VARCHAR(255), first_name VARCHAR(255), last_name VARCHAR(255), phone_number VARCHAR(255), country_code VARCHAR(255), created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, modified_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP ); CREATE TABLE configs ( id SERIAL, key VARCHAR(255) NOT NULL, config TEXT NOT NULL, PRIMARY KEY (key) ); CREATE TABLE customers ( id SERIAL, customer_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, NAME VARCHAR(255), email VARCHAR(255), phone VARCHAR(255), phone_country_code VARCHAR(255), description VARCHAR(255), address JSON, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, metadata JSON, PRIMARY KEY (customer_id, merchant_id) ); CREATE TABLE events ( id SERIAL PRIMARY KEY, event_id VARCHAR(255) NOT NULL, event_type "EventType" NOT NULL, event_class "EventClass" NOT NULL, is_webhook_notified BOOLEAN NOT NULL DEFAULT FALSE, intent_reference_id VARCHAR(255), primary_object_id VARCHAR(255) NOT NULL, primary_object_type "EventObjectType" NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP ); CREATE TABLE locker_mock_up ( id SERIAL PRIMARY KEY, card_id VARCHAR(255) NOT NULL, external_id VARCHAR(255) NOT NULL, card_fingerprint VARCHAR(255) NOT NULL, card_global_fingerprint VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, card_number VARCHAR(255) NOT NULL, card_exp_year VARCHAR(255) NOT NULL, card_exp_month VARCHAR(255) NOT NULL, name_on_card VARCHAR(255), nickname VARCHAR(255), customer_id VARCHAR(255), duplicate BOOLEAN ); CREATE TABLE mandate ( id SERIAL PRIMARY KEY, mandate_id VARCHAR(255) NOT NULL, customer_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, payment_method_id VARCHAR(255) NOT NULL, mandate_status "MandateStatus" NOT NULL, mandate_type "MandateType" NOT NULL, customer_accepted_at TIMESTAMP, customer_ip_address VARCHAR(255), customer_user_agent VARCHAR(255), network_transaction_id VARCHAR(255), previous_transaction_id VARCHAR(255), created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP ); CREATE TABLE merchant_account ( id SERIAL PRIMARY KEY, merchant_id VARCHAR(255) NOT NULL, api_key VARCHAR(255), return_url VARCHAR(255), enable_payment_response_hash BOOLEAN NOT NULL DEFAULT FALSE, payment_response_hash_key VARCHAR(255) DEFAULT NULL, redirect_to_merchant_with_http_post BOOLEAN NOT NULL DEFAULT FALSE, merchant_name VARCHAR(255), merchant_details JSON, webhook_details JSON, routing_algorithm "RoutingAlgorithm", custom_routing_rules JSON, sub_merchants_enabled BOOLEAN DEFAULT FALSE, parent_merchant_id VARCHAR(255), publishable_key VARCHAR(255) ); CREATE TABLE merchant_connector_account ( id SERIAL PRIMARY KEY, merchant_id VARCHAR(255) NOT NULL, connector_name VARCHAR(255) NOT NULL, connector_account_details JSON NOT NULL, test_mode BOOLEAN, disabled BOOLEAN, merchant_connector_id SERIAL NOT NULL, payment_methods_enabled JSON [ ], connector_type "ConnectorType" NOT NULL DEFAULT 'payment_processor'::"ConnectorType" ); CREATE TABLE payment_attempt ( id SERIAL PRIMARY KEY, payment_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, txn_id VARCHAR(255) NOT NULL, status "AttemptStatus" NOT NULL, amount INTEGER NOT NULL, currency "Currency", save_to_locker BOOLEAN, connector VARCHAR(255) NOT NULL, error_message TEXT, offer_amount INTEGER, surcharge_amount INTEGER, tax_amount INTEGER, payment_method_id VARCHAR(255), payment_method "PaymentMethodType", payment_flow "PaymentFlow", redirect BOOLEAN, connector_transaction_id VARCHAR(255), capture_method "CaptureMethod", capture_on TIMESTAMP, confirm BOOLEAN NOT NULL, authentication_type "AuthenticationType", created_at TIMESTAMP NOT NULL, modified_at TIMESTAMP NOT NULL, last_synced TIMESTAMP ); CREATE TABLE payment_intent ( id SERIAL PRIMARY KEY, payment_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, status "IntentStatus" NOT NULL, amount INTEGER NOT NULL, currency "Currency", amount_captured INTEGER, customer_id VARCHAR(255), description VARCHAR(255), return_url VARCHAR(255), metadata JSONB DEFAULT '{}'::JSONB, connector_id VARCHAR(255), shipping_address_id VARCHAR(255), billing_address_id VARCHAR(255), statement_descriptor_name VARCHAR(255), statement_descriptor_suffix VARCHAR(255), created_at TIMESTAMP NOT NULL, modified_at TIMESTAMP NOT NULL, last_synced TIMESTAMP, setup_future_usage "FutureUsage", off_session BOOLEAN, client_secret VARCHAR(255) ); CREATE TABLE payment_methods ( id SERIAL PRIMARY KEY, customer_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, payment_method_id VARCHAR(255) NOT NULL, accepted_currency "Currency" [ ], scheme VARCHAR(255), token VARCHAR(255), cardholder_name VARCHAR(255), issuer_name VARCHAR(255), issuer_country VARCHAR(255), payer_country TEXT [ ], is_stored BOOLEAN, swift_code VARCHAR(255), direct_debit_token VARCHAR(255), network_transaction_id VARCHAR(255), created_at TIMESTAMP NOT NULL, last_modified TIMESTAMP NOT NULL, payment_method "PaymentMethodType" NOT NULL, payment_method_type "PaymentMethodSubType", payment_method_issuer VARCHAR(255), payment_method_issuer_code "PaymentMethodIssuerCode" ); CREATE TABLE process_tracker ( id VARCHAR(127) PRIMARY KEY, NAME VARCHAR(255), tag TEXT [ ] NOT NULL DEFAULT '{}'::TEXT [ ], runner VARCHAR(255), retry_count INTEGER NOT NULL, schedule_time TIMESTAMP, rule VARCHAR(255) NOT NULL, tracking_data JSON NOT NULL, business_status VARCHAR(255) NOT NULL, status "ProcessTrackerStatus" NOT NULL, event TEXT [ ] NOT NULL DEFAULT '{}'::TEXT [ ], created_at TIMESTAMP NOT NULL DEFAULT now(), updated_at TIMESTAMP NOT NULL DEFAULT now() ); CREATE TABLE refund ( id SERIAL PRIMARY KEY, internal_reference_id VARCHAR(255) NOT NULL, refund_id VARCHAR(255) NOT NULL, payment_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, transaction_id VARCHAR(255) NOT NULL, connector VARCHAR(255) NOT NULL, pg_refund_id VARCHAR(255), external_reference_id VARCHAR(255), refund_type "RefundType" NOT NULL, total_amount INTEGER NOT NULL, currency "Currency" NOT NULL, refund_amount INTEGER NOT NULL, refund_status "RefundStatus" NOT NULL, sent_to_gateway BOOLEAN NOT NULL DEFAULT FALSE, refund_error_message TEXT, metadata JSON, refund_arn VARCHAR(255), created_at TIMESTAMP NOT NULL, modified_at TIMESTAMP NOT NULL, description VARCHAR(255) ); CREATE TABLE temp_card ( id SERIAL PRIMARY KEY, date_created TIMESTAMP NOT NULL, txn_id VARCHAR(255), card_info JSON ); -- Indices CREATE INDEX customers_created_at_index ON customers (created_at); CREATE UNIQUE INDEX merchant_account_api_key_index ON merchant_account (api_key); CREATE UNIQUE INDEX merchant_account_merchant_id_index ON merchant_account (merchant_id); CREATE UNIQUE INDEX merchant_account_publishable_key_index ON merchant_account (publishable_key); CREATE INDEX merchant_connector_account_connector_type_index ON merchant_connector_account (connector_type); CREATE INDEX merchant_connector_account_merchant_id_index ON merchant_connector_account (merchant_id); CREATE UNIQUE INDEX payment_attempt_payment_id_merchant_id_index ON payment_attempt (payment_id, merchant_id); CREATE UNIQUE INDEX payment_intent_payment_id_merchant_id_index ON payment_intent (payment_id, merchant_id); CREATE INDEX payment_methods_created_at_index ON payment_methods (created_at); CREATE INDEX payment_methods_customer_id_index ON payment_methods (customer_id); CREATE INDEX payment_methods_last_modified_index ON payment_methods (last_modified); CREATE INDEX payment_methods_payment_method_id_index ON payment_methods (payment_method_id); CREATE INDEX refund_internal_reference_id_index ON refund (internal_reference_id); CREATE INDEX refund_payment_id_merchant_id_index ON refund (payment_id, merchant_id); CREATE INDEX refund_refund_id_index ON refund (refund_id); CREATE UNIQUE INDEX refund_refund_id_merchant_id_index ON refund (refund_id, merchant_id); CREATE INDEX temp_card_txn_id_index ON temp_card (txn_id); <file_sep> pack="QBP-A" entity="configs" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2022-09-29-084920_create_initial_tables/down.sql" -- Tables DROP TABLE address; DROP TABLE configs; DROP TABLE customers; DROP TABLE events; DROP TABLE locker_mock_up; DROP TABLE mandate; DROP TABLE merchant_account; DROP TABLE merchant_connector_account; DROP TABLE payment_attempt; DROP TABLE payment_intent; DROP TABLE payment_methods; DROP TABLE process_tracker; DROP TABLE refund; DROP TABLE temp_card; -- Types DROP TYPE "AttemptStatus"; DROP TYPE "AuthenticationType"; DROP TYPE "CaptureMethod"; DROP TYPE "ConnectorType"; DROP TYPE "Currency"; DROP TYPE "EventClass"; DROP TYPE "EventObjectType"; DROP TYPE "EventType"; DROP TYPE "FutureUsage"; DROP TYPE "IntentStatus"; DROP TYPE "MandateStatus"; DROP TYPE "MandateType"; DROP TYPE "PaymentFlow"; DROP TYPE "PaymentMethodIssuerCode"; DROP TYPE "PaymentMethodSubType"; DROP TYPE "PaymentMethodType"; DROP TYPE "ProcessTrackerStatus"; DROP TYPE "RefundStatus"; DROP TYPE "RefundType"; DROP TYPE "RoutingAlgorithm"; <file_sep> pack="QBP-A" entity="configs" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_configs.rs" // schema snippet for entity=configs repo=hyperswitch // table: configs columns: [] entities: [configs] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/connector_response.rs<|crate|> diesel_models<|op|> select entity=connector_response repo=hyperswitch tables=connector_response joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-C" entity="connector_response" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/connector_response.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use router_env::{instrument, logger, tracing}; use super::generics; use crate::{ connector_response::{ ConnectorResponse, ConnectorResponseNew, ConnectorResponseUpdate, ConnectorResponseUpdateInternal, }, errors, payment_attempt::{PaymentAttempt, PaymentAttemptUpdate, PaymentAttemptUpdateInternal}, schema::{connector_response::dsl, payment_attempt::dsl as pa_dsl}, PgPooledConn, StorageResult, }; impl ConnectorResponseNew { #[instrument(skip(conn))] pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ConnectorResponse> { let payment_attempt_update = PaymentAttemptUpdate::ConnectorResponse { authentication_data: self.authentication_data.clone(), encoded_data: self.encoded_data.clone(), connector_transaction_id: self.connector_transaction_id.clone(), connector: self.connector_name.clone(), updated_by: self.updated_by.clone(), charge_id: self.charge_id.clone(), }; let _payment_attempt: Result<PaymentAttempt, _> = generics::generic_update_with_unique_predicate_get_result::< <PaymentAttempt as HasTable>::Table, _, _, _, >( conn, pa_dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(pa_dsl::merchant_id.eq(self.merchant_id.to_owned())), PaymentAttemptUpdateInternal::from(payment_attempt_update), ) .await .inspect_err(|err| { logger::error!( "Error while updating payment attempt in connector_response flow {:?}", err ); }); generics::generic_insert(conn, self).await } } impl ConnectorResponse { #[instrument(skip(conn))] pub async fn update( self, conn: &PgPooledConn, connector_response: ConnectorResponseUpdate, ) -> StorageResult<Self> { let payment_attempt_update = match connector_response.clone() { ConnectorResponseUpdate::ResponseUpdate { connector_transaction_id, authentication_data, encoded_data, connector_name, charge_id, updated_by, } => PaymentAttemptUpdate::ConnectorResponse { authentication_data, encoded_data, connector_transaction_id, connector: connector_name, charge_id, updated_by, }, ConnectorResponseUpdate::ErrorUpdate { connector_name, updated_by, } => PaymentAttemptUpdate::ConnectorResponse { authentication_data: None, encoded_data: None, connector_transaction_id: None, connector: connector_name, charge_id: None, updated_by, }, }; let _payment_attempt: Result<PaymentAttempt, _> = generics::generic_update_with_unique_predicate_get_result::< <PaymentAttempt as HasTable>::Table, _, _, _, >( conn, pa_dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(pa_dsl::merchant_id.eq(self.merchant_id.to_owned())), PaymentAttemptUpdateInternal::from(payment_attempt_update), ) .await .inspect_err(|err| { logger::error!( "Error while updating payment attempt in connector_response flow {:?}", err ); }); let connector_response_result = match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id .eq(self.merchant_id.clone()) .and(dsl::payment_id.eq(self.payment_id.clone())) .and(dsl::attempt_id.eq(self.attempt_id.clone())), ConnectorResponseUpdateInternal::from(connector_response), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, }; connector_response_result } #[instrument(skip(conn))] 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> { let connector_response: Self = generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()).and( dsl::payment_id .eq(payment_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ), ) .await?; match generics::generic_find_one::<<PaymentAttempt as HasTable>::Table, _, _>( conn, pa_dsl::payment_id.eq(payment_id.to_owned()).and( pa_dsl::merchant_id .eq(merchant_id.to_owned()) .and(pa_dsl::attempt_id.eq(attempt_id.to_owned())), ), ) .await { Ok::<PaymentAttempt, _>(payment_attempt) => { if payment_attempt.authentication_data != connector_response.authentication_data { logger::error!( "Not Equal pa_authentication_data : {:?}, cr_authentication_data: {:?} ", payment_attempt.authentication_data, connector_response.authentication_data ); } if payment_attempt.encoded_data != connector_response.encoded_data { logger::error!( "Not Equal pa_encoded_data : {:?}, cr_encoded_data: {:?} ", payment_attempt.encoded_data, connector_response.encoded_data ); } if payment_attempt.connector_transaction_id != connector_response.connector_transaction_id { logger::error!( "Not Equal pa_connector_transaction_id : {:?}, cr_connector_transaction_id: {:?} ", payment_attempt.connector_transaction_id, connector_response.connector_transaction_id ); } if payment_attempt.connector != connector_response.connector_name { logger::error!( "Not Equal pa_connector : {:?}, cr_connector_name: {:?} ", payment_attempt.connector, connector_response.connector_name ); } } Err(err) => { logger::error!( "Error while finding payment attempt in connector_response flow {:?}", err ); } } Ok(connector_response) } } <file_sep> pack="QBP-C" entity="connector_response" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-10-13-090450_add_updated_by_for_tables/up.sql" ALTER TABLE payment_intent ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE payment_attempt ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE refund ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE connector_response ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE reverse_lookup ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE address ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; <file_sep> pack="QBP-C" entity="connector_response" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-11-08-144951_drop_connector_response_table/up.sql" -- Your SQL goes here DROP TABLE connector_response; --NOT to run in deployment envs <file_sep> pack="QBP-C" entity="connector_response" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-11-08-144951_drop_connector_response_table/down.sql" -- This file should undo anything in `up.sql` CREATE TABLE connector_response ( id SERIAL PRIMARY KEY, payment_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, txn_id VARCHAR(255) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, modified_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, connector_name VARCHAR(32) NOT NULL, connector_transaction_id VARCHAR(255), authentication_data JSON, encoded_data TEXT ); CREATE UNIQUE INDEX connector_response_id_index ON connector_response (payment_id, merchant_id, txn_id); ALTER TABLE connector_response ALTER COLUMN connector_name DROP NOT NULL; ALTER TABLE connector_response RENAME COLUMN txn_id TO attempt_id; ALTER TABLE connector_response ALTER COLUMN payment_id TYPE VARCHAR(64), ALTER COLUMN merchant_id TYPE VARCHAR(64), ALTER COLUMN attempt_id TYPE VARCHAR(64), ALTER COLUMN connector_name TYPE VARCHAR(64), ALTER COLUMN connector_transaction_id TYPE VARCHAR(128); ALTER TABLE connector_response ALTER COLUMN modified_at DROP DEFAULT; ALTER TABLE connector_response ALTER COLUMN created_at DROP DEFAULT; ALTER TABLE connector_response ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; <file_sep> pack="QBP-C" entity="connector_response" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_connector_response.rs" // schema snippet for entity=connector_response repo=hyperswitch // table: connector_response columns: [] entities: [connector_response] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/customers.rs<|crate|> router<|op|> select entity=customers repo=hyperswitch tables=customers joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="customers" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/customers.rs" use common_enums::ApiVersion; use common_utils::{encryption::Encryption, pii, types::Description}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; #[cfg(all(feature = "v2", feature = "customer_v2"))] use crate::enums::DeleteStatus; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::schema::customers; #[cfg(all(feature = "v2", feature = "customer_v2"))] use crate::schema_v2::customers; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[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, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl CustomerNew { pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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, } } } #[cfg(all(feature = "v2", feature = "customer_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 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(all(feature = "v2", feature = "customer_v2"))] impl CustomerNew { pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } } #[cfg(all(feature = "v2", feature = "customer_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, 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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[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, } #[cfg(all(feature = "v2", feature = "customer_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 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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_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<pii::SecretSerdeValue>, pub address_id: Option<String>, pub default_payment_method_id: Option<Option<String>>, pub updated_by: Option<String>, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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, .. } = 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), ..source } } } #[cfg(all(feature = "v2", feature = "customer_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>, } #[cfg(all(feature = "v2", feature = "customer_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, .. } = 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), ..source } } } <file_sep> pack="QBP-A" entity="customers" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/customers.rs" use common_utils::id_type; #[cfg(all(feature = "v2", feature = "customer_v2"))] use diesel::BoolExpressionMethods; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use diesel::BoolExpressionMethods; use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; // #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::errors; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::schema::customers::dsl; #[cfg(all(feature = "v2", feature = "customer_v2"))] use crate::schema_v2::customers::dsl; use crate::{ customers::{Customer, CustomerNew, CustomerUpdateInternal}, 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>, } // #[cfg(all(feature = "v2", feature = "customer_v2"))] impl Customer { #[cfg(all(feature = "v2", feature = "customer_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(all(feature = "v2", feature = "customer_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 } pub async fn list_by_merchant_id( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, constraints: CustomerListConstraints, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } #[cfg(all(feature = "v2", feature = "customer_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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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(all(feature = "v2", feature = "customer_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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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 } }
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/customers.rs<|crate|> router<|op|> select entity=customers repo=hyperswitch tables=customers joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="customers" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/customers.rs" use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use diesel_models::query::customers::CustomerListConstraints as DieselCustomerListConstraints; use error_stack::ResultExt; use futures::future::try_join_all; use hyperswitch_domain_models::customer; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use router_env::{instrument, tracing}; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage::{self as storage_types, enums::MerchantStorageScheme}, }, }; pub struct CustomerListConstraints { pub limit: u16, pub offset: Option<u32>, } impl From<CustomerListConstraints> for DieselCustomerListConstraints { fn from(value: CustomerListConstraints) -> Self { Self { limit: i64::from(value.limit), offset: value.offset.map(i64::from), } } } #[async_trait::async_trait] pub trait CustomerInterface where customer::Customer: Conversion<DstType = storage_types::Customer, NewDstType = storage_types::CustomerNew>, { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError>; #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[allow(clippy::too_many_arguments)] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: customer::Customer, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, constraints: CustomerListConstraints, ) -> CustomResult<Vec<customer::Customer>, errors::StorageError>; async fn insert_customer( &self, customer_data: customer::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; #[cfg(all(feature = "v2", feature = "customer_v2"))] #[allow(clippy::too_many_arguments)] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: customer::Customer, merchant_id: &id_type::MerchantId, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; } #[cfg(feature = "kv_store")] mod storage { use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use diesel_models::kv; use error_stack::{report, ResultExt}; use futures::future::try_join_all; use hyperswitch_domain_models::customer; use masking::PeekInterface; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::CustomerInterface; use crate::{ connection, core::{ customers::REDACTED, errors::{self, CustomResult}, }, services::Store, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage::{self as storage_types, enums::MerchantStorageScheme}, }, utils::db_utils, }; #[async_trait::async_trait] impl CustomerInterface for Store { #[instrument(skip_all)] // check customer not found in kv and fallback to db #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|err| report!(errors::StorageError::from(err))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let maybe_customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( // check for ValueNotFound async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, )) .await? .try_into_hget() .map(Some) }, database_call, )) .await } }?; let maybe_result = maybe_customer .async_map(|c| async { c.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), }) } #[instrument(skip_all)] // check customer not found in kv and fallback to db #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|err| report!(errors::StorageError::from(err))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let maybe_customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( // check for ValueNotFound async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, )) .await? .try_into_hget() .map(Some) }, database_call, )) .await } }?; let maybe_result = maybe_customer .async_map(|customer| async { customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; Ok(maybe_result) } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_optional_by_merchant_id_merchant_reference_id( &conn, merchant_reference_id, merchant_id, ) .await .map_err(|err| report!(errors::StorageError::from(err))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let maybe_customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdMerchantReferenceId { merchant_id, merchant_reference_id: merchant_reference_id.get_string_repr(), }; let field = format!("cust_{}", merchant_reference_id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( // check for ValueNotFound async { kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, ) .await? .try_into_hget() .map(Some) }, database_call, )) .await } }?; let maybe_result = maybe_customer .async_map(|c| async { c.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), }) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: customer::Customer, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let customer = Conversion::convert(customer) .await .change_context(errors::StorageError::EncryptionError)?; let database_call = || async { storage_types::Customer::update_by_customer_id_merchant_id( &conn, customer_id.clone(), merchant_id.clone(), customer_update.clone().into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let key = PartitionKey::MerchantIdCustomerId { merchant_id: &merchant_id, customer_id: &customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Update(key.clone(), &field, customer.updated_by.as_deref()), )) .await; let updated_object = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let updated_customer = diesel_models::CustomerUpdateInternal::from(customer_update.clone()) .apply_changeset(customer.clone()); let redis_value = serde_json::to_string(&updated_customer) .change_context(errors::StorageError::KVError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::CustomerUpdate( kv::CustomerUpdateMems { orig: customer, update_data: customer_update.into(), }, )), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<diesel_models::Customer>( (&field, redis_value), redis_entry, ), key, )) .await .change_context(errors::StorageError::KVError)? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_customer) } }; updated_object? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_by_merchant_reference_id_merchant_id( &conn, merchant_reference_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdMerchantReferenceId { merchant_id, merchant_reference_id: merchant_reference_id.get_string_repr(), }; let field = format!("cust_{}", merchant_reference_id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( async { kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, ) .await? .try_into_hget() }, database_call, )) .await } }?; let result: customer::Customer = customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; match result.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(result), } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } }?; let result: customer::Customer = customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; match result.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(result), } } #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, constraints: super::CustomerListConstraints, ) -> CustomResult<Vec<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let customer_list_constraints = diesel_models::query::customers::CustomerListConstraints::from(constraints); let encrypted_customers = storage_types::Customer::list_by_merchant_id( &conn, merchant_id, customer_list_constraints, ) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let customers = try_join_all(encrypted_customers.into_iter().map( |encrypted_customer| async { encrypted_customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }, )) .await?; Ok(customers) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn insert_customer( &self, customer_data: customer::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let id = customer_data.id.clone(); let mut new_customer = customer_data .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Insert, )) .await; new_customer.update_storage_scheme(storage_scheme); let create_customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; new_customer .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } MerchantStorageScheme::RedisKv => { let key = PartitionKey::GlobalId { id: id.get_string_repr(), }; let field = format!("cust_{}", id.get_string_repr()); let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Customer(new_customer.clone())), }, }; let storage_customer = new_customer.into(); match kv_wrapper::<diesel_models::Customer, _, _>( self, KvOperation::HSetNx::<diesel_models::Customer>( &field, &storage_customer, redis_entry, ), key, ) .await .change_context(errors::StorageError::KVError)? .try_into_hsetnx() { Ok(redis_interface::HsetnxReply::KeyNotSet) => { Err(report!(errors::StorageError::DuplicateValue { entity: "customer", key: Some(id.get_string_repr().to_owned()), })) } Ok(redis_interface::HsetnxReply::KeySet) => Ok(storage_customer), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } }?; create_customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn insert_customer( &self, customer_data: customer::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let customer_id = customer_data.customer_id.clone(); let merchant_id = customer_data.merchant_id.clone(); let mut new_customer = customer_data .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Insert, )) .await; new_customer.update_storage_scheme(storage_scheme); let create_customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; new_customer .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdCustomerId { merchant_id: &merchant_id, customer_id: &customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Customer(new_customer.clone())), }, }; let storage_customer = new_customer.into(); match Box::pin(kv_wrapper::<diesel_models::Customer, _, _>( self, KvOperation::HSetNx::<diesel_models::Customer>( &field, &storage_customer, redis_entry, ), key, )) .await .change_context(errors::StorageError::KVError)? .try_into_hsetnx() { Ok(redis_interface::HsetnxReply::KeyNotSet) => { Err(report!(errors::StorageError::DuplicateValue { entity: "customer", key: Some(customer_id.get_string_repr().to_string()), })) } Ok(redis_interface::HsetnxReply::KeySet) => Ok(storage_customer), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } }?; create_customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Customer::delete_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, _merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_by_global_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::GlobalId { id: id.get_string_repr(), }; let field = format!("cust_{}", id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( async { kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, ) .await? .try_into_hget() }, database_call, )) .await } }?; let result: customer::Customer = customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; if result.status == common_enums::DeleteStatus::Redacted { Err(report!(errors::StorageError::CustomerRedacted)) } else { Ok(result) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: customer::Customer, _merchant_id: &id_type::MerchantId, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let customer = Conversion::convert(customer) .await .change_context(errors::StorageError::EncryptionError)?; let database_call = || async { storage_types::Customer::update_by_id( &conn, id.clone(), customer_update.clone().into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let key = PartitionKey::GlobalId { id: id.get_string_repr(), }; let field = format!("cust_{}", id.get_string_repr()); let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Update(key.clone(), &field, customer.updated_by.as_deref()), )) .await; let updated_object = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let updated_customer = diesel_models::CustomerUpdateInternal::from(customer_update.clone()) .apply_changeset(customer.clone()); let redis_value = serde_json::to_string(&updated_customer) .change_context(errors::StorageError::KVError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::CustomerUpdate( kv::CustomerUpdateMems { orig: customer, update_data: customer_update.into(), }, )), }, }; kv_wrapper::<(), _, _>( self, KvOperation::Hset::<diesel_models::Customer>( (&field, redis_value), redis_entry, ), key, ) .await .change_context(errors::StorageError::KVError)? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_customer) } }; updated_object? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } } } #[cfg(not(feature = "kv_store"))] mod storage { use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use futures::future::try_join_all; use hyperswitch_domain_models::customer; use masking::PeekInterface; use router_env::{instrument, tracing}; use super::CustomerInterface; use crate::{ connection, core::{ customers::REDACTED, errors::{self, CustomResult}, }, services::Store, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage::{self as storage_types, enums::MerchantStorageScheme}, }, }; #[async_trait::async_trait] impl CustomerInterface for Store { #[instrument(skip_all)] #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let maybe_customer: Option<customer::Customer> = storage_types::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .async_map(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; maybe_customer.map_or(Ok(None), |customer| { // in the future, once #![feature(is_some_and)] is stable, we can make this more concise: // `if customer.name.is_some_and(|ref name| name == REDACTED) ...` match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), } }) } #[instrument(skip_all)] #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let maybe_customer: Option<customer::Customer> = storage_types::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .async_map(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; Ok(maybe_customer) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let maybe_customer: Option<customer::Customer> = storage_types::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .async_map(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; maybe_customer.map_or(Ok(None), |customer| { // in the future, once #![feature(is_some_and)] is stable, we can make this more concise: // `if customer.name.is_some_and(|ref name| name == REDACTED) ...` match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), } }) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, _customer: customer::Customer, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Customer::update_by_customer_id_merchant_id( &conn, customer_id, merchant_id.clone(), customer_update.into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.into()) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let customer: customer::Customer = storage_types::Customer::find_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await?; match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(customer), } } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let customer: customer::Customer = storage_types::Customer::find_by_merchant_reference_id_merchant_id( &conn, merchant_reference_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await?; match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(customer), } } #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, constraints: super::CustomerListConstraints, ) -> CustomResult<Vec<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let customer_list_constraints = diesel_models::query::customers::CustomerListConstraints::from(constraints); let encrypted_customers = storage_types::Customer::list_by_merchant_id( &conn, merchant_id, customer_list_constraints, ) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let customers = try_join_all(encrypted_customers.into_iter().map( |encrypted_customer| async { encrypted_customer .convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }, )) .await?; Ok(customers) } #[instrument(skip_all)] async fn insert_customer( &self, customer_data: customer::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; customer_data .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Customer::delete_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[allow(clippy::too_many_arguments)] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: customer::Customer, merchant_id: &id_type::MerchantId, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Customer::update_by_global_id(&conn, id, customer_update.into()) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let customer: customer::Customer = storage_types::Customer::find_by_global_id(&conn, customer_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await?; match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(customer), } } } } #[async_trait::async_trait] impl CustomerInterface for MockDb { #[allow(clippy::panic)] #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let customers = self.customers.lock().await; let customer = customers .iter() .find(|customer| { customer.customer_id == *customer_id && &customer.merchant_id == merchant_id }) .cloned(); customer .async_map(|c| async { c.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose() } #[allow(clippy::panic)] #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let customers = self.customers.lock().await; let customer = customers .iter() .find(|customer| { customer.customer_id == *customer_id && &customer.merchant_id == merchant_id }) .cloned(); customer .async_map(|c| async { c.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose() } #[allow(clippy::panic)] #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { todo!() } async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, constraints: CustomerListConstraints, ) -> CustomResult<Vec<customer::Customer>, errors::StorageError> { let customers = self.customers.lock().await; let customers = try_join_all( customers .iter() .filter(|customer| customer.merchant_id == *merchant_id) .take(usize::from(constraints.limit)) .skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0)) .map(|customer| async { customer .to_owned() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }), ) .await?; Ok(customers) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, _state: &KeyManagerState, _customer_id: id_type::CustomerId, _merchant_id: id_type::MerchantId, _customer: customer::Customer, _customer_update: storage_types::CustomerUpdate, _key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_by_customer_id_merchant_id( &self, _state: &KeyManagerState, _customer_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, _key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_customer_by_merchant_reference_id_merchant_id( &self, _state: &KeyManagerState, _merchant_reference_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, _key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } #[allow(clippy::panic)] async fn insert_customer( &self, customer_data: customer::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let mut customers = self.customers.lock().await; let customer = Conversion::convert(customer_data) .await .change_context(errors::StorageError::EncryptionError)?; customers.push(customer.clone()); customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn delete_customer_by_customer_id_merchant_id( &self, _customer_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[allow(clippy::too_many_arguments)] async fn update_customer_by_global_id( &self, _state: &KeyManagerState, _id: &id_type::GlobalCustomerId, _customer: customer::Customer, _merchant_id: &id_type::MerchantId, _customer_update: storage_types::CustomerUpdate, _key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_customer_by_global_id( &self, _state: &KeyManagerState, _id: &id_type::GlobalCustomerId, _merchant_id: &id_type::MerchantId, _key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } } <file_sep> pack="QBP-A" entity="customers" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql" ALTER TABLE ORGANIZATION ADD COLUMN org_id VARCHAR(32), ADD COLUMN org_name TEXT; ALTER TABLE merchant_account ADD COLUMN merchant_id VARCHAR(64), ADD COLUMN return_url VARCHAR(255), ADD COLUMN enable_payment_response_hash BOOLEAN DEFAULT FALSE, ADD COLUMN payment_response_hash_key VARCHAR(255), ADD COLUMN redirect_to_merchant_with_http_post BOOLEAN DEFAULT FALSE, ADD COLUMN sub_merchants_enabled BOOLEAN DEFAULT FALSE, ADD COLUMN parent_merchant_id VARCHAR(64), ADD COLUMN locker_id VARCHAR(64), ADD COLUMN intent_fulfillment_time BIGINT, ADD COLUMN default_profile VARCHAR(64), ADD COLUMN payment_link_config JSONB NULL, ADD COLUMN pm_collect_link_config JSONB NULL, ADD COLUMN is_recon_enabled BOOLEAN, ADD COLUMN webhook_details JSON NULL, ADD COLUMN routing_algorithm JSON, ADD COLUMN frm_routing_algorithm JSONB, ADD COLUMN payout_routing_algorithm JSONB; -- The default value is for temporary purpose only ALTER TABLE merchant_account ADD COLUMN primary_business_details JSON; ALTER TABLE business_profile ADD COLUMN profile_id VARCHAR(64), ADD COLUMN routing_algorithm JSON DEFAULT NULL, ADD COLUMN intent_fulfillment_time BIGINT DEFAULT NULL, ADD COLUMN frm_routing_algorithm JSONB DEFAULT NULL, ADD COLUMN payout_routing_algorithm JSONB DEFAULT NULL; ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS business_country "CountryAlpha2", ADD COLUMN IF NOT EXISTS business_label VARCHAR(255), ADD COLUMN IF NOT EXISTS business_sub_label VARCHAR(64), ADD COLUMN IF NOT EXISTS test_mode BOOLEAN, ADD COLUMN IF NOT EXISTS frm_configs jsonb, ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(128); ALTER TABLE customers ADD COLUMN customer_id VARCHAR(64), ADD COLUMN address_id VARCHAR(64); ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS payment_id VARCHAR(64), ADD COLUMN connector_id VARCHAR(64), ADD COLUMN shipping_address_id VARCHAR(64), ADD COLUMN billing_address_id VARCHAR(64), ADD COLUMN shipping_details BYTEA, ADD COLUMN billing_details BYTEA, ADD COLUMN statement_descriptor_suffix VARCHAR(255), ADD COLUMN business_country "CountryAlpha2", ADD COLUMN business_label VARCHAR(64), ADD COLUMN incremental_authorization_allowed BOOLEAN, ADD COLUMN merchant_decision VARCHAR(64), ADD COLUMN fingerprint_id VARCHAR(64), ADD COLUMN statement_descriptor_name VARCHAR(255), ADD COLUMN amount_to_capture BIGINT, ADD COLUMN off_session BOOLEAN, ADD COLUMN payment_confirm_source "PaymentSource", ADD COLUMN merchant_order_reference_id VARCHAR(255), ADD COLUMN is_payment_processor_token_flow BOOLEAN, ADD COLUMN charges jsonb; ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS attempt_id VARCHAR(64), ADD COLUMN amount bigint, ADD COLUMN currency "Currency", ADD COLUMN save_to_locker BOOLEAN, ADD COLUMN offer_amount bigint, ADD COLUMN payment_method VARCHAR, ADD COLUMN connector_transaction_id VARCHAR(128), ADD COLUMN connector_transaction_data VARCHAR(512), ADD COLUMN processor_transaction_data text, ADD COLUMN capture_method "CaptureMethod", ADD COLUMN capture_on TIMESTAMP, ADD COLUMN mandate_id VARCHAR(64), ADD COLUMN payment_method_type VARCHAR(64), ADD COLUMN business_sub_label VARCHAR(64), ADD COLUMN mandate_details JSONB, ADD COLUMN mandate_data JSONB, ADD COLUMN tax_amount bigint, ADD COLUMN straight_through_algorithm JSONB, ADD COLUMN confirm BOOLEAN, ADD COLUMN authentication_data JSON, ADD COLUMN payment_method_billing_address_id VARCHAR(64), ADD COLUMN connector_mandate_detail JSONB, ADD COLUMN charge_id VARCHAR(64); -- Create the index which was dropped because of dropping the column CREATE INDEX payment_attempt_connector_transaction_id_merchant_id_index ON payment_attempt (connector_transaction_id, merchant_id); CREATE UNIQUE INDEX payment_attempt_payment_id_merchant_id_attempt_id_index ON payment_attempt (payment_id, merchant_id, attempt_id); -- Payment Methods CREATE TYPE "PaymentMethodIssuerCode" AS ENUM ( 'jp_hdfc', 'jp_icici', 'jp_googlepay', 'jp_applepay', 'jp_phonepe', 'jp_wechat', 'jp_sofort', 'jp_giropay', 'jp_sepa', 'jp_bacs' ); ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS payment_method_id VARCHAR(64), ADD COLUMN IF NOT EXISTS accepted_currency "Currency" [ ], ADD COLUMN IF NOT EXISTS scheme VARCHAR(32), ADD COLUMN IF NOT EXISTS token VARCHAR(128), ADD COLUMN IF NOT EXISTS cardholder_name VARCHAR(255), ADD COLUMN IF NOT EXISTS issuer_name VARCHAR(64), ADD COLUMN IF NOT EXISTS issuer_country VARCHAR(64), ADD COLUMN IF NOT EXISTS payer_country TEXT [ ], ADD COLUMN IF NOT EXISTS is_stored BOOLEAN, ADD COLUMN IF NOT EXISTS direct_debit_token VARCHAR(128), ADD COLUMN IF NOT EXISTS swift_code VARCHAR(32), ADD COLUMN IF NOT EXISTS payment_method_issuer VARCHAR(128), ADD COLUMN IF NOT EXISTS metadata JSON, ADD COLUMN IF NOT EXISTS payment_method VARCHAR, ADD COLUMN IF NOT EXISTS payment_method_type VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_issuer_code "PaymentMethodIssuerCode"; ALTER TABLE refund ADD COLUMN connector_refund_data VARCHAR(512), ADD COLUMN connector_transaction_data VARCHAR(512); ALTER TABLE captures ADD COLUMN connector_capture_data VARCHAR(512); ALTER TABLE refund ADD COLUMN IF NOT EXISTS internal_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS refund_id VARCHAR(64), ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(64); <file_sep> pack="QBP-A" entity="customers" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR` column instead of `SERIAL` column for tables that already have it. -- It must be ensured that the deployed version of the application does not include the `id` column in any of its queries. -- Drop the id column as this will be used later as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account DROP COLUMN IF EXISTS id; ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS id; ------------------------ Customers ----------------------- ALTER TABLE customers DROP COLUMN IF EXISTS id; ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent DROP COLUMN id; ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund ----------------------- ALTER TABLE refund DROP COLUMN IF EXISTS id; ------------------------ BlockList ----------------------- ALTER TABLE blocklist DROP COLUMN IF EXISTS id; ------------------------ Roles ----------------------- ALTER TABLE roles DROP COLUMN IF EXISTS id; ------------------------ Users ----------------------- ALTER TABLE users DROP COLUMN IF EXISTS id; <file_sep> pack="QBP-A" entity="customers" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/down.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR(64)` column for tables that had it removed. -- It must be ensured that the deployed version of the application includes the `id` column in any of its queries. -- Re-create the id column as this was used as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account ADD COLUMN id VARCHAR(64); ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account ADD COLUMN id VARCHAR(64); ------------------------ Customers ----------------------- ALTER TABLE customers ADD COLUMN id VARCHAR(64); ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent ADD COLUMN id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt ADD COLUMN id VARCHAR(64); ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods ADD COLUMN id VARCHAR(64); ------------------------ Address ----------------------- ALTER TABLE address ADD COLUMN id VARCHAR(64); ------------------------ Dispute ----------------------- ALTER TABLE dispute ADD COLUMN id VARCHAR(64); ------------------------ Mandate ----------------------- ALTER TABLE mandate ADD COLUMN id VARCHAR(64); ------------------------ Refund ----------------------- ALTER TABLE refund ADD COLUMN id VARCHAR(64); ------------------------ BlockList ----------------------- ALTER TABLE blocklist ADD COLUMN id VARCHAR(64); ------------------------ Roles ----------------------- ALTER TABLE roles ADD COLUMN id VARCHAR(64); ------------------------ Users ----------------------- ALTER TABLE users ADD COLUMN id VARCHAR(64); <file_sep> pack="QBP-A" entity="customers" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_customers.rs" // schema snippet for entity=customers repo=hyperswitch // table: customers columns: [] entities: [customers] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/customers.rs<|crate|> storage_impl<|op|> select entity=customers repo=hyperswitch tables=customers joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="customers" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/customers.rs" use common_enums::ApiVersion; use common_utils::{encryption::Encryption, pii, types::Description}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; #[cfg(all(feature = "v2", feature = "customer_v2"))] use crate::enums::DeleteStatus; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::schema::customers; #[cfg(all(feature = "v2", feature = "customer_v2"))] use crate::schema_v2::customers; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[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, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl CustomerNew { pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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, } } } #[cfg(all(feature = "v2", feature = "customer_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 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(all(feature = "v2", feature = "customer_v2"))] impl CustomerNew { pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } } #[cfg(all(feature = "v2", feature = "customer_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, 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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[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, } #[cfg(all(feature = "v2", feature = "customer_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 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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_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<pii::SecretSerdeValue>, pub address_id: Option<String>, pub default_payment_method_id: Option<Option<String>>, pub updated_by: Option<String>, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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, .. } = 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), ..source } } } #[cfg(all(feature = "v2", feature = "customer_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>, } #[cfg(all(feature = "v2", feature = "customer_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, .. } = 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), ..source } } } <file_sep> pack="QBP-B" entity="customers" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/customers.rs" use common_utils::id_type; #[cfg(all(feature = "v2", feature = "customer_v2"))] use diesel::BoolExpressionMethods; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use diesel::BoolExpressionMethods; use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; // #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::errors; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::schema::customers::dsl; #[cfg(all(feature = "v2", feature = "customer_v2"))] use crate::schema_v2::customers::dsl; use crate::{ customers::{Customer, CustomerNew, CustomerUpdateInternal}, 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>, } // #[cfg(all(feature = "v2", feature = "customer_v2"))] impl Customer { #[cfg(all(feature = "v2", feature = "customer_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(all(feature = "v2", feature = "customer_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 } pub async fn list_by_merchant_id( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, constraints: CustomerListConstraints, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } #[cfg(all(feature = "v2", feature = "customer_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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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(all(feature = "v2", feature = "customer_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(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] 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_sep> pack="QBP-B" entity="customers" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/customers.rs" use diesel_models::customers::Customer; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Customer {} <file_sep> pack="QBP-B" entity="customers" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql" ALTER TABLE ORGANIZATION ADD COLUMN org_id VARCHAR(32), ADD COLUMN org_name TEXT; ALTER TABLE merchant_account ADD COLUMN merchant_id VARCHAR(64), ADD COLUMN return_url VARCHAR(255), ADD COLUMN enable_payment_response_hash BOOLEAN DEFAULT FALSE, ADD COLUMN payment_response_hash_key VARCHAR(255), ADD COLUMN redirect_to_merchant_with_http_post BOOLEAN DEFAULT FALSE, ADD COLUMN sub_merchants_enabled BOOLEAN DEFAULT FALSE, ADD COLUMN parent_merchant_id VARCHAR(64), ADD COLUMN locker_id VARCHAR(64), ADD COLUMN intent_fulfillment_time BIGINT, ADD COLUMN default_profile VARCHAR(64), ADD COLUMN payment_link_config JSONB NULL, ADD COLUMN pm_collect_link_config JSONB NULL, ADD COLUMN is_recon_enabled BOOLEAN, ADD COLUMN webhook_details JSON NULL, ADD COLUMN routing_algorithm JSON, ADD COLUMN frm_routing_algorithm JSONB, ADD COLUMN payout_routing_algorithm JSONB; -- The default value is for temporary purpose only ALTER TABLE merchant_account ADD COLUMN primary_business_details JSON; ALTER TABLE business_profile ADD COLUMN profile_id VARCHAR(64), ADD COLUMN routing_algorithm JSON DEFAULT NULL, ADD COLUMN intent_fulfillment_time BIGINT DEFAULT NULL, ADD COLUMN frm_routing_algorithm JSONB DEFAULT NULL, ADD COLUMN payout_routing_algorithm JSONB DEFAULT NULL; ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS business_country "CountryAlpha2", ADD COLUMN IF NOT EXISTS business_label VARCHAR(255), ADD COLUMN IF NOT EXISTS business_sub_label VARCHAR(64), ADD COLUMN IF NOT EXISTS test_mode BOOLEAN, ADD COLUMN IF NOT EXISTS frm_configs jsonb, ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(128); ALTER TABLE customers ADD COLUMN customer_id VARCHAR(64), ADD COLUMN address_id VARCHAR(64); ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS payment_id VARCHAR(64), ADD COLUMN connector_id VARCHAR(64), ADD COLUMN shipping_address_id VARCHAR(64), ADD COLUMN billing_address_id VARCHAR(64), ADD COLUMN shipping_details BYTEA, ADD COLUMN billing_details BYTEA, ADD COLUMN statement_descriptor_suffix VARCHAR(255), ADD COLUMN business_country "CountryAlpha2", ADD COLUMN business_label VARCHAR(64), ADD COLUMN incremental_authorization_allowed BOOLEAN, ADD COLUMN merchant_decision VARCHAR(64), ADD COLUMN fingerprint_id VARCHAR(64), ADD COLUMN statement_descriptor_name VARCHAR(255), ADD COLUMN amount_to_capture BIGINT, ADD COLUMN off_session BOOLEAN, ADD COLUMN payment_confirm_source "PaymentSource", ADD COLUMN merchant_order_reference_id VARCHAR(255), ADD COLUMN is_payment_processor_token_flow BOOLEAN, ADD COLUMN charges jsonb; ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS attempt_id VARCHAR(64), ADD COLUMN amount bigint, ADD COLUMN currency "Currency", ADD COLUMN save_to_locker BOOLEAN, ADD COLUMN offer_amount bigint, ADD COLUMN payment_method VARCHAR, ADD COLUMN connector_transaction_id VARCHAR(128), ADD COLUMN connector_transaction_data VARCHAR(512), ADD COLUMN processor_transaction_data text, ADD COLUMN capture_method "CaptureMethod", ADD COLUMN capture_on TIMESTAMP, ADD COLUMN mandate_id VARCHAR(64), ADD COLUMN payment_method_type VARCHAR(64), ADD COLUMN business_sub_label VARCHAR(64), ADD COLUMN mandate_details JSONB, ADD COLUMN mandate_data JSONB, ADD COLUMN tax_amount bigint, ADD COLUMN straight_through_algorithm JSONB, ADD COLUMN confirm BOOLEAN, ADD COLUMN authentication_data JSON, ADD COLUMN payment_method_billing_address_id VARCHAR(64), ADD COLUMN connector_mandate_detail JSONB, ADD COLUMN charge_id VARCHAR(64); -- Create the index which was dropped because of dropping the column CREATE INDEX payment_attempt_connector_transaction_id_merchant_id_index ON payment_attempt (connector_transaction_id, merchant_id); CREATE UNIQUE INDEX payment_attempt_payment_id_merchant_id_attempt_id_index ON payment_attempt (payment_id, merchant_id, attempt_id); -- Payment Methods CREATE TYPE "PaymentMethodIssuerCode" AS ENUM ( 'jp_hdfc', 'jp_icici', 'jp_googlepay', 'jp_applepay', 'jp_phonepe', 'jp_wechat', 'jp_sofort', 'jp_giropay', 'jp_sepa', 'jp_bacs' ); ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS payment_method_id VARCHAR(64), ADD COLUMN IF NOT EXISTS accepted_currency "Currency" [ ], ADD COLUMN IF NOT EXISTS scheme VARCHAR(32), ADD COLUMN IF NOT EXISTS token VARCHAR(128), ADD COLUMN IF NOT EXISTS cardholder_name VARCHAR(255), ADD COLUMN IF NOT EXISTS issuer_name VARCHAR(64), ADD COLUMN IF NOT EXISTS issuer_country VARCHAR(64), ADD COLUMN IF NOT EXISTS payer_country TEXT [ ], ADD COLUMN IF NOT EXISTS is_stored BOOLEAN, ADD COLUMN IF NOT EXISTS direct_debit_token VARCHAR(128), ADD COLUMN IF NOT EXISTS swift_code VARCHAR(32), ADD COLUMN IF NOT EXISTS payment_method_issuer VARCHAR(128), ADD COLUMN IF NOT EXISTS metadata JSON, ADD COLUMN IF NOT EXISTS payment_method VARCHAR, ADD COLUMN IF NOT EXISTS payment_method_type VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_issuer_code "PaymentMethodIssuerCode"; ALTER TABLE refund ADD COLUMN connector_refund_data VARCHAR(512), ADD COLUMN connector_transaction_data VARCHAR(512); ALTER TABLE captures ADD COLUMN connector_capture_data VARCHAR(512); ALTER TABLE refund ADD COLUMN IF NOT EXISTS internal_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS refund_id VARCHAR(64), ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(64); <file_sep> pack="QBP-B" entity="customers" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR` column instead of `SERIAL` column for tables that already have it. -- It must be ensured that the deployed version of the application does not include the `id` column in any of its queries. -- Drop the id column as this will be used later as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account DROP COLUMN IF EXISTS id; ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS id; ------------------------ Customers ----------------------- ALTER TABLE customers DROP COLUMN IF EXISTS id; ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent DROP COLUMN id; ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund ----------------------- ALTER TABLE refund DROP COLUMN IF EXISTS id; ------------------------ BlockList ----------------------- ALTER TABLE blocklist DROP COLUMN IF EXISTS id; ------------------------ Roles ----------------------- ALTER TABLE roles DROP COLUMN IF EXISTS id; ------------------------ Users ----------------------- ALTER TABLE users DROP COLUMN IF EXISTS id; <file_sep> pack="QBP-B" entity="customers" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/down.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR(64)` column for tables that had it removed. -- It must be ensured that the deployed version of the application includes the `id` column in any of its queries. -- Re-create the id column as this was used as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account ADD COLUMN id VARCHAR(64); ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account ADD COLUMN id VARCHAR(64); ------------------------ Customers ----------------------- ALTER TABLE customers ADD COLUMN id VARCHAR(64); ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent ADD COLUMN id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt ADD COLUMN id VARCHAR(64); ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods ADD COLUMN id VARCHAR(64); ------------------------ Address ----------------------- ALTER TABLE address ADD COLUMN id VARCHAR(64); ------------------------ Dispute ----------------------- ALTER TABLE dispute ADD COLUMN id VARCHAR(64); ------------------------ Mandate ----------------------- ALTER TABLE mandate ADD COLUMN id VARCHAR(64); ------------------------ Refund ----------------------- ALTER TABLE refund ADD COLUMN id VARCHAR(64); ------------------------ BlockList ----------------------- ALTER TABLE blocklist ADD COLUMN id VARCHAR(64); ------------------------ Roles ----------------------- ALTER TABLE roles ADD COLUMN id VARCHAR(64); ------------------------ Users ----------------------- ALTER TABLE users ADD COLUMN id VARCHAR(64); <file_sep> pack="QBP-B" entity="customers" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_customers.rs" // schema snippet for entity=customers repo=hyperswitch // table: customers columns: [] entities: [customers] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/dashboard_metadata.rs<|crate|> router<|op|> select entity=dashboard_metadata repo=hyperswitch tables=dashboard_metadata joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="dashboard_metadata" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/user/dashboard_metadata.rs" use common_utils::id_type; use diesel::{query_builder::AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; use crate::{enums, schema::dashboard_metadata}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = dashboard_metadata, check_for_backend(diesel::pg::Pg))] pub struct DashboardMetadata { pub id: i32, pub user_id: Option<String>, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, pub data_key: enums::DashboardMetadata, pub data_value: Secret<serde_json::Value>, pub created_by: String, pub created_at: PrimitiveDateTime, pub last_modified_by: String, pub last_modified_at: PrimitiveDateTime, } #[derive( router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay, AsChangeset, )] #[diesel(table_name = dashboard_metadata)] pub struct DashboardMetadataNew { pub user_id: Option<String>, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, pub data_key: enums::DashboardMetadata, pub data_value: Secret<serde_json::Value>, pub created_by: String, pub created_at: PrimitiveDateTime, pub last_modified_by: String, pub last_modified_at: PrimitiveDateTime, } #[derive( router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay, AsChangeset, )] #[diesel(table_name = dashboard_metadata)] pub struct DashboardMetadataUpdateInternal { pub data_key: enums::DashboardMetadata, pub data_value: Secret<serde_json::Value>, pub last_modified_by: String, pub last_modified_at: PrimitiveDateTime, } #[derive(Debug)] pub enum DashboardMetadataUpdate { UpdateData { data_key: enums::DashboardMetadata, data_value: Secret<serde_json::Value>, last_modified_by: String, }, } impl From<DashboardMetadataUpdate> for DashboardMetadataUpdateInternal { fn from(metadata_update: DashboardMetadataUpdate) -> Self { let last_modified_at = common_utils::date_time::now(); match metadata_update { DashboardMetadataUpdate::UpdateData { data_key, data_value, last_modified_by, } => Self { data_key, data_value, last_modified_by, last_modified_at, }, } } } <file_sep> pack="QBP-A" entity="dashboard_metadata" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/dashboard_metadata.rs" use common_utils::id_type; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use crate::{ enums, query::generics, schema::dashboard_metadata::dsl, user::dashboard_metadata::{ DashboardMetadata, DashboardMetadataNew, DashboardMetadataUpdate, DashboardMetadataUpdateInternal, }, PgPooledConn, StorageResult, }; impl DashboardMetadataNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<DashboardMetadata> { generics::generic_insert(conn, self).await } } impl DashboardMetadata { pub async fn update( conn: &PgPooledConn, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: DashboardMetadataUpdate, ) -> StorageResult<Self> { let predicate = dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::org_id.eq(org_id.to_owned())) .and(dsl::data_key.eq(data_key.to_owned())); if let Some(uid) = user_id { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, predicate.and(dsl::user_id.eq(uid)), DashboardMetadataUpdateInternal::from(dashboard_metadata_update), ) .await } else { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, predicate.and(dsl::user_id.is_null()), DashboardMetadataUpdateInternal::from(dashboard_metadata_update), ) .await } } pub async fn find_user_scoped_dashboard_metadata( conn: &PgPooledConn, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_types: Vec<enums::DashboardMetadata>, ) -> StorageResult<Vec<Self>> { let predicate = dsl::user_id .eq(user_id) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::org_id.eq(org_id)) .and(dsl::data_key.eq_any(data_types)); generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, predicate, None, None, Some(dsl::last_modified_at.asc()), ) .await } pub async fn find_merchant_scoped_dashboard_metadata( conn: &PgPooledConn, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_types: Vec<enums::DashboardMetadata>, ) -> StorageResult<Vec<Self>> { let predicate = dsl::merchant_id .eq(merchant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::data_key.eq_any(data_types)); generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, predicate, None, None, Some(dsl::last_modified_at.asc()), ) .await } pub async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( conn: &PgPooledConn, user_id: String, merchant_id: id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::user_id .eq(user_id) .and(dsl::merchant_id.eq(merchant_id)), ) .await } pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( conn: &PgPooledConn, user_id: String, merchant_id: id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::user_id .eq(user_id) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::data_key.eq(data_key)), ) .await } } <file_sep> pack="QBP-A" entity="dashboard_metadata" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/dashboard_metadata.rs" use common_utils::id_type; use diesel_models::{enums, user::dashboard_metadata as storage}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use storage_impl::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait DashboardMetadataInterface { async fn insert_metadata( &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>; async fn update_metadata( &self, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>; async fn find_user_scoped_dashboard_metadata( &self, user_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>; async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>; async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError>; async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &self, user_id: &str, merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>; } #[async_trait::async_trait] impl DashboardMetadataInterface for Store { #[instrument(skip_all)] async fn insert_metadata( &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; metadata .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_metadata( &self, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DashboardMetadata::update( &conn, user_id, merchant_id, org_id, data_key, dashboard_metadata_update, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_scoped_dashboard_metadata( &self, user_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::DashboardMetadata::find_user_scoped_dashboard_metadata( &conn, user_id.to_owned(), merchant_id.to_owned(), org_id.to_owned(), data_keys, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::DashboardMetadata::find_merchant_scoped_dashboard_metadata( &conn, merchant_id.to_owned(), org_id.to_owned(), data_keys, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DashboardMetadata::delete_all_user_scoped_dashboard_metadata_by_merchant_id( &conn, user_id.to_owned(), merchant_id.to_owned(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &self, user_id: &str, merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &conn, user_id.to_owned(), merchant_id.to_owned(), data_key, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl DashboardMetadataInterface for MockDb { async fn insert_metadata( &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; if dashboard_metadata.iter().any(|metadata_inner| { metadata_inner.user_id == metadata.user_id && metadata_inner.merchant_id == metadata.merchant_id && metadata_inner.org_id == metadata.org_id && metadata_inner.data_key == metadata.data_key }) { Err(errors::StorageError::DuplicateValue { entity: "user_id, merchant_id, org_id and data_key", key: None, })? } let metadata_new = storage::DashboardMetadata { id: i32::try_from(dashboard_metadata.len()) .change_context(errors::StorageError::MockDbError)?, user_id: metadata.user_id, merchant_id: metadata.merchant_id, org_id: metadata.org_id, data_key: metadata.data_key, data_value: metadata.data_value, created_by: metadata.created_by, created_at: metadata.created_at, last_modified_by: metadata.last_modified_by, last_modified_at: metadata.last_modified_at, }; dashboard_metadata.push(metadata_new.clone()); Ok(metadata_new) } async fn update_metadata( &self, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; let dashboard_metadata_to_update = dashboard_metadata .iter_mut() .find(|metadata| { metadata.user_id == user_id && metadata.merchant_id == merchant_id && metadata.org_id == org_id && metadata.data_key == data_key }) .ok_or(errors::StorageError::MockDbError)?; match dashboard_metadata_update { storage::DashboardMetadataUpdate::UpdateData { data_key, data_value, last_modified_by, } => { dashboard_metadata_to_update.data_key = data_key; dashboard_metadata_to_update.data_value = data_value; dashboard_metadata_to_update.last_modified_by = last_modified_by; dashboard_metadata_to_update.last_modified_at = common_utils::date_time::now(); } } Ok(dashboard_metadata_to_update.clone()) } async fn find_user_scoped_dashboard_metadata( &self, user_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let dashboard_metadata = self.dashboard_metadata.lock().await; let query_result = dashboard_metadata .iter() .filter(|metadata_inner| { metadata_inner .user_id .clone() .map(|user_id_inner| user_id_inner == user_id) .unwrap_or(false) && metadata_inner.merchant_id == *merchant_id && metadata_inner.org_id == *org_id && data_keys.contains(&metadata_inner.data_key) }) .cloned() .collect::<Vec<storage::DashboardMetadata>>(); if query_result.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No dashboard_metadata available for user_id = {user_id},\ merchant_id = {merchant_id:?}, org_id = {org_id:?} and data_keys = {data_keys:?}", )) .into()); } Ok(query_result) } async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let dashboard_metadata = self.dashboard_metadata.lock().await; let query_result = dashboard_metadata .iter() .filter(|metadata_inner| { metadata_inner.merchant_id == *merchant_id && metadata_inner.org_id == *org_id && data_keys.contains(&metadata_inner.data_key) }) .cloned() .collect::<Vec<storage::DashboardMetadata>>(); if query_result.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No dashboard_metadata available for merchant_id = {merchant_id:?},\ org_id = {org_id:?} and data_keyss = {data_keys:?}", )) .into()); } Ok(query_result) } async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; let initial_len = dashboard_metadata.len(); dashboard_metadata.retain(|metadata_inner| { !(metadata_inner .user_id .clone() .map(|user_id_inner| user_id_inner == user_id) .unwrap_or(false) && metadata_inner.merchant_id == *merchant_id) }); if dashboard_metadata.len() == initial_len { return Err(errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id} and merchant id = {merchant_id:?}" )) .into()); } Ok(true) } async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &self, user_id: &str, merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; let index_to_remove = dashboard_metadata .iter() .position(|metadata_inner| { metadata_inner.user_id.as_deref() == Some(user_id) && metadata_inner.merchant_id == *merchant_id && metadata_inner.data_key == data_key }) .ok_or(errors::StorageError::ValueNotFound( "No data found".to_string(), ))?; let deleted_value = dashboard_metadata.swap_remove(index_to_remove); Ok(deleted_value) } } <file_sep> pack="QBP-A" entity="dashboard_metadata" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-11-23-100644_create_dashboard_metadata_table/down.sql" -- This file should undo anything in `up.sql` DROP INDEX IF EXISTS dashboard_metadata_index; DROP TABLE IF EXISTS dashboard_metadata; <file_sep> pack="QBP-A" entity="dashboard_metadata" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-12-14-101348_alter_dashboard_metadata_key_type/up.sql" -- Your SQL goes here CREATE TYPE "DashboardMetadata" AS ENUM ( 'production_agreement', 'setup_processor', 'configure_endpoint', 'setup_complete', 'first_processor_connected', 'second_processor_connected', 'configured_routing', 'test_payment', 'integration_method', 'stripe_connected', 'paypal_connected', 'sp_routing_configured', 'sp_test_payment', 'download_woocom', 'configure_woocom', 'setup_woocom_webhook', 'is_multiple_configuration', 'configuration_type', 'feedback', 'prod_intent' ); ALTER TABLE dashboard_metadata ALTER COLUMN data_key TYPE "DashboardMetadata" USING (data_key::"DashboardMetadata"); <file_sep> pack="QBP-A" entity="dashboard_metadata" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-12-14-101348_alter_dashboard_metadata_key_type/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE dashboard_metadata ALTER COLUMN data_key TYPE VARCHAR(64); DROP TYPE IF EXISTS "DashboardMetadata"; <file_sep> pack="QBP-A" entity="dashboard_metadata" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_dashboard_metadata.rs" // schema snippet for entity=dashboard_metadata repo=hyperswitch // table: dashboard_metadata columns: [] entities: [dashboard_metadata] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/dispute.rs<|crate|> router<|op|> select entity=dispute repo=hyperswitch tables=dispute joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="dispute" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/dispute.rs" use common_utils::custom_serde; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use serde::Serialize; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::dispute}; #[derive(Clone, Debug, Insertable, Serialize, router_derive::DebugAsDisplay)] #[diesel(table_name = dispute)] #[serde(deny_unknown_fields)] pub struct DisputeNew { pub dispute_id: String, pub amount: String, pub currency: String, pub dispute_stage: storage_enums::DisputeStage, pub dispute_status: storage_enums::DisputeStatus, pub payment_id: common_utils::id_type::PaymentId, pub attempt_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub connector_status: String, pub connector_dispute_id: String, pub connector_reason: Option<String>, pub connector_reason_code: Option<String>, pub challenge_required_by: Option<PrimitiveDateTime>, pub connector_created_at: Option<PrimitiveDateTime>, pub connector_updated_at: Option<PrimitiveDateTime>, pub connector: String, pub evidence: Option<Secret<serde_json::Value>>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub dispute_amount: i64, pub organization_id: common_utils::id_type::OrganizationId, pub dispute_currency: Option<storage_enums::Currency>, } #[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable, Selectable)] #[diesel(table_name = dispute, primary_key(dispute_id), check_for_backend(diesel::pg::Pg))] pub struct Dispute { pub dispute_id: String, pub amount: String, pub currency: String, pub dispute_stage: storage_enums::DisputeStage, pub dispute_status: storage_enums::DisputeStatus, pub payment_id: common_utils::id_type::PaymentId, pub attempt_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub connector_status: String, pub connector_dispute_id: String, pub connector_reason: Option<String>, pub connector_reason_code: Option<String>, pub challenge_required_by: Option<PrimitiveDateTime>, pub connector_created_at: Option<PrimitiveDateTime>, pub connector_updated_at: Option<PrimitiveDateTime>, #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub connector: String, pub evidence: Secret<serde_json::Value>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub dispute_amount: i64, pub organization_id: common_utils::id_type::OrganizationId, pub dispute_currency: Option<storage_enums::Currency>, } #[derive(Debug)] pub enum DisputeUpdate { Update { dispute_stage: storage_enums::DisputeStage, dispute_status: storage_enums::DisputeStatus, connector_status: String, connector_reason: Option<String>, connector_reason_code: Option<String>, challenge_required_by: Option<PrimitiveDateTime>, connector_updated_at: Option<PrimitiveDateTime>, }, StatusUpdate { dispute_status: storage_enums::DisputeStatus, connector_status: Option<String>, }, EvidenceUpdate { evidence: Secret<serde_json::Value>, }, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = dispute)] pub struct DisputeUpdateInternal { dispute_stage: Option<storage_enums::DisputeStage>, dispute_status: Option<storage_enums::DisputeStatus>, connector_status: Option<String>, connector_reason: Option<String>, connector_reason_code: Option<String>, challenge_required_by: Option<PrimitiveDateTime>, connector_updated_at: Option<PrimitiveDateTime>, modified_at: PrimitiveDateTime, evidence: Option<Secret<serde_json::Value>>, } impl From<DisputeUpdate> for DisputeUpdateInternal { fn from(merchant_account_update: DisputeUpdate) -> Self { match merchant_account_update { DisputeUpdate::Update { dispute_stage, dispute_status, connector_status, connector_reason, connector_reason_code, challenge_required_by, connector_updated_at, } => Self { dispute_stage: Some(dispute_stage), dispute_status: Some(dispute_status), connector_status: Some(connector_status), connector_reason, connector_reason_code, challenge_required_by, connector_updated_at, modified_at: common_utils::date_time::now(), evidence: None, }, DisputeUpdate::StatusUpdate { dispute_status, connector_status, } => Self { dispute_status: Some(dispute_status), connector_status, modified_at: common_utils::date_time::now(), dispute_stage: None, connector_reason: None, connector_reason_code: None, challenge_required_by: None, connector_updated_at: None, evidence: None, }, DisputeUpdate::EvidenceUpdate { evidence } => Self { evidence: Some(evidence), dispute_stage: None, dispute_status: None, connector_status: None, connector_reason: None, connector_reason_code: None, challenge_required_by: None, connector_updated_at: None, modified_at: common_utils::date_time::now(), }, } } } <file_sep> pack="QBP-A" entity="dispute" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/dispute.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; use crate::{ dispute::{Dispute, DisputeNew, DisputeUpdate, DisputeUpdateInternal}, errors, schema::dispute::dsl, PgPooledConn, StorageResult, }; impl DisputeNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Dispute> { generics::generic_insert(conn, self).await } } impl Dispute { pub async fn find_by_merchant_id_payment_id_connector_dispute_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())) .and(dsl::connector_dispute_id.eq(connector_dispute_id.to_owned())), ) .await } pub async fn find_by_merchant_id_dispute_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::dispute_id.eq(dispute_id.to_owned())), ) .await } pub async fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), None, None, None, ) .await } pub async fn update(self, conn: &PgPooledConn, dispute: DisputeUpdate) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::dispute_id.eq(self.dispute_id.to_owned()), DisputeUpdateInternal::from(dispute), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } } <file_sep> pack="QBP-A" entity="dispute" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/dispute.rs" use std::collections::HashMap; use error_stack::report; use hyperswitch_domain_models::disputes; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage::{self, DisputeDbExt}, }; #[async_trait::async_trait] pub trait DisputeInterface { async fn insert_dispute( &self, dispute: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError>; async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult<Option<storage::Dispute>, errors::StorageError>; async fn find_dispute_by_merchant_id_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError>; async fn find_disputes_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>; async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>; async fn update_dispute( &self, this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError>; async fn get_dispute_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::StorageError>; } #[async_trait::async_trait] impl DisputeInterface for Store { #[instrument(skip_all)] async fn insert_dispute( &self, dispute: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; dispute .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult<Option<storage::Dispute>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::find_by_merchant_id_payment_id_connector_dispute_id( &conn, merchant_id, payment_id, connector_dispute_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_dispute_by_merchant_id_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::find_by_merchant_id_dispute_id(&conn, merchant_id, dispute_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_disputes_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::filter_by_constraints(&conn, merchant_id, dispute_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_dispute( &self, this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update(&conn, dispute) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn get_dispute_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::get_dispute_status_with_count( &conn, merchant_id, profile_id_list, time_range, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl DisputeInterface for MockDb { async fn insert_dispute( &self, dispute: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError> { let evidence = dispute.evidence.ok_or(errors::StorageError::MockDbError)?; let mut locked_disputes = self.disputes.lock().await; if locked_disputes .iter() .any(|d| d.dispute_id == dispute.dispute_id) { Err(errors::StorageError::MockDbError)?; } let now = common_utils::date_time::now(); let new_dispute = storage::Dispute { dispute_id: dispute.dispute_id, amount: dispute.amount, currency: dispute.currency, dispute_stage: dispute.dispute_stage, dispute_status: dispute.dispute_status, payment_id: dispute.payment_id, attempt_id: dispute.attempt_id, merchant_id: dispute.merchant_id, connector_status: dispute.connector_status, connector_dispute_id: dispute.connector_dispute_id, connector_reason: dispute.connector_reason, connector_reason_code: dispute.connector_reason_code, challenge_required_by: dispute.challenge_required_by, connector_created_at: dispute.connector_created_at, connector_updated_at: dispute.connector_updated_at, created_at: now, modified_at: now, connector: dispute.connector, profile_id: dispute.profile_id, evidence, merchant_connector_id: dispute.merchant_connector_id, dispute_amount: dispute.dispute_amount, organization_id: dispute.organization_id, dispute_currency: dispute.dispute_currency, }; locked_disputes.push(new_dispute.clone()); Ok(new_dispute) } async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult<Option<storage::Dispute>, errors::StorageError> { Ok(self .disputes .lock() .await .iter() .find(|d| { d.merchant_id == *merchant_id && d.payment_id == *payment_id && d.connector_dispute_id == connector_dispute_id }) .cloned()) } async fn find_dispute_by_merchant_id_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError> { let locked_disputes = self.disputes.lock().await; locked_disputes .iter() .find(|d| d.merchant_id == *merchant_id && d.dispute_id == dispute_id) .cloned() .ok_or(errors::StorageError::ValueNotFound(format!("No dispute available for merchant_id = {merchant_id:?} and dispute_id = {dispute_id}")) .into()) } async fn find_disputes_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let locked_disputes = self.disputes.lock().await; let limit_usize = dispute_constraints .limit .unwrap_or(u32::MAX) .try_into() .unwrap_or(usize::MAX); let offset_usize = dispute_constraints .offset .unwrap_or(0) .try_into() .unwrap_or(usize::MIN); let filtered_disputes: Vec<storage::Dispute> = locked_disputes .iter() .filter(|dispute| { dispute.merchant_id == *merchant_id && dispute_constraints .dispute_id .as_ref() .map_or(true, |id| &dispute.dispute_id == id) && dispute_constraints .payment_id .as_ref() .map_or(true, |id| &dispute.payment_id == id) && dispute_constraints .profile_id .as_ref() .map_or(true, |profile_ids| { dispute .profile_id .as_ref() .map_or(true, |id| profile_ids.contains(id)) }) && dispute_constraints .dispute_status .as_ref() .map_or(true, |statuses| statuses.contains(&dispute.dispute_status)) && dispute_constraints .dispute_stage .as_ref() .map_or(true, |stages| stages.contains(&dispute.dispute_stage)) && dispute_constraints.reason.as_ref().map_or(true, |reason| { dispute .connector_reason .as_ref() .map_or(true, |d_reason| d_reason == reason) }) && dispute_constraints .connector .as_ref() .map_or(true, |connectors| { connectors .iter() .any(|connector| dispute.connector.as_str() == *connector) }) && dispute_constraints .merchant_connector_id .as_ref() .map_or(true, |id| { dispute.merchant_connector_id.as_ref() == Some(id) }) && dispute_constraints .currency .as_ref() .map_or(true, |currencies| { currencies.iter().any(|currency| { dispute .dispute_currency .map(|dispute_currency| &dispute_currency == currency) .unwrap_or(dispute.currency.as_str() == currency.to_string()) }) }) && dispute_constraints .time_range .as_ref() .map_or(true, |range| { let dispute_time = dispute.created_at; dispute_time >= range.start_time && range .end_time .map_or(true, |end_time| dispute_time <= end_time) }) }) .skip(offset_usize) .take(limit_usize) .cloned() .collect(); Ok(filtered_disputes) } async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let locked_disputes = self.disputes.lock().await; Ok(locked_disputes .iter() .filter(|d| d.merchant_id == *merchant_id && d.payment_id == *payment_id) .cloned() .collect()) } async fn update_dispute( &self, this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError> { let mut locked_disputes = self.disputes.lock().await; let dispute_to_update = locked_disputes .iter_mut() .find(|d| d.dispute_id == this.dispute_id) .ok_or(errors::StorageError::MockDbError)?; let now = common_utils::date_time::now(); match dispute { storage::DisputeUpdate::Update { dispute_stage, dispute_status, connector_status, connector_reason, connector_reason_code, challenge_required_by, connector_updated_at, } => { if connector_reason.is_some() { dispute_to_update.connector_reason = connector_reason; } if connector_reason_code.is_some() { dispute_to_update.connector_reason_code = connector_reason_code; } if challenge_required_by.is_some() { dispute_to_update.challenge_required_by = challenge_required_by; } if connector_updated_at.is_some() { dispute_to_update.connector_updated_at = connector_updated_at; } dispute_to_update.dispute_stage = dispute_stage; dispute_to_update.dispute_status = dispute_status; dispute_to_update.connector_status = connector_status; } storage::DisputeUpdate::StatusUpdate { dispute_status, connector_status, } => { if let Some(status) = connector_status { dispute_to_update.connector_status = status; } dispute_to_update.dispute_status = dispute_status; } storage::DisputeUpdate::EvidenceUpdate { evidence } => { dispute_to_update.evidence = evidence; } } dispute_to_update.modified_at = now; Ok(dispute_to_update.clone()) } async fn get_dispute_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { let locked_disputes = self.disputes.lock().await; let filtered_disputes_data = locked_disputes .iter() .filter(|d| { d.merchant_id == *merchant_id && d.created_at >= time_range.start_time && time_range .end_time .as_ref() .map(|received_end_time| received_end_time >= &d.created_at) .unwrap_or(true) && profile_id_list .as_ref() .zip(d.profile_id.as_ref()) .map(|(received_profile_list, received_profile_id)| { received_profile_list.contains(received_profile_id) }) .unwrap_or(true) }) .cloned() .collect::<Vec<storage::Dispute>>(); Ok(filtered_disputes_data .into_iter() .fold( HashMap::new(), |mut acc: HashMap<common_enums::DisputeStatus, i64>, value| { acc.entry(value.dispute_status) .and_modify(|value| *value += 1) .or_insert(1); acc }, ) .into_iter() .collect::<Vec<(common_enums::DisputeStatus, i64)>>()) } } #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] mod mockdb_dispute_interface { use std::borrow::Cow; use diesel_models::{ dispute::DisputeNew, enums::{DisputeStage, DisputeStatus}, }; use hyperswitch_domain_models::disputes::DisputeListConstraints; use masking::Secret; use redis_interface::RedisSettings; use serde_json::Value; use time::macros::datetime; use crate::db::{dispute::DisputeInterface, MockDb}; pub struct DisputeNewIds { dispute_id: String, payment_id: common_utils::id_type::PaymentId, attempt_id: String, merchant_id: common_utils::id_type::MerchantId, connector_dispute_id: String, } fn create_dispute_new(dispute_ids: DisputeNewIds) -> DisputeNew { DisputeNew { dispute_id: dispute_ids.dispute_id, amount: "amount".into(), currency: "currency".into(), dispute_stage: DisputeStage::Dispute, dispute_status: DisputeStatus::DisputeOpened, payment_id: dispute_ids.payment_id, attempt_id: dispute_ids.attempt_id, merchant_id: dispute_ids.merchant_id, connector_status: "connector_status".into(), connector_dispute_id: dispute_ids.connector_dispute_id, connector_reason: Some("connector_reason".into()), connector_reason_code: Some("connector_reason_code".into()), challenge_required_by: Some(datetime!(2019-01-01 0:00)), connector_created_at: Some(datetime!(2019-01-02 0:00)), connector_updated_at: Some(datetime!(2019-01-03 0:00)), connector: "connector".into(), evidence: Some(Secret::from(Value::String("evidence".into()))), profile_id: Some(common_utils::generate_profile_id_of_default_length()), merchant_connector_id: None, dispute_amount: 1040, organization_id: common_utils::id_type::OrganizationId::default(), dispute_currency: Some(common_enums::Currency::default()), } } #[tokio::test] async fn test_insert_dispute() { let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create a mock DB"); let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( "payment_1", )) .unwrap(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_dispute = mockdb .disputes .lock() .await .iter() .find(|d| d.dispute_id == created_dispute.dispute_id) .cloned(); assert!(found_dispute.is_some()); assert_eq!(created_dispute, found_dispute.unwrap()); } #[tokio::test] async fn test_find_by_merchant_id_payment_id_connector_dispute_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( "payment_1", )) .unwrap(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( "payment_1", )) .unwrap(), connector_dispute_id: "connector_dispute_2".into(), })) .await .unwrap(); let found_dispute = mockdb .find_by_merchant_id_payment_id_connector_dispute_id( &merchant_id, &common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")) .unwrap(), "connector_dispute_1", ) .await .unwrap(); assert!(found_dispute.is_some()); assert_eq!(created_dispute, found_dispute.unwrap()); } #[tokio::test] async fn test_find_dispute_by_merchant_id_dispute_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_dispute = mockdb .find_dispute_by_merchant_id_dispute_id(&merchant_id, "dispute_1") .await .unwrap(); assert_eq!(created_dispute, found_dispute); } #[tokio::test] async fn test_find_disputes_by_merchant_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_2")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_disputes = mockdb .find_disputes_by_constraints( &merchant_id, &DisputeListConstraints { dispute_id: None, payment_id: None, profile_id: None, connector: None, merchant_connector_id: None, currency: None, limit: None, offset: None, dispute_status: None, dispute_stage: None, reason: None, time_range: None, }, ) .await .unwrap(); assert_eq!(1, found_disputes.len()); assert_eq!(created_dispute, found_disputes.first().unwrap().clone()); } #[tokio::test] async fn test_find_disputes_by_merchant_id_payment_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_disputes = mockdb .find_disputes_by_merchant_id_payment_id(&merchant_id, &payment_id) .await .unwrap(); assert_eq!(1, found_disputes.len()); assert_eq!(created_dispute, found_disputes.first().unwrap().clone()); } mod update_dispute { use std::borrow::Cow; use diesel_models::{ dispute::DisputeUpdate, enums::{DisputeStage, DisputeStatus}, }; use masking::Secret; use serde_json::Value; use time::macros::datetime; use crate::db::{ dispute::{ tests::mockdb_dispute_interface::{create_dispute_new, DisputeNewIds}, DisputeInterface, }, MockDb, }; #[tokio::test] async fn test_update_dispute_update() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let updated_dispute = mockdb .update_dispute( created_dispute.clone(), DisputeUpdate::Update { dispute_stage: DisputeStage::PreDispute, dispute_status: DisputeStatus::DisputeAccepted, connector_status: "updated_connector_status".into(), connector_reason: Some("updated_connector_reason".into()), connector_reason_code: Some("updated_connector_reason_code".into()), challenge_required_by: Some(datetime!(2019-01-10 0:00)), connector_updated_at: Some(datetime!(2019-01-11 0:00)), }, ) .await .unwrap(); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); assert_ne!(created_dispute.dispute_stage, updated_dispute.dispute_stage); assert_ne!( created_dispute.dispute_status, updated_dispute.dispute_status ); assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); assert_ne!( created_dispute.connector_status, updated_dispute.connector_status ); assert_eq!( created_dispute.connector_dispute_id, updated_dispute.connector_dispute_id ); assert_ne!( created_dispute.connector_reason, updated_dispute.connector_reason ); assert_ne!( created_dispute.connector_reason_code, updated_dispute.connector_reason_code ); assert_ne!( created_dispute.challenge_required_by, updated_dispute.challenge_required_by ); assert_eq!( created_dispute.connector_created_at, updated_dispute.connector_created_at ); assert_ne!( created_dispute.connector_updated_at, updated_dispute.connector_updated_at ); assert_eq!(created_dispute.created_at, updated_dispute.created_at); assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); assert_eq!(created_dispute.connector, updated_dispute.connector); assert_eq!(created_dispute.evidence, updated_dispute.evidence); } #[tokio::test] async fn test_update_dispute_update_status() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let updated_dispute = mockdb .update_dispute( created_dispute.clone(), DisputeUpdate::StatusUpdate { dispute_status: DisputeStatus::DisputeExpired, connector_status: Some("updated_connector_status".into()), }, ) .await .unwrap(); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); assert_eq!(created_dispute.dispute_stage, updated_dispute.dispute_stage); assert_ne!( created_dispute.dispute_status, updated_dispute.dispute_status ); assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); assert_ne!( created_dispute.connector_status, updated_dispute.connector_status ); assert_eq!( created_dispute.connector_dispute_id, updated_dispute.connector_dispute_id ); assert_eq!( created_dispute.connector_reason, updated_dispute.connector_reason ); assert_eq!( created_dispute.connector_reason_code, updated_dispute.connector_reason_code ); assert_eq!( created_dispute.challenge_required_by, updated_dispute.challenge_required_by ); assert_eq!( created_dispute.connector_created_at, updated_dispute.connector_created_at ); assert_eq!( created_dispute.connector_updated_at, updated_dispute.connector_updated_at ); assert_eq!(created_dispute.created_at, updated_dispute.created_at); assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); assert_eq!(created_dispute.connector, updated_dispute.connector); assert_eq!(created_dispute.evidence, updated_dispute.evidence); } #[tokio::test] async fn test_update_dispute_update_evidence() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let updated_dispute = mockdb .update_dispute( created_dispute.clone(), DisputeUpdate::EvidenceUpdate { evidence: Secret::from(Value::String("updated_evidence".into())), }, ) .await .unwrap(); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); assert_eq!(created_dispute.dispute_stage, updated_dispute.dispute_stage); assert_eq!( created_dispute.dispute_status, updated_dispute.dispute_status ); assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); assert_eq!( created_dispute.connector_status, updated_dispute.connector_status ); assert_eq!( created_dispute.connector_dispute_id, updated_dispute.connector_dispute_id ); assert_eq!( created_dispute.connector_reason, updated_dispute.connector_reason ); assert_eq!( created_dispute.connector_reason_code, updated_dispute.connector_reason_code ); assert_eq!( created_dispute.challenge_required_by, updated_dispute.challenge_required_by ); assert_eq!( created_dispute.connector_created_at, updated_dispute.connector_created_at ); assert_eq!( created_dispute.connector_updated_at, updated_dispute.connector_updated_at ); assert_eq!(created_dispute.created_at, updated_dispute.created_at); assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); assert_eq!(created_dispute.connector, updated_dispute.connector); assert_ne!(created_dispute.evidence, updated_dispute.evidence); } } } } <file_sep> pack="QBP-A" entity="dispute" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-10-28-125949_add_dispute_currency_column_in_dispute_table/up.sql" -- Your SQL goes here ALTER TABLE dispute ADD COLUMN IF NOT EXISTS dispute_currency "Currency"; <file_sep> pack="QBP-A" entity="dispute" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-10-28-125949_add_dispute_currency_column_in_dispute_table/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE dispute DROP COLUMN IF EXISTS dispute_currency; <file_sep> pack="QBP-A" entity="dispute" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/down.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR(64)` column for tables that had it removed. -- It must be ensured that the deployed version of the application includes the `id` column in any of its queries. -- Re-create the id column as this was used as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account ADD COLUMN id VARCHAR(64); ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account ADD COLUMN id VARCHAR(64); ------------------------ Customers ----------------------- ALTER TABLE customers ADD COLUMN id VARCHAR(64); ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent ADD COLUMN id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt ADD COLUMN id VARCHAR(64); ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods ADD COLUMN id VARCHAR(64); ------------------------ Address ----------------------- ALTER TABLE address ADD COLUMN id VARCHAR(64); ------------------------ Dispute ----------------------- ALTER TABLE dispute ADD COLUMN id VARCHAR(64); ------------------------ Mandate ----------------------- ALTER TABLE mandate ADD COLUMN id VARCHAR(64); ------------------------ Refund ----------------------- ALTER TABLE refund ADD COLUMN id VARCHAR(64); ------------------------ BlockList ----------------------- ALTER TABLE blocklist ADD COLUMN id VARCHAR(64); ------------------------ Roles ----------------------- ALTER TABLE roles ADD COLUMN id VARCHAR(64); ------------------------ Users ----------------------- ALTER TABLE users ADD COLUMN id VARCHAR(64); <file_sep> pack="QBP-A" entity="dispute" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_dispute.rs" // schema snippet for entity=dispute repo=hyperswitch // table: dispute columns: [] entities: [dispute] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/dynamic_routing_stats.rs<|crate|> router<|op|> select entity=dynamic_routing_stats repo=hyperswitch tables=dynamic_routing_stats joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="dynamic_routing_stats" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/dynamic_routing_stats.rs" use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::schema::dynamic_routing_stats; #[derive(Clone, Debug, Eq, Insertable, PartialEq)] #[diesel(table_name = dynamic_routing_stats)] pub struct DynamicRoutingStatsNew { pub payment_id: common_utils::id_type::PaymentId, pub attempt_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub profile_id: common_utils::id_type::ProfileId, pub amount: common_utils::types::MinorUnit, pub success_based_routing_connector: String, pub payment_connector: String, pub currency: Option<common_enums::Currency>, pub payment_method: Option<common_enums::PaymentMethod>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub payment_status: common_enums::AttemptStatus, pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, pub created_at: time::PrimitiveDateTime, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub global_success_based_connector: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)] #[diesel(table_name = dynamic_routing_stats, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct DynamicRoutingStats { pub payment_id: common_utils::id_type::PaymentId, pub attempt_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub profile_id: common_utils::id_type::ProfileId, pub amount: common_utils::types::MinorUnit, pub success_based_routing_connector: String, pub payment_connector: String, pub currency: Option<common_enums::Currency>, pub payment_method: Option<common_enums::PaymentMethod>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub payment_status: common_enums::AttemptStatus, pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, pub created_at: time::PrimitiveDateTime, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub global_success_based_connector: Option<String>, } #[derive( Clone, Debug, Eq, PartialEq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, )] #[diesel(table_name = dynamic_routing_stats)] pub struct DynamicRoutingStatsUpdate { pub amount: common_utils::types::MinorUnit, pub success_based_routing_connector: String, pub payment_connector: String, pub currency: Option<common_enums::Currency>, pub payment_method: Option<common_enums::PaymentMethod>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub payment_status: common_enums::AttemptStatus, pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub global_success_based_connector: Option<String>, } <file_sep> pack="QBP-A" entity="dynamic_routing_stats" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/dynamic_routing_stats.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use error_stack::report; use super::generics; use crate::{ dynamic_routing_stats::{ DynamicRoutingStats, DynamicRoutingStatsNew, DynamicRoutingStatsUpdate, }, errors, schema::dynamic_routing_stats::dsl, PgPooledConn, StorageResult, }; impl DynamicRoutingStatsNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<DynamicRoutingStats> { generics::generic_insert(conn, self).await } } impl DynamicRoutingStats { pub async fn find_optional_by_attempt_id_merchant_id( conn: &PgPooledConn, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ) .await } pub async fn update( conn: &PgPooledConn, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, dynamic_routing_stat: DynamicRoutingStatsUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::< <Self as HasTable>::Table, DynamicRoutingStatsUpdate, _, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), dynamic_routing_stat, ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating dynamic_routing_stats entry") }) } } <file_sep> pack="QBP-A" entity="dynamic_routing_stats" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/dynamic_routing_stats.rs" use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait DynamicRoutingStatsInterface { async fn insert_dynamic_routing_stat_entry( &self, dynamic_routing_stat_new: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>; async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError>; async fn update_dynamic_routing_stats( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>; } #[async_trait::async_trait] impl DynamicRoutingStatsInterface for Store { #[instrument(skip_all)] async fn insert_dynamic_routing_stat_entry( &self, dynamic_routing_stat: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; dynamic_routing_stat .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DynamicRoutingStats::find_optional_by_attempt_id_merchant_id( &conn, attempt_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn update_dynamic_routing_stats( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DynamicRoutingStats::update(&conn, attempt_id, merchant_id, data) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl DynamicRoutingStatsInterface for MockDb { #[instrument(skip_all)] async fn insert_dynamic_routing_stat_entry( &self, _dynamic_routing_stat: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, _attempt_id: String, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_dynamic_routing_stats( &self, _attempt_id: String, _merchant_id: &common_utils::id_type::MerchantId, _data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl DynamicRoutingStatsInterface for KafkaStore { #[instrument(skip_all)] async fn insert_dynamic_routing_stat_entry( &self, dynamic_routing_stat: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { self.diesel_store .insert_dynamic_routing_stat_entry(dynamic_routing_stat) .await } async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { self.diesel_store .find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(attempt_id, merchant_id) .await } async fn update_dynamic_routing_stats( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { self.diesel_store .update_dynamic_routing_stats(attempt_id, merchant_id, data) .await } } <file_sep> pack="QBP-A" entity="dynamic_routing_stats" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-16-111228_add_new_col_payment_method_type_in_dynamic_routing_stats/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE dynamic_routing_stats DROP COLUMN IF EXISTS payment_method_type; <file_sep> pack="QBP-A" entity="dynamic_routing_stats" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/up.sql" -- Your SQL goes here ALTER TABLE dynamic_routing_stats ADD COLUMN IF NOT EXISTS global_success_based_connector VARCHAR(64); <file_sep> pack="QBP-A" entity="dynamic_routing_stats" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE dynamic_routing_stats DROP COLUMN IF EXISTS global_success_based_connector; <file_sep> pack="QBP-A" entity="dynamic_routing_stats" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_dynamic_routing_stats.rs" // schema snippet for entity=dynamic_routing_stats repo=hyperswitch // table: dynamic_routing_stats columns: [] entities: [dynamic_routing_stats] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/events.rs<|crate|> router<|op|> select entity=events repo=hyperswitch tables=events joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="events" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/events.rs" use common_utils::{custom_serde, encryption::Encryption}; use diesel::{ expression::AsExpression, AsChangeset, Identifiable, Insertable, Queryable, Selectable, }; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::events}; #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = events)] pub struct EventNew { pub event_id: String, pub event_type: storage_enums::EventType, pub event_class: storage_enums::EventClass, pub is_webhook_notified: bool, pub primary_object_id: String, pub primary_object_type: storage_enums::EventObjectType, pub created_at: PrimitiveDateTime, pub merchant_id: Option<common_utils::id_type::MerchantId>, pub business_profile_id: Option<common_utils::id_type::ProfileId>, pub primary_object_created_at: Option<PrimitiveDateTime>, pub idempotent_event_id: Option<String>, pub initial_attempt_id: Option<String>, pub request: Option<Encryption>, pub response: Option<Encryption>, pub delivery_attempt: Option<storage_enums::WebhookDeliveryAttempt>, pub metadata: Option<EventMetadata>, pub is_overall_delivery_successful: Option<bool>, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = events)] pub struct EventUpdateInternal { pub is_webhook_notified: Option<bool>, pub response: Option<Encryption>, pub is_overall_delivery_successful: Option<bool>, } #[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable, Selectable)] #[diesel(table_name = events, primary_key(event_id), check_for_backend(diesel::pg::Pg))] pub struct Event { pub event_id: String, pub event_type: storage_enums::EventType, pub event_class: storage_enums::EventClass, pub is_webhook_notified: bool, pub primary_object_id: String, pub primary_object_type: storage_enums::EventObjectType, #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, pub merchant_id: Option<common_utils::id_type::MerchantId>, pub business_profile_id: Option<common_utils::id_type::ProfileId>, // This column can be used to partition the database table, so that all events related to a // single object would reside in the same partition pub primary_object_created_at: Option<PrimitiveDateTime>, pub idempotent_event_id: Option<String>, pub initial_attempt_id: Option<String>, pub request: Option<Encryption>, pub response: Option<Encryption>, pub delivery_attempt: Option<storage_enums::WebhookDeliveryAttempt>, pub metadata: Option<EventMetadata>, pub is_overall_delivery_successful: Option<bool>, } #[derive(Clone, Debug, Deserialize, Serialize, AsExpression, diesel::FromSqlRow)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub enum EventMetadata { Payment { payment_id: common_utils::id_type::PaymentId, }, Payout { payout_id: String, }, Refund { payment_id: common_utils::id_type::PaymentId, refund_id: String, }, Dispute { payment_id: common_utils::id_type::PaymentId, attempt_id: String, dispute_id: String, }, Mandate { payment_method_id: String, mandate_id: String, }, } common_utils::impl_to_sql_from_sql_json!(EventMetadata); <file_sep> pack="QBP-A" entity="events" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/events.rs" 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 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 } 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>, 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, 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 } 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>, 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, 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>, 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::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 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, 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, 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_sep> pack="QBP-A" entity="events" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/events.rs" use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage, }, }; #[async_trait::async_trait] pub trait EventInterface where domain::Event: Conversion<DstType = storage::events::Event, NewDstType = storage::events::EventNew>, { async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError>; } #[async_trait::async_trait] impl EventInterface for Store { #[instrument(skip_all)] async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; event .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::find_by_merchant_id_event_id(&conn, merchant_id, event_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_merchant_id_primary_object_id( &conn, merchant_id, primary_object_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_merchant_id_constraints( &conn, merchant_id, created_after, created_before, limit, offset, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_by_merchant_id_initial_attempt_id( &conn, merchant_id, initial_attempt_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_profile_id_primary_object_id( &conn, profile_id, primary_object_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_profile_id_constraints( &conn, profile_id, created_after, created_before, limit, offset, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( merchant_key_store.merchant_id.clone(), ), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Event::update_by_merchant_id_event_id(&conn, merchant_id, event_id, event.into()) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::count_initial_attempts_by_constraints( &conn, merchant_id, profile_id, created_after, created_before, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl EventInterface for MockDb { async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let mut locked_events = self.events.lock().await; let stored_event = Conversion::convert(event) .await .change_context(errors::StorageError::EncryptionError)?; locked_events.push(stored_event.clone()); stored_event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let locked_events = self.events.lock().await; locked_events .iter() .find(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.event_id == event_id }) .cloned() .async_map(|event| async { event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "No event available with merchant_id = {merchant_id:?} and event_id = {event_id}" )) .into(), ) } async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && event.primary_object_id == primary_object_id }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events_iter = locked_events.iter().filter(|event| { let check = event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event.is_overall_delivery_successful == is_delivered); check }); let offset: usize = if let Some(offset) = offset { if offset < 0 { Err(errors::StorageError::MockDbError)?; } offset .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { 0 }; let limit: usize = if let Some(limit) = limit { if limit < 0 { Err(errors::StorageError::MockDbError)?; } limit .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { usize::MAX }; let events = events_iter .skip(offset) .take(limit) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id == Some(initial_attempt_id.to_owned()) }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.business_profile_id == Some(profile_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && event.primary_object_id == primary_object_id }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events_iter = locked_events.iter().filter(|event| { let check = event.business_profile_id == Some(profile_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event.is_overall_delivery_successful == is_delivered); check }); let offset: usize = if let Some(offset) = offset { if offset < 0 { Err(errors::StorageError::MockDbError)?; } offset .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { 0 }; let limit: usize = if let Some(limit) = limit { if limit < 0 { Err(errors::StorageError::MockDbError)?; } limit .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { usize::MAX }; let events = events_iter .skip(offset) .take(limit) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let mut locked_events = self.events.lock().await; let event_to_update = locked_events .iter_mut() .find(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.event_id == event_id }) .ok_or(errors::StorageError::MockDbError)?; match event { domain::EventUpdate::UpdateResponse { is_webhook_notified, response, } => { event_to_update.is_webhook_notified = is_webhook_notified; event_to_update.response = response.map(Into::into); } domain::EventUpdate::OverallDeliveryStatusUpdate { is_overall_delivery_successful, } => { event_to_update.is_overall_delivery_successful = Some(is_overall_delivery_successful) } } event_to_update .clone() .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError> { let locked_events = self.events.lock().await; let iter_events = locked_events.iter().filter(|event| { let check = event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.merchant_id == Some(merchant_id.to_owned())) && (event.business_profile_id == profile_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event.is_overall_delivery_successful == is_delivered); check }); let events = iter_events.cloned().collect::<Vec<_>>(); i64::try_from(events.len()) .change_context(errors::StorageError::MockDbError) .attach_printable("Failed to convert usize to i64") } } #[cfg(test)] mod tests { use std::sync::Arc; use common_utils::{type_name, types::keymanager::Identifier}; use diesel_models::{enums, events::EventMetadata}; use time::macros::datetime; use crate::{ db::{ events::EventInterface, merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb, }, routes::{ self, app::{settings::Settings, StorageImpl}, }, services, types::domain, }; #[allow(clippy::unwrap_used)] #[tokio::test] async fn test_mockdb_event_interface() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let event_id = "test_event_id"; let (tx, _) = tokio::sync::oneshot::channel(); let app_state = Box::pin(routes::AppState::with_storage( Settings::default(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1")) .unwrap(); let business_profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("profile1")).unwrap(); let payment_id = "test_payment_id"; let key_manager_state = &state.into(); let master_key = mockdb.get_master_key(); mockdb .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), Identifier::Merchant(merchant_id.to_owned()), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let merchant_key_store = mockdb .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); let event1 = mockdb .insert_event( key_manager_state, domain::Event { event_id: event_id.into(), event_type: enums::EventType::PaymentSucceeded, event_class: enums::EventClass::Payments, is_webhook_notified: false, primary_object_id: payment_id.into(), primary_object_type: enums::EventObjectType::PaymentDetails, created_at: common_utils::date_time::now(), merchant_id: Some(merchant_id.to_owned()), business_profile_id: Some(business_profile_id.to_owned()), primary_object_created_at: Some(common_utils::date_time::now()), idempotent_event_id: Some(event_id.into()), initial_attempt_id: Some(event_id.into()), request: None, response: None, delivery_attempt: Some(enums::WebhookDeliveryAttempt::InitialAttempt), metadata: Some(EventMetadata::Payment { payment_id: common_utils::id_type::PaymentId::try_from( std::borrow::Cow::Borrowed(payment_id), ) .unwrap(), }), is_overall_delivery_successful: Some(false), }, &merchant_key_store, ) .await .unwrap(); assert_eq!(event1.event_id, event_id); let updated_event = mockdb .update_event_by_merchant_id_event_id( key_manager_state, &merchant_id, event_id, domain::EventUpdate::UpdateResponse { is_webhook_notified: true, response: None, }, &merchant_key_store, ) .await .unwrap(); assert!(updated_event.is_webhook_notified); assert_eq!(updated_event.primary_object_id, payment_id); assert_eq!(updated_event.event_id, event_id); } } <file_sep> pack="QBP-A" entity="events" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-06-14-145304_events_add_metadata_column/down.sql" ALTER TABLE events DROP COLUMN metadata; <file_sep> pack="QBP-A" entity="events" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-19-072457_add_is_overall_delivery_successful_column_in_events_table/up.sql" ALTER TABLE events ADD COLUMN IF NOT EXISTS is_overall_delivery_successful BOOLEAN; <file_sep> pack="QBP-A" entity="events" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-19-072457_add_is_overall_delivery_successful_column_in_events_table/down.sql" ALTER TABLE events DROP COLUMN IF EXISTS is_overall_delivery_successful; <file_sep> pack="QBP-A" entity="events" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_events.rs" // schema snippet for entity=events repo=hyperswitch // table: events columns: [] entities: [events] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/fraud_check.rs<|crate|> router<|op|> select entity=fraud_check repo=hyperswitch tables=fraud_check joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="fraud_check" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/fraud_check.rs" use common_enums as storage_enums; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, schema::fraud_check, }; #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = fraud_check, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct FraudCheck { pub frm_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub created_at: PrimitiveDateTime, pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: FraudCheckType, pub frm_status: FraudCheckStatus, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, pub modified_at: PrimitiveDateTime, pub last_step: FraudCheckLastStep, pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision. } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = fraud_check)] pub struct FraudCheckNew { pub frm_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub created_at: PrimitiveDateTime, pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: FraudCheckType, pub frm_status: FraudCheckStatus, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, pub modified_at: PrimitiveDateTime, pub last_step: FraudCheckLastStep, pub payment_capture_method: Option<storage_enums::CaptureMethod>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum FraudCheckUpdate { //Refer PaymentAttemptUpdate for other variants implementations ResponseUpdate { frm_status: FraudCheckStatus, frm_transaction_id: Option<String>, frm_reason: Option<serde_json::Value>, frm_score: Option<i32>, metadata: Option<serde_json::Value>, modified_at: PrimitiveDateTime, last_step: FraudCheckLastStep, payment_capture_method: Option<storage_enums::CaptureMethod>, }, ErrorUpdate { status: FraudCheckStatus, error_message: Option<Option<String>>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = fraud_check)] pub struct FraudCheckUpdateInternal { frm_status: Option<FraudCheckStatus>, frm_transaction_id: Option<String>, frm_reason: Option<serde_json::Value>, frm_score: Option<i32>, frm_error: Option<Option<String>>, metadata: Option<serde_json::Value>, last_step: FraudCheckLastStep, payment_capture_method: Option<storage_enums::CaptureMethod>, } impl From<FraudCheckUpdate> for FraudCheckUpdateInternal { fn from(fraud_check_update: FraudCheckUpdate) -> Self { match fraud_check_update { FraudCheckUpdate::ResponseUpdate { frm_status, frm_transaction_id, frm_reason, frm_score, metadata, modified_at: _, last_step, payment_capture_method, } => Self { frm_status: Some(frm_status), frm_transaction_id, frm_reason, frm_score, metadata, last_step, payment_capture_method, ..Default::default() }, FraudCheckUpdate::ErrorUpdate { status, error_message, } => Self { frm_status: Some(status), frm_error: error_message, ..Default::default() }, } } } <file_sep> pack="QBP-A" entity="fraud_check" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/fraud_check.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use crate::{ errors, fraud_check::*, query::generics, schema::fraud_check::dsl, PgPooledConn, StorageResult, }; impl FraudCheckNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<FraudCheck> { generics::generic_insert(conn, self).await } } impl FraudCheck { pub async fn update_with_attempt_id( self, conn: &PgPooledConn, fraud_check: FraudCheckUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), FraudCheckUpdateInternal::from(fraud_check), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn get_with_payment_id( conn: &PgPooledConn, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_id .eq(payment_id) .and(dsl::merchant_id.eq(merchant_id)), ) .await } pub async fn get_with_payment_id_if_present( conn: &PgPooledConn, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_id .eq(payment_id) .and(dsl::merchant_id.eq(merchant_id)), ) .await } } <file_sep> pack="QBP-A" entity="fraud_check" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/fraud_check.rs" use diesel_models::fraud_check::{self as storage, FraudCheck, FraudCheckUpdate}; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait FraudCheckInterface { async fn insert_fraud_check_response( &self, new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, errors::StorageError>; async fn update_fraud_check_response_with_attempt_id( &self, this: FraudCheck, fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, errors::StorageError>; async fn find_fraud_check_by_payment_id( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<FraudCheck, errors::StorageError>; async fn find_fraud_check_by_payment_id_if_present( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, errors::StorageError>; } #[async_trait::async_trait] impl FraudCheckInterface for Store { #[instrument(skip_all)] async fn insert_fraud_check_response( &self, new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_fraud_check_response_with_attempt_id( &self, this: FraudCheck, fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update_with_attempt_id(&conn, fraud_check) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_fraud_check_by_payment_id( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<FraudCheck, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; FraudCheck::get_with_payment_id(&conn, payment_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_fraud_check_by_payment_id_if_present( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; FraudCheck::get_with_payment_id_if_present(&conn, payment_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl FraudCheckInterface for MockDb { async fn insert_fraud_check_response( &self, _new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_fraud_check_response_with_attempt_id( &self, _this: FraudCheck, _fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_fraud_check_by_payment_id( &self, _payment_id: common_utils::id_type::PaymentId, _merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<FraudCheck, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_fraud_check_by_payment_id_if_present( &self, _payment_id: common_utils::id_type::PaymentId, _merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } <file_sep> pack="QBP-A" entity="fraud_check" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-08-16-103806_add_last_executed_frm_step/down.sql" alter table fraud_check drop column last_step; <file_sep> pack="QBP-A" entity="fraud_check" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-04-24-104042_add_capture_method_in_fraud_check_table/up.sql" ALTER TABLE fraud_check ADD COLUMN IF NOT EXISTS payment_capture_method "CaptureMethod" NULL; <file_sep> pack="QBP-A" entity="fraud_check" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-04-24-104042_add_capture_method_in_fraud_check_table/down.sql" ALTER TABLE fraud_check DROP COLUMN IF EXISTS payment_capture_method; <file_sep> pack="QBP-A" entity="fraud_check" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_fraud_check.rs" // schema snippet for entity=fraud_check repo=hyperswitch // table: fraud_check columns: [] entities: [fraud_check] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/generics.rs<|crate|> diesel_models<|op|> select entity=generics repo=hyperswitch tables=generics joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-C" entity="generics" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/generics.rs" use std::fmt::Debug; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ associations::HasTable, debug_query, dsl::{Find, 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}, LoadQuery, RunQueryDsl, }, result::Error as DieselError, Expression, Insertable, QueryDsl, QuerySource, Table, }; use error_stack::{report, ResultExt}; use router_env::logger; use crate::{errors, 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 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> + 'static, IntoBoxed<'static, T, Pg>: FilterDsl<P, 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); 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::NotFound) .attach_printable("Error filtering records by predicate") } 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), }, } }
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/gsm.rs<|crate|> router<|op|> select entity=gsm repo=hyperswitch tables=gsm joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="gsm" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/gsm.rs" //! Gateway status mapping use common_enums::ErrorCategory; use common_utils::{ custom_serde, events::{ApiEventMetric, ApiEventsType}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::schema::gateway_status_map; #[derive( Clone, Debug, Eq, PartialEq, Ord, PartialOrd, router_derive::DebugAsDisplay, Identifiable, Queryable, Selectable, serde::Serialize, )] #[diesel(table_name = gateway_status_map, primary_key(connector, flow, sub_flow, code, message), check_for_backend(diesel::pg::Pg))] pub struct GatewayStatusMap { pub connector: String, pub flow: String, pub sub_flow: String, pub code: String, pub message: String, pub status: String, pub router_error: Option<String>, pub decision: String, #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "custom_serde::iso8601")] pub last_modified: PrimitiveDateTime, pub step_up_possible: bool, pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: bool, } #[derive(Clone, Debug, Eq, PartialEq, Insertable)] #[diesel(table_name = gateway_status_map)] pub struct GatewayStatusMappingNew { pub connector: String, pub flow: String, pub sub_flow: String, pub code: String, pub message: String, pub status: String, pub router_error: Option<String>, pub decision: String, pub step_up_possible: bool, pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: bool, } #[derive( Clone, Debug, PartialEq, Eq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, )] #[diesel(table_name = gateway_status_map)] pub struct GatewayStatusMapperUpdateInternal { pub connector: Option<String>, pub flow: Option<String>, pub sub_flow: Option<String>, pub code: Option<String>, pub message: Option<String>, pub status: Option<String>, pub router_error: Option<Option<String>>, pub decision: Option<String>, pub step_up_possible: Option<bool>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub last_modified: PrimitiveDateTime, pub clear_pan_possible: Option<bool>, } #[derive(Debug)] pub struct GatewayStatusMappingUpdate { pub status: Option<String>, pub router_error: Option<Option<String>>, pub decision: Option<String>, pub step_up_possible: Option<bool>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: Option<bool>, } impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { fn from(value: GatewayStatusMappingUpdate) -> Self { let GatewayStatusMappingUpdate { decision, status, router_error, step_up_possible, unified_code, unified_message, error_category, clear_pan_possible, } = value; Self { status, router_error, decision, step_up_possible, unified_code, unified_message, error_category, last_modified: common_utils::date_time::now(), connector: None, flow: None, sub_flow: None, code: None, message: None, clear_pan_possible, } } } impl ApiEventMetric for GatewayStatusMap { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } } <file_sep> pack="QBP-A" entity="gsm" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/gsm.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use error_stack::report; use crate::{ errors, gsm::*, query::generics, schema::gateway_status_map::dsl, PgPooledConn, StorageResult, }; impl GatewayStatusMappingNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<GatewayStatusMap> { generics::generic_insert(conn, self).await } } impl GatewayStatusMap { pub async fn find( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::connector .eq(connector) .and(dsl::flow.eq(flow)) .and(dsl::sub_flow.eq(sub_flow)) .and(dsl::code.eq(code)) .and(dsl::message.eq(message)), ) .await } pub async fn retrieve_decision( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> StorageResult<String> { Self::find(conn, connector, flow, sub_flow, code, message) .await .map(|item| item.decision) } pub async fn update( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, gsm: GatewayStatusMappingUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::< <Self as HasTable>::Table, GatewayStatusMapperUpdateInternal, _, _, >( conn, dsl::connector .eq(connector) .and(dsl::flow.eq(flow)) .and(dsl::sub_flow.eq(sub_flow)) .and(dsl::code.eq(code)) .and(dsl::message.eq(message)), gsm.into(), ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating gsm entry") }) } pub async fn delete( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::connector .eq(connector) .and(dsl::flow.eq(flow)) .and(dsl::sub_flow.eq(sub_flow)) .and(dsl::code.eq(code)) .and(dsl::message.eq(message)), ) .await } } <file_sep> pack="QBP-A" entity="gsm" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/gsm.rs" use diesel_models::gsm as storage; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait GsmInterface { async fn add_gsm_rule( &self, rule: storage::GatewayStatusMappingNew, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; async fn find_gsm_decision( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<String, errors::StorageError>; async fn find_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; async fn update_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, data: storage::GatewayStatusMappingUpdate, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; async fn delete_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<bool, errors::StorageError>; } #[async_trait::async_trait] impl GsmInterface for Store { #[instrument(skip_all)] async fn add_gsm_rule( &self, rule: storage::GatewayStatusMappingNew, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; rule.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_gsm_decision( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<String, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::GatewayStatusMap::retrieve_decision( &conn, connector, flow, sub_flow, code, message, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::GatewayStatusMap::find(&conn, connector, flow, sub_flow, code, message) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, data: storage::GatewayStatusMappingUpdate, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::GatewayStatusMap::update(&conn, connector, flow, sub_flow, code, message, data) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::GatewayStatusMap::delete(&conn, connector, flow, sub_flow, code, message) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl GsmInterface for MockDb { async fn add_gsm_rule( &self, _rule: storage::GatewayStatusMappingNew, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_gsm_decision( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, ) -> CustomResult<String, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_gsm_rule( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_gsm_rule( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, _data: storage::GatewayStatusMappingUpdate, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn delete_gsm_rule( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, ) -> CustomResult<bool, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } <file_sep> pack="QBP-A" entity="gsm" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-11-24-104438_add_error_category_col_to_gsm/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE gateway_status_map DROP COLUMN error_category; <file_sep> pack="QBP-A" entity="gsm" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-10-091820_add-clear-pan-possible-to-gsm/up.sql" -- Your SQL goes here ALTER TABLE gateway_status_map ADD COLUMN IF NOT EXISTS clear_pan_possible BOOLEAN NOT NULL DEFAULT FALSE; <file_sep> pack="QBP-A" entity="gsm" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-10-091820_add-clear-pan-possible-to-gsm/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE gateway_status_map DROP COLUMN IF EXISTS clear_pan_possible; <file_sep> pack="QBP-A" entity="gsm" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_gsm.rs" // schema snippet for entity=gsm repo=hyperswitch // table: gateway_status_map columns: [] entities: [gsm] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/locker_mock_up.rs<|crate|> router<|op|> select entity=locker_mock_up repo=hyperswitch tables=locker_mock_up joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="locker_mock_up" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/locker_mock_up.rs" use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::locker_mock_up; #[derive(Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq)] #[diesel(table_name = locker_mock_up, primary_key(card_id), check_for_backend(diesel::pg::Pg))] pub struct LockerMockUp { pub card_id: String, pub external_id: String, pub card_fingerprint: String, pub card_global_fingerprint: String, pub merchant_id: common_utils::id_type::MerchantId, pub card_number: String, pub card_exp_year: String, pub card_exp_month: String, pub name_on_card: Option<String>, pub nickname: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub duplicate: Option<bool>, pub card_cvc: Option<String>, pub payment_method_id: Option<String>, pub enc_card_data: Option<String>, } #[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = locker_mock_up)] pub struct LockerMockUpNew { pub card_id: String, pub external_id: String, pub card_fingerprint: String, pub card_global_fingerprint: String, pub merchant_id: common_utils::id_type::MerchantId, pub card_number: String, pub card_exp_year: String, pub card_exp_month: String, pub name_on_card: Option<String>, pub card_cvc: Option<String>, pub payment_method_id: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub nickname: Option<String>, pub enc_card_data: Option<String>, } <file_sep> pack="QBP-A" entity="locker_mock_up" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/locker_mock_up.rs" use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ locker_mock_up::{LockerMockUp, LockerMockUpNew}, schema::locker_mock_up::dsl, PgPooledConn, StorageResult, }; impl LockerMockUpNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<LockerMockUp> { generics::generic_insert(conn, self).await } } impl LockerMockUp { pub async fn find_by_card_id(conn: &PgPooledConn, card_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::card_id.eq(card_id.to_owned()), ) .await } pub async fn delete_by_card_id(conn: &PgPooledConn, card_id: &str) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::card_id.eq(card_id.to_owned()), ) .await } } <file_sep> pack="QBP-A" entity="locker_mock_up" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/locker_mock_up.rs" use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait LockerMockUpInterface { async fn find_locker_by_card_id( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError>; async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError>; async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError>; } #[async_trait::async_trait] impl LockerMockUpInterface for Store { #[instrument(skip_all)] async fn find_locker_by_card_id( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::LockerMockUp::find_by_card_id(&conn, card_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::LockerMockUp::delete_by_card_id(&conn, card_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl LockerMockUpInterface for MockDb { async fn find_locker_by_card_id( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { self.lockers .lock() .await .iter() .find(|l| l.card_id == card_id) .cloned() .ok_or(errors::StorageError::MockDbError.into()) } async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let mut locked_lockers = self.lockers.lock().await; if locked_lockers.iter().any(|l| l.card_id == new.card_id) { Err(errors::StorageError::MockDbError)?; } let created_locker = storage::LockerMockUp { card_id: new.card_id, external_id: new.external_id, card_fingerprint: new.card_fingerprint, card_global_fingerprint: new.card_global_fingerprint, merchant_id: new.merchant_id, card_number: new.card_number, card_exp_year: new.card_exp_year, card_exp_month: new.card_exp_month, name_on_card: new.name_on_card, nickname: None, customer_id: new.customer_id, duplicate: None, card_cvc: new.card_cvc, payment_method_id: new.payment_method_id, enc_card_data: new.enc_card_data, }; locked_lockers.push(created_locker.clone()); Ok(created_locker) } async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let mut locked_lockers = self.lockers.lock().await; let position = locked_lockers .iter() .position(|l| l.card_id == card_id) .ok_or(errors::StorageError::MockDbError)?; Ok(locked_lockers.remove(position)) } } #[cfg(test)] mod tests { #[allow(clippy::unwrap_used)] mod mockdb_locker_mock_up_interface { use common_utils::{generate_customer_id_of_default_length, id_type}; use crate::{ db::{locker_mock_up::LockerMockUpInterface, MockDb}, types::storage, }; pub struct LockerMockUpIds { card_id: String, external_id: String, merchant_id: id_type::MerchantId, customer_id: id_type::CustomerId, } fn create_locker_mock_up_new(locker_ids: LockerMockUpIds) -> storage::LockerMockUpNew { storage::LockerMockUpNew { card_id: locker_ids.card_id, external_id: locker_ids.external_id, card_fingerprint: "card_fingerprint".into(), card_global_fingerprint: "card_global_fingerprint".into(), merchant_id: locker_ids.merchant_id, card_number: "1234123412341234".into(), card_exp_year: "2023".into(), card_exp_month: "06".into(), name_on_card: Some("name_on_card".into()), card_cvc: Some("123".into()), payment_method_id: Some("payment_method_id".into()), customer_id: Some(locker_ids.customer_id), nickname: Some("card_holder_nickname".into()), enc_card_data: Some("enc_card_data".into()), } } #[tokio::test] async fn find_locker_by_card_id() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let _ = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_2".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await; let found_locker = mockdb.find_locker_by_card_id("card_1").await.unwrap(); assert_eq!(created_locker, found_locker) } #[tokio::test] async fn insert_locker_mock_up() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let found_locker = mockdb .lockers .lock() .await .iter() .find(|l| l.card_id == "card_1") .cloned(); assert!(found_locker.is_some()); assert_eq!(created_locker, found_locker.unwrap()) } #[tokio::test] async fn delete_locker_mock_up() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let deleted_locker = mockdb.delete_locker_mock_up("card_1").await.unwrap(); assert_eq!(created_locker, deleted_locker); let exist = mockdb .lockers .lock() .await .iter() .any(|l| l.card_id == "card_1"); assert!(!exist) } } } <file_sep> pack="QBP-A" entity="locker_mock_up" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2022-12-27-172643_update_locker_mock_up/up.sql" -- Your SQL goes here ALTER TABLE locker_mock_up ADD COLUMN payment_method_id VARCHAR(64); <file_sep> pack="QBP-A" entity="locker_mock_up" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2022-12-27-172643_update_locker_mock_up/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE locker_mock_up DROP COLUMN payment_method_id; <file_sep> pack="QBP-A" entity="locker_mock_up" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-05-02-102332_payout_create/up.sql" CREATE type "PayoutStatus" AS ENUM ( 'success', 'failed', 'cancelled', 'pending', 'ineligible', 'requires_creation', 'requires_payout_method_data', 'requires_fulfillment' ); CREATE type "PayoutType" AS ENUM ('card', 'bank'); CREATE TABLE PAYOUT_ATTEMPT ( payout_attempt_id VARCHAR (64) NOT NULL PRIMARY KEY, payout_id VARCHAR (64) NOT NULL, customer_id VARCHAR (64) NOT NULL, merchant_id VARCHAR (64) NOT NULL, address_id VARCHAR (64) NOT NULL, connector VARCHAR (64) NOT NULL, connector_payout_id VARCHAR (128) NOT NULL, payout_token VARCHAR (64), status "PayoutStatus" NOT NULL, is_eligible BOOLEAN, error_message TEXT, error_code VARCHAR (64), business_country "CountryAlpha2", business_label VARCHAR(64), created_at timestamp NOT NULL DEFAULT NOW():: timestamp, last_modified_at timestamp NOT NULL DEFAULT NOW():: timestamp ); CREATE TABLE PAYOUTS ( payout_id VARCHAR (64) NOT NULL PRIMARY KEY, merchant_id VARCHAR (64) NOT NULL, customer_id VARCHAR (64) NOT NULL, address_id VARCHAR (64) NOT NULL, payout_type "PayoutType" NOT NULL, payout_method_id VARCHAR (64), amount BIGINT NOT NULL, destination_currency "Currency" NOT NULL, source_currency "Currency" NOT NULL, description VARCHAR (255), recurring BOOLEAN NOT NULL, auto_fulfill BOOLEAN NOT NULL, return_url VARCHAR (255), entity_type VARCHAR (64) NOT NULL, metadata JSONB DEFAULT '{}':: JSONB, created_at timestamp NOT NULL DEFAULT NOW():: timestamp, last_modified_at timestamp NOT NULL DEFAULT NOW():: timestamp ); CREATE UNIQUE INDEX payout_attempt_index ON PAYOUT_ATTEMPT ( merchant_id, payout_attempt_id, payout_id ); CREATE UNIQUE INDEX payouts_index ON PAYOUTS (merchant_id, payout_id); -- Alterations ALTER TABLE merchant_account ADD COLUMN payout_routing_algorithm JSONB; ALTER TABLE locker_mock_up ADD COLUMN enc_card_data TEXT; ALTER TYPE "ConnectorType" ADD VALUE 'payout_processor'; <file_sep> pack="QBP-A" entity="locker_mock_up" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_locker_mock_up.rs" // schema snippet for entity=locker_mock_up repo=hyperswitch // table: locker_mock_up columns: [] entities: [locker_mock_up] sources: [migration, model_or_query]
query_boundary
<file_sep> pack="QBP-A" entity="mandate" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/mandate.rs" 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>, } #[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>, } impl MandateNew { pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } } #[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: mandate_new.customer_user_agent.clone(), 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(), } } } <file_sep> pack="QBP-A" entity="mandate" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/mandate.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use error_stack::report; use super::generics; use crate::{errors, mandate::*, schema::mandate::dsl, PgPooledConn, StorageResult}; impl MandateNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Mandate> { generics::generic_insert(conn, self).await } } impl Mandate { pub async fn find_by_merchant_id_mandate_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, mandate_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::mandate_id.eq(mandate_id.to_owned())), ) .await } pub async fn find_by_merchant_id_connector_mandate_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_mandate_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_mandate_id.eq(connector_mandate_id.to_owned())), ) .await } pub async fn find_by_merchant_id_customer_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, customer_id: &common_utils::id_type::CustomerId, ) -> 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::customer_id.eq(customer_id.to_owned())), None, None, None, ) .await } //Fix this function once V2 mandate is schema is being built #[cfg(all(feature = "v2", feature = "customer_v2"))] pub async fn find_by_global_customer_id( conn: &PgPooledConn, customer_id: &common_utils::id_type::GlobalCustomerId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::customer_id.eq(customer_id.to_owned()), None, None, None, ) .await } pub async fn update_by_merchant_id_mandate_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, mandate_id: &str, mandate: MandateUpdateInternal, ) -> StorageResult<Self> { <fim_prefix> <|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/mandate.rs<|crate|> router<|op|> update entity=mandate repo=hyperswitch tables=mandate joins=none pack=query_boundary lang=rust_sql<|meta_end|> generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::mandate_id.eq(mandate_id.to_owned())), mandate, ) .await? .first() <fim_suffix> .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating mandate") }) } } <fim_middle> <file_sep> pack="QBP-A" entity="mandate" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/mandate.rs" use common_utils::id_type; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::storage::{self as storage_types, enums::MerchantStorageScheme}, }; #[async_trait::async_trait] pub trait MandateInterface { async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>; // Fix this function once we move to mandate v2 #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_mandate_by_global_customer_id( &self, id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>; async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, mandate: storage_types::Mandate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>; async fn insert_mandate( &self, mandate: storage_types::MandateNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; } #[cfg(feature = "kv_store")] mod storage { use common_utils::{fallback_reverse_lookup_not_found, id_type}; use diesel_models::kv; use error_stack::{report, ResultExt}; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::MandateInterface; use crate::{ connection, core::errors::{self, utils::RedisErrorExt, CustomResult}, db::reverse_lookup::ReverseLookupInterface, services::Store, types::storage::{self as storage_types, enums::MerchantStorageScheme, MandateDbExt}, utils::db_utils, }; #[async_trait::async_trait] impl MandateInterface for Store { #[instrument(skip_all)] async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Mandate::find_by_merchant_id_mandate_id( &conn, merchant_id, mandate_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdMandateId { merchant_id, mandate_id, }; let field = format!("mandate_{}", mandate_id); Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Mandate>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Mandate::find_by_merchant_id_connector_mandate_id( &conn, merchant_id, connector_mandate_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let lookup_id = format!( "mid_{}_conn_mandate_{}", merchant_id.get_string_repr(), connector_mandate_id ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Mandate>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_customer_id(&conn, merchant_id, customer_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_mandate_by_global_customer_id( &self, id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_global_customer_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, mandate: storage_types::Mandate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let key = PartitionKey::MerchantIdMandateId { merchant_id, mandate_id, }; let field = format!("mandate_{}", mandate_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Update(key.clone(), &field, mandate.updated_by.as_deref()), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { storage_types::Mandate::update_by_merchant_id_mandate_id( &conn, merchant_id, mandate_id, mandate_update.convert_to_mandate_update(storage_scheme), ) .await .map_err(|error| report!(errors::StorageError::from(error))) } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); if let diesel_models::MandateUpdate::ConnectorMandateIdUpdate { connector_mandate_id: Some(val), .. } = &mandate_update { let rev_lookup = diesel_models::ReverseLookupNew { sk_id: field.clone(), pk_id: key_str.clone(), lookup_id: format!( "mid_{}_conn_mandate_{}", merchant_id.get_string_repr(), val ), source: "mandate".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(rev_lookup, storage_scheme) .await?; } let m_update = mandate_update.convert_to_mandate_update(storage_scheme); let updated_mandate = m_update.clone().apply_changeset(mandate.clone()); let redis_value = serde_json::to_string(&updated_mandate) .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::MandateUpdate( kv::MandateUpdateMems { orig: mandate, update_data: m_update, }, )), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<diesel_models::Mandate>::Hset( (&field, redis_value), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_mandate) } } } #[instrument(skip_all)] async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::filter_by_constraints(&conn, merchant_id, mandate_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_mandate( &self, mut mandate: storage_types::MandateNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Insert, )) .await; mandate.update_storage_scheme(storage_scheme); match storage_scheme { MerchantStorageScheme::PostgresOnly => mandate .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))), MerchantStorageScheme::RedisKv => { let mandate_id = mandate.mandate_id.clone(); let merchant_id = &mandate.merchant_id.to_owned(); let connector_mandate_id = mandate.connector_mandate_id.clone(); let key = PartitionKey::MerchantIdMandateId { merchant_id, mandate_id: mandate_id.as_str(), }; let key_str = key.to_string(); let field = format!("mandate_{}", mandate_id); let storage_mandate = storage_types::Mandate::from(&mandate); let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Mandate(mandate)), }, }; if let Some(connector_val) = connector_mandate_id { let lookup_id = format!( "mid_{}_conn_mandate_{}", merchant_id.get_string_repr(), connector_val ); let reverse_lookup_entry = diesel_models::ReverseLookupNew { sk_id: field.clone(), pk_id: key_str.clone(), lookup_id, source: "mandate".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup_entry, storage_scheme) .await?; } match Box::pin(kv_wrapper::<diesel_models::Mandate, _, _>( self, KvOperation::<diesel_models::Mandate>::HSetNx( &field, &storage_mandate, redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "mandate", key: Some(storage_mandate.mandate_id), } .into()), Ok(HsetnxReply::KeySet) => Ok(storage_mandate), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } } } #[cfg(not(feature = "kv_store"))] mod storage { use common_utils::id_type; use error_stack::report; use router_env::{instrument, tracing}; use super::MandateInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::storage::{self as storage_types, enums::MerchantStorageScheme, MandateDbExt}, }; #[async_trait::async_trait] impl MandateInterface for Store { #[instrument(skip_all)] async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_mandate_id(&conn, merchant_id, mandate_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_connector_mandate_id( &conn, merchant_id, connector_mandate_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_customer_id(&conn, merchant_id, customer_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } // Need to fix this once we start moving to mandate v2 #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_mandate_by_global_customer_id( &self, customer_id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_global_id(&conn, customer_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, _mandate: storage_types::Mandate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Mandate::update_by_merchant_id_mandate_id( &conn, merchant_id, mandate_id, storage_types::MandateUpdateInternal::from(mandate_update), ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::filter_by_constraints(&conn, merchant_id, mandate_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_mandate( &self, mandate: storage_types::MandateNew, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; mandate .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[async_trait::async_trait] impl MandateInterface for MockDb { async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { self.mandates .lock() .await .iter() .find(|mandate| mandate.merchant_id == *merchant_id && mandate.mandate_id == mandate_id) .cloned() .ok_or_else(|| errors::StorageError::ValueNotFound("mandate not found".to_string())) .map_err(|err| err.into()) } async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { self.mandates .lock() .await .iter() .find(|mandate| { mandate.merchant_id == *merchant_id && mandate.connector_mandate_id == Some(connector_mandate_id.to_string()) }) .cloned() .ok_or_else(|| errors::StorageError::ValueNotFound("mandate not found".to_string())) .map_err(|err| err.into()) } async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { return Ok(self .mandates .lock() .await .iter() .filter(|mandate| { mandate.merchant_id == *merchant_id && &mandate.customer_id == customer_id }) .cloned() .collect()); } // Need to fix this once we move to v2 mandate #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_mandate_by_global_customer_id( &self, id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { todo!() } async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, _mandate: storage_types::Mandate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let mut mandates = self.mandates.lock().await; match mandates .iter_mut() .find(|mandate| mandate.merchant_id == *merchant_id && mandate.mandate_id == mandate_id) { Some(mandate) => { let m_update = diesel_models::MandateUpdateInternal::from(mandate_update); let updated_mandate = m_update.clone().apply_changeset(mandate.clone()); Ok(updated_mandate) } None => { Err(errors::StorageError::ValueNotFound("mandate not found".to_string()).into()) } } } async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let mandates = self.mandates.lock().await; let mandates_iter = mandates.iter().filter(|mandate| { let mut checker = mandate.merchant_id == *merchant_id; if let Some(created_time) = mandate_constraints.created_time { checker &= mandate.created_at == created_time; } if let Some(created_time_lt) = mandate_constraints.created_time_lt { checker &= mandate.created_at < created_time_lt; } if let Some(created_time_gt) = mandate_constraints.created_time_gt { checker &= mandate.created_at > created_time_gt; } if let Some(created_time_lte) = mandate_constraints.created_time_lte { checker &= mandate.created_at <= created_time_lte; } if let Some(created_time_gte) = mandate_constraints.created_time_gte { checker &= mandate.created_at >= created_time_gte; } if let Some(connector) = &mandate_constraints.connector { checker &= mandate.connector == *connector; } if let Some(mandate_status) = mandate_constraints.mandate_status { checker &= mandate.mandate_status == mandate_status; } checker }); #[allow(clippy::as_conversions)] let offset = (if mandate_constraints.offset.unwrap_or(0) < 0 { 0 } else { mandate_constraints.offset.unwrap_or(0) }) as usize; let mandates: Vec<storage_types::Mandate> = if let Some(limit) = mandate_constraints.limit { #[allow(clippy::as_conversions)] mandates_iter .skip(offset) .take((if limit < 0 { 0 } else { limit }) as usize) .cloned() .collect() } else { mandates_iter.skip(offset).cloned().collect() }; Ok(mandates) } async fn insert_mandate( &self, mandate_new: storage_types::MandateNew, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let mut mandates = self.mandates.lock().await; let mandate = storage_types::Mandate { mandate_id: mandate_new.mandate_id.clone(), customer_id: mandate_new.customer_id, merchant_id: mandate_new.merchant_id, original_payment_id: mandate_new.original_payment_id, payment_method_id: mandate_new.payment_method_id, 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, customer_user_agent: mandate_new.customer_user_agent, network_transaction_id: mandate_new.network_transaction_id, previous_attempt_id: mandate_new.previous_attempt_id, 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, connector_mandate_id: mandate_new.connector_mandate_id, start_date: mandate_new.start_date, end_date: mandate_new.end_date, metadata: mandate_new.metadata, connector_mandate_ids: mandate_new.connector_mandate_ids, merchant_connector_id: mandate_new.merchant_connector_id, updated_by: mandate_new.updated_by, }; mandates.push(mandate.clone()); Ok(mandate) } } <file_sep> pack="QBP-A" entity="mandate" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-07-15-143920_change_primary_key_for_mandate/up.sql" -- Your SQL goes here -- The below query will lock the mandate table -- Running this query is not necessary on higher environments -- as the application will work fine without these queries being run -- This query is necessary for the application to not use id in update of mandate -- This query should be run only after the new version of application is deployed ALTER TABLE mandate DROP CONSTRAINT mandate_pkey; -- Use the `mandate_id` column as primary key ALTER TABLE mandate ADD PRIMARY KEY (mandate_id); <file_sep> pack="QBP-A" entity="mandate" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-07-15-143920_change_primary_key_for_mandate/down.sql" ALTER TABLE mandate DROP CONSTRAINT mandate_pkey; ALTER TABLE mandate ADD PRIMARY KEY (id); <file_sep> pack="QBP-A" entity="mandate" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/down.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR(64)` column for tables that had it removed. -- It must be ensured that the deployed version of the application includes the `id` column in any of its queries. -- Re-create the id column as this was used as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account ADD COLUMN id VARCHAR(64); ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account ADD COLUMN id VARCHAR(64); ------------------------ Customers ----------------------- ALTER TABLE customers ADD COLUMN id VARCHAR(64); ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent ADD COLUMN id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt ADD COLUMN id VARCHAR(64); ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods ADD COLUMN id VARCHAR(64); ------------------------ Address ----------------------- ALTER TABLE address ADD COLUMN id VARCHAR(64); ------------------------ Dispute ----------------------- ALTER TABLE dispute ADD COLUMN id VARCHAR(64); ------------------------ Mandate ----------------------- ALTER TABLE mandate ADD COLUMN id VARCHAR(64); ------------------------ Refund ----------------------- ALTER TABLE refund ADD COLUMN id VARCHAR(64); ------------------------ BlockList ----------------------- ALTER TABLE blocklist ADD COLUMN id VARCHAR(64); ------------------------ Roles ----------------------- ALTER TABLE roles ADD COLUMN id VARCHAR(64); ------------------------ Users ----------------------- ALTER TABLE users ADD COLUMN id VARCHAR(64); <file_sep> pack="QBP-A" entity="mandate" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_mandate.rs" // schema snippet for entity=mandate repo=hyperswitch // table: mandate columns: [] entities: [mandate] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/mandate.rs<|crate|> storage_impl<|op|> update entity=mandate repo=hyperswitch tables=mandate joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="mandate" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/mandate.rs" 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>, } #[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>, } impl MandateNew { pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } } #[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: mandate_new.customer_user_agent.clone(), 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(), } } } <file_sep> pack="QBP-B" entity="mandate" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/mandate.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use error_stack::report; use super::generics; use crate::{errors, mandate::*, schema::mandate::dsl, PgPooledConn, StorageResult}; impl MandateNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Mandate> { generics::generic_insert(conn, self).await } } impl Mandate { pub async fn find_by_merchant_id_mandate_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, mandate_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::mandate_id.eq(mandate_id.to_owned())), ) .await } pub async fn find_by_merchant_id_connector_mandate_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_mandate_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_mandate_id.eq(connector_mandate_id.to_owned())), ) .await } pub async fn find_by_merchant_id_customer_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, customer_id: &common_utils::id_type::CustomerId, ) -> 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::customer_id.eq(customer_id.to_owned())), None, None, None, ) .await } //Fix this function once V2 mandate is schema is being built #[cfg(all(feature = "v2", feature = "customer_v2"))] pub async fn find_by_global_customer_id( conn: &PgPooledConn, customer_id: &common_utils::id_type::GlobalCustomerId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::customer_id.eq(customer_id.to_owned()), None, None, None, ) .await } pub async fn update_by_merchant_id_mandate_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, mandate_id: &str, mandate: MandateUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::mandate_id.eq(mandate_id.to_owned())), mandate, ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating mandate") }) } } <file_sep> pack="QBP-B" entity="mandate" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/mandate.rs" use diesel_models::Mandate; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Mandate {} <file_sep> pack="QBP-B" entity="mandate" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-07-15-143920_change_primary_key_for_mandate/up.sql" -- Your SQL goes here -- The below query will lock the mandate table -- Running this query is not necessary on higher environments -- as the application will work fine without these queries being run -- This query is necessary for the application to not use id in update of mandate -- This query should be run only after the new version of application is deployed ALTER TABLE mandate DROP CONSTRAINT mandate_pkey; -- Use the `mandate_id` column as primary key ALTER TABLE mandate ADD PRIMARY KEY (mandate_id); <file_sep> pack="QBP-B" entity="mandate" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-07-15-143920_change_primary_key_for_mandate/down.sql" ALTER TABLE mandate DROP CONSTRAINT mandate_pkey; ALTER TABLE mandate ADD PRIMARY KEY (id); <file_sep> pack="QBP-B" entity="mandate" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/down.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR(64)` column for tables that had it removed. -- It must be ensured that the deployed version of the application includes the `id` column in any of its queries. -- Re-create the id column as this was used as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account ADD COLUMN id VARCHAR(64); ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account ADD COLUMN id VARCHAR(64); ------------------------ Customers ----------------------- ALTER TABLE customers ADD COLUMN id VARCHAR(64); ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent ADD COLUMN id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt ADD COLUMN id VARCHAR(64); ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods ADD COLUMN id VARCHAR(64); ------------------------ Address ----------------------- ALTER TABLE address ADD COLUMN id VARCHAR(64); ------------------------ Dispute ----------------------- ALTER TABLE dispute ADD COLUMN id VARCHAR(64); ------------------------ Mandate ----------------------- ALTER TABLE mandate ADD COLUMN id VARCHAR(64); ------------------------ Refund ----------------------- ALTER TABLE refund ADD COLUMN id VARCHAR(64); ------------------------ BlockList ----------------------- ALTER TABLE blocklist ADD COLUMN id VARCHAR(64); ------------------------ Roles ----------------------- ALTER TABLE roles ADD COLUMN id VARCHAR(64); ------------------------ Users ----------------------- ALTER TABLE users ADD COLUMN id VARCHAR(64); <file_sep> pack="QBP-B" entity="mandate" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_mandate.rs" // schema snippet for entity=mandate repo=hyperswitch // table: mandate columns: [] entities: [mandate] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/merchant_account.rs<|crate|> router<|op|> select entity=merchant_account repo=hyperswitch tables=merchant_account joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="merchant_account" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/merchant_account.rs" 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>, } #[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>, } #[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, } } } /// 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>, } #[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, } } } #[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>, } 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>, } #[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>, } #[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), } } } #[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), } } } <file_sep> pack="QBP-A" entity="merchant_account" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/merchant_account.rs" use common_types::consts::API_VERSION; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] use crate::schema::merchant_account::dsl; #[cfg(feature = "v2")] use crate::schema_v2::merchant_account::dsl; use crate::{ errors, merchant_account::{MerchantAccount, MerchantAccountNew, MerchantAccountUpdateInternal}, PgPooledConn, StorageResult, }; impl MerchantAccountNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantAccount> { generics::generic_insert(conn, self).await } } #[cfg(feature = "v1")] impl MerchantAccount { pub async fn update( self, conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.get_id().to_owned(), merchant_account, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn update_with_specific_fields( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id.eq(identifier.to_owned()), merchant_account, ) .await } pub async fn delete_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id.eq(identifier.to_owned()), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id.eq(identifier.to_owned()), ) .await } pub async fn find_by_publishable_key( conn: &PgPooledConn, publishable_key: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::publishable_key.eq(publishable_key.to_owned()), ) .await } pub async fn list_by_organization_id( conn: &PgPooledConn, organization_id: &common_utils::id_type::OrganizationId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::organization_id .eq(organization_id.to_owned()) .and(dsl::version.eq(API_VERSION)), None, None, None, ) .await } pub async fn list_multiple_merchant_accounts( conn: &PgPooledConn, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id.eq_any(merchant_ids.clone()), None, None, None, ) .await } pub async fn list_all_merchant_accounts( conn: &PgPooledConn, limit: u32, offset: Option<u32>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id.ne_all(vec![""]), Some(i64::from(limit)), offset.map(i64::from), None, ) .await } pub async fn update_all_merchant_accounts( conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Vec<Self>> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id.ne_all(vec![""]), merchant_account, ) .await } } #[cfg(feature = "v2")] impl MerchantAccount { pub async fn update( self, conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.get_id().to_owned(), merchant_account, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn update_with_specific_fields( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, dsl::id.eq(identifier.to_owned()), merchant_account) .await } pub async fn delete_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::id.eq(identifier.to_owned()), ) .await } pub async fn find_by_merchant_id( conn: &PgPooledConn, identifier: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(identifier.to_owned()), ) .await } pub async fn find_by_publishable_key( conn: &PgPooledConn, publishable_key: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::publishable_key.eq(publishable_key.to_owned()), ) .await } pub async fn list_by_organization_id( conn: &PgPooledConn, organization_id: &common_utils::id_type::OrganizationId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::organization_id.eq(organization_id.to_owned()), None, None, None, ) .await } pub async fn list_multiple_merchant_accounts( conn: &PgPooledConn, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >(conn, dsl::id.eq_any(merchant_ids), None, None, None) .await } pub async fn list_all_merchant_accounts( conn: &PgPooledConn, limit: u32, offset: Option<u32>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::id.ne_all(vec![""]), Some(i64::from(limit)), offset.map(i64::from), None, ) .await } pub async fn update_all_merchant_accounts( conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, ) -> StorageResult<Vec<Self>> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::id.ne_all(vec![""]), merchant_account, ) .await } } <file_sep> pack="QBP-A" entity="merchant_account" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/merchant_account.rs" #[cfg(feature = "olap")] use std::collections::HashMap; use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use diesel_models::MerchantAccountUpdateInternal; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use storage_impl::redis::cache::{self, CacheKind, ACCOUNTS_CACHE}; use super::{MasterKeyInterface, MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, db::merchant_key_store::MerchantKeyStoreInterface, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage, }, }; #[async_trait::async_trait] pub trait MerchantAccountInterface where domain::MerchantAccount: Conversion<DstType = storage::MerchantAccount, NewDstType = storage::MerchantAccountNew>, { async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; async fn update_all_merchant_account( &self, merchant_account: storage::MerchantAccountUpdate, ) -> CustomResult<usize, errors::StorageError>; async fn update_merchant( &self, state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError>; #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>; async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError>; #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>; #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, errors::StorageError, >; } #[async_trait::async_trait] impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; merchant_account .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let fetch_func = || async { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { fetch_func() .await? .convert( state, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, merchant_id.get_string_repr(), fetch_func, &ACCOUNTS_CACHE, ) .await? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } } #[instrument(skip_all)] async fn update_merchant( &self, state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; let updated_merchant_account = Conversion::convert(this) .await .change_context(errors::StorageError::EncryptionError)? .update(&conn, merchant_account.into()) .await .map_err(|error| report!(errors::StorageError::from(error)))?; #[cfg(feature = "accounts_cache")] { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; let updated_merchant_account = storage::MerchantAccount::update_with_specific_fields( &conn, merchant_id, merchant_account.into(), ) .await .map_err(|error| report!(errors::StorageError::from(error)))?; #[cfg(feature = "accounts_cache")] { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError> { let fetch_by_pub_key_func = || async { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantAccount::find_by_publishable_key(&conn, publishable_key) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let merchant_account; #[cfg(not(feature = "accounts_cache"))] { merchant_account = fetch_by_pub_key_func().await?; } #[cfg(feature = "accounts_cache")] { merchant_account = cache::get_or_populate_in_memory( self, publishable_key, fetch_by_pub_key_func, &ACCOUNTS_CACHE, ) .await?; } let key_store = self .get_merchant_key_store_by_merchant_id( state, merchant_account.get_id(), &self.get_master_key().to_vec().into(), ) .await?; let domain_merchant_account = merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; Ok((domain_merchant_account, key_store)) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { use futures::future::try_join_all; let conn = connection::pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_by_organization_id(&conn, organization_id) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let db_master_key = self.get_master_key().to_vec().into(); let merchant_key_stores = try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| { self.get_merchant_key_store_by_merchant_id( state, merchant_account.get_id(), &db_master_key, ) })) .await?; let merchant_accounts = try_join_all( encrypted_merchant_accounts .into_iter() .zip(merchant_key_stores.iter()) .map(|(merchant_account, key_store)| async { merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }), ) .await?; Ok(merchant_accounts) } #[instrument(skip_all)] async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; let is_deleted_func = || async { storage::MerchantAccount::delete_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let is_deleted; #[cfg(not(feature = "accounts_cache"))] { is_deleted = is_deleted_func().await?; } #[cfg(feature = "accounts_cache")] { let merchant_account = storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error)))?; is_deleted = is_deleted_func().await?; publish_and_redact_merchant_account_cache(self, &merchant_account).await?; } Ok(is_deleted) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_multiple_merchant_accounts(&conn, merchant_ids) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let db_master_key = self.get_master_key().to_vec().into(); let merchant_key_stores = self .list_multiple_key_stores( state, encrypted_merchant_accounts .iter() .map(|merchant_account| merchant_account.get_id()) .cloned() .collect(), &db_master_key, ) .await?; let key_stores_by_id: HashMap<_, _> = merchant_key_stores .iter() .map(|key_store| (key_store.merchant_id.to_owned(), key_store)) .collect(); let merchant_accounts = futures::future::try_join_all(encrypted_merchant_accounts.into_iter().map( |merchant_account| async { let key_store = key_stores_by_id.get(merchant_account.get_id()).ok_or( errors::StorageError::ValueNotFound(format!( "merchant_key_store with merchant_id = {:?}", merchant_account.get_id() )), )?; merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }, )) .await?; Ok(merchant_accounts) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_and_org_ids( &self, _state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, errors::StorageError, > { let conn = connection::pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_all_merchant_accounts(&conn, limit, offset) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let merchant_and_org_ids = encrypted_merchant_accounts .into_iter() .map(|merchant_account| { let merchant_id = merchant_account.get_id().clone(); let org_id = merchant_account.organization_id; (merchant_id, org_id) }) .collect(); Ok(merchant_and_org_ids) } async fn update_all_merchant_account( &self, merchant_account: storage::MerchantAccountUpdate, ) -> CustomResult<usize, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; let db_func = || async { storage::MerchantAccount::update_all_merchant_accounts( &conn, MerchantAccountUpdateInternal::from(merchant_account), ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let total; #[cfg(not(feature = "accounts_cache"))] { let ma = db_func().await?; total = ma.len(); } #[cfg(feature = "accounts_cache")] { let ma = db_func().await?; publish_and_redact_all_merchant_account_cache(self, &ma).await?; total = ma.len(); } Ok(total) } } #[async_trait::async_trait] impl MerchantAccountInterface for MockDb { #[allow(clippy::panic)] async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let mut accounts = self.merchant_accounts.lock().await; let account = Conversion::convert(merchant_account) .await .change_context(errors::StorageError::EncryptionError)?; accounts.push(account.clone()); account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[allow(clippy::panic)] async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let accounts = self.merchant_accounts.lock().await; accounts .iter() .find(|account| account.get_id() == merchant_id) .cloned() .ok_or(errors::StorageError::ValueNotFound(format!( "Merchant ID: {:?} not found", merchant_id )))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn update_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_account_update: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let merchant_id = merchant_account.get_id().to_owned(); let mut accounts = self.merchant_accounts.lock().await; accounts .iter_mut() .find(|account| account.get_id() == merchant_account.get_id()) .async_map(|account| async { let update = MerchantAccountUpdateInternal::from(merchant_account_update) .apply_changeset( Conversion::convert(merchant_account) .await .change_context(errors::StorageError::EncryptionError)?, ); *account = update.clone(); update .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "Merchant ID: {:?} not found", merchant_id )) .into(), ) } async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account_update: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let mut accounts = self.merchant_accounts.lock().await; accounts .iter_mut() .find(|account| account.get_id() == merchant_id) .async_map(|account| async { let update = MerchantAccountUpdateInternal::from(merchant_account_update) .apply_changeset(account.clone()); *account = update.clone(); update .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "Merchant ID: {:?} not found", merchant_id )) .into(), ) } async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError> { let accounts = self.merchant_accounts.lock().await; let account = accounts .iter() .find(|account| { account .publishable_key .as_ref() .is_some_and(|key| key == publishable_key) }) .ok_or(errors::StorageError::ValueNotFound(format!( "Publishable Key: {} not found", publishable_key )))?; let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await?; let merchant_account = account .clone() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; Ok((merchant_account, key_store)) } async fn update_all_merchant_account( &self, merchant_account_update: storage::MerchantAccountUpdate, ) -> CustomResult<usize, errors::StorageError> { let mut accounts = self.merchant_accounts.lock().await; Ok(accounts.iter_mut().fold(0, |acc, account| { let update = MerchantAccountUpdateInternal::from(merchant_account_update.clone()) .apply_changeset(account.clone()); *account = update; acc + 1 })) } async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let mut accounts = self.merchant_accounts.lock().await; accounts.retain(|x| x.get_id() != merchant_id); Ok(true) } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { let accounts = self.merchant_accounts.lock().await; let futures = accounts .iter() .filter(|account| account.organization_id == *organization_id) .map(|account| async { let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await; match key_store { Ok(key) => account .clone() .convert(state, key.key.get_inner(), key.merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError), Err(err) => Err(err), } }); futures::future::join_all(futures) .await .into_iter() .collect() } #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { let accounts = self.merchant_accounts.lock().await; let futures = accounts .iter() .filter(|account| merchant_ids.contains(account.get_id())) .map(|account| async { let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await; match key_store { Ok(key) => account .clone() .convert(state, key.key.get_inner(), key.merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError), Err(err) => Err(err), } }); futures::future::join_all(futures) .await .into_iter() .collect() } #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, _state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, errors::StorageError, > { let accounts = self.merchant_accounts.lock().await; let limit = limit.try_into().unwrap_or(accounts.len()); let offset = offset.unwrap_or(0).try_into().unwrap_or(0); let merchant_and_org_ids = accounts .iter() .skip(offset) .take(limit) .map(|account| (account.get_id().clone(), account.organization_id.clone())) .collect::<Vec<_>>(); Ok(merchant_and_org_ids) } } #[cfg(feature = "accounts_cache")] async fn publish_and_redact_merchant_account_cache( store: &dyn super::StorageInterface, merchant_account: &storage::MerchantAccount, ) -> CustomResult<(), errors::StorageError> { let publishable_key = merchant_account .publishable_key .as_ref() .map(|publishable_key| CacheKind::Accounts(publishable_key.into())); #[cfg(feature = "v1")] let cgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| { CacheKind::CGraph( format!( "cgraph_{}_{}", merchant_account.get_id().get_string_repr(), profile_id.get_string_repr(), ) .into(), ) }); // TODO: we will not have default profile in v2 #[cfg(feature = "v2")] let cgraph_key = None; let mut cache_keys = vec![CacheKind::Accounts( merchant_account.get_id().get_string_repr().into(), )]; cache_keys.extend(publishable_key.into_iter()); cache_keys.extend(cgraph_key.into_iter()); cache::redact_from_redis_and_publish(store.get_cache_store().as_ref(), cache_keys).await?; Ok(()) } #[cfg(feature = "accounts_cache")] async fn publish_and_redact_all_merchant_account_cache( store: &dyn super::StorageInterface, merchant_accounts: &[storage::MerchantAccount], ) -> CustomResult<(), errors::StorageError> { let merchant_ids = merchant_accounts .iter() .map(|merchant_account| merchant_account.get_id().get_string_repr().to_string()); let publishable_keys = merchant_accounts .iter() .filter_map(|m| m.publishable_key.clone()); let cache_keys: Vec<CacheKind<'_>> = merchant_ids .chain(publishable_keys) .map(|s| CacheKind::Accounts(s.into())) .collect(); cache::redact_from_redis_and_publish(store.get_cache_store().as_ref(), cache_keys).await?; Ok(()) } <file_sep> pack="QBP-A" entity="merchant_account" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-10-101701_recreate_varchar_id_column_for_merchant_account/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE merchant_account DROP id; <file_sep> pack="QBP-A" entity="merchant_account" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-11-062329_add-product-type-column-merchant-account/up.sql" -- Your SQL goes here ALTER TABLE merchant_account ADD COLUMN IF NOT EXISTS product_type VARCHAR(64); <file_sep> pack="QBP-A" entity="merchant_account" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-11-062329_add-product-type-column-merchant-account/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE merchant_account DROP product_type; <file_sep> pack="QBP-A" entity="merchant_account" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_merchant_account.rs" // schema snippet for entity=merchant_account repo=hyperswitch // table: merchant_account columns: [] entities: [merchant_account] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/merchant_key_store.rs<|crate|> router<|op|> select entity=merchant_key_store repo=hyperswitch tables=merchant_key_store joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="merchant_key_store" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/merchant_key_store.rs" use common_utils::{custom_serde, encryption::Encryption}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::schema::merchant_key_store; #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_key_store, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantKeyStore { pub merchant_id: common_utils::id_type::MerchantId, pub key: Encryption, #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, } #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Insertable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_key_store)] pub struct MerchantKeyStoreNew { pub merchant_id: common_utils::id_type::MerchantId, pub key: Encryption, pub created_at: PrimitiveDateTime, } #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, AsChangeset, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_key_store)] pub struct MerchantKeyStoreUpdateInternal { pub merchant_id: common_utils::id_type::MerchantId, pub key: Encryption, } <file_sep> pack="QBP-A" entity="merchant_key_store" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/merchant_key_store.rs" use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ merchant_key_store::{MerchantKeyStore, MerchantKeyStoreNew}, schema::merchant_key_store::dsl, PgPooledConn, StorageResult, }; impl MerchantKeyStoreNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantKeyStore> { generics::generic_insert(conn, self).await } } impl MerchantKeyStore { pub async fn find_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), ) .await } pub async fn delete_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), ) .await } pub async fn list_multiple_key_stores( conn: &PgPooledConn, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, _, >( conn, dsl::merchant_id.eq_any(merchant_ids), None, None, None, ) .await } pub async fn list_all_key_stores( conn: &PgPooledConn, from: u32, limit: u32, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, _, >( conn, dsl::merchant_id.ne_all(vec!["".to_string()]), Some(limit.into()), Some(from.into()), None, ) .await } } <file_sep> pack="QBP-A" entity="merchant_key_store" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/merchant_key_store.rs" use common_utils::types::keymanager::KeyManagerState; use error_stack::{report, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use storage_impl::redis::cache::{self, CacheKind, ACCOUNTS_CACHE}; use crate::{ connection, core::errors::{self, CustomResult}, db::MockDb, services::Store, types::domain::{ self, behaviour::{Conversion, ReverseConversion}, }, }; #[async_trait::async_trait] pub trait MerchantKeyStoreInterface { async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>; async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>; async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError>; #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; } #[async_trait::async_trait] impl MerchantKeyStoreInterface for Store { #[instrument(skip_all)] async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; let merchant_id = merchant_key_store.merchant_id.clone(); merchant_key_store .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert(state, key, merchant_id.into()) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { let fetch_func = || async { let conn = connection::pg_accounts_connection_read(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::find_by_merchant_id( &conn, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { fetch_func() .await? .convert(state, key, merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "accounts_cache")] { let key_store_cache_key = format!("merchant_key_store_{}", merchant_id.get_string_repr()); cache::get_or_populate_in_memory( self, &key_store_cache_key, fetch_func, &ACCOUNTS_CACHE, ) .await? .convert(state, key, merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) } } #[instrument(skip_all)] async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let delete_func = || async { let conn = connection::pg_accounts_connection_write(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::delete_by_merchant_id( &conn, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { delete_func().await } #[cfg(feature = "accounts_cache")] { let key_store_cache_key = format!("merchant_key_store_{}", merchant_id.get_string_repr()); cache::publish_and_redact( self, CacheKind::Accounts(key_store_cache_key.into()), delete_func, ) .await } } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let fetch_func = || async { let conn = connection::pg_accounts_connection_read(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::list_multiple_key_stores( &conn, merchant_ids, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { let merchant_id = key_store.merchant_id.clone(); key_store .convert(state, key, merchant_id.into()) .await .change_context(errors::StorageError::DecryptionError) })) .await } async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; let stores = diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores( &conn, from, to, ) .await .map_err(|err| report!(errors::StorageError::from(err)))?; futures::future::try_join_all(stores.into_iter().map(|key_store| async { let merchant_id = key_store.merchant_id.clone(); key_store .convert(state, key, merchant_id.into()) .await .change_context(errors::StorageError::DecryptionError) })) .await } } #[async_trait::async_trait] impl MerchantKeyStoreInterface for MockDb { async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { let mut locked_merchant_key_store = self.merchant_key_store.lock().await; if locked_merchant_key_store .iter() .any(|merchant_key| merchant_key.merchant_id == merchant_key_store.merchant_id) { Err(errors::StorageError::DuplicateValue { entity: "merchant_key_store", key: Some(merchant_key_store.merchant_id.get_string_repr().to_owned()), })?; } let merchant_key = Conversion::convert(merchant_key_store) .await .change_context(errors::StorageError::MockDbError)?; locked_merchant_key_store.push(merchant_key.clone()); let merchant_id = merchant_key.merchant_id.clone(); merchant_key .convert(state, key, merchant_id.into()) .await .change_context(errors::StorageError::DecryptionError) } async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { self.merchant_key_store .lock() .await .iter() .find(|merchant_key| merchant_key.merchant_id == *merchant_id) .cloned() .ok_or(errors::StorageError::ValueNotFound(String::from( "merchant_key_store", )))? .convert(state, key, merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) } async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let mut merchant_key_stores = self.merchant_key_store.lock().await; let index = merchant_key_stores .iter() .position(|mks| mks.merchant_id == *merchant_id) .ok_or(errors::StorageError::ValueNotFound(format!( "No merchant key store found for merchant_id = {:?}", merchant_id )))?; merchant_key_stores.remove(index); Ok(true) } #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; futures::future::try_join_all( merchant_key_stores .iter() .filter(|merchant_key| merchant_ids.contains(&merchant_key.merchant_id)) .map(|merchant_key| async { merchant_key .to_owned() .convert(state, key, merchant_key.merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }), ) .await } async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, _from: u32, _to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async { merchant_key .to_owned() .convert(state, key, merchant_key.merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) })) .await } } #[cfg(test)] mod tests { use std::{borrow::Cow, sync::Arc}; use common_utils::{type_name, types::keymanager::Identifier}; use time::macros::datetime; use tokio::sync::oneshot; use crate::{ db::{merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb}, routes::{ self, app::{settings::Settings, StorageImpl}, }, services, types::domain, }; #[allow(clippy::unwrap_used, clippy::expect_used)] #[tokio::test] async fn test_mock_db_merchant_key_store_interface() { let conf = Settings::new().expect("invalid settings"); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); #[allow(clippy::expect_used)] let mock_db = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create mock DB"); let master_key = mock_db.get_master_key(); let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant1")).unwrap(); let identifier = Identifier::Merchant(merchant_id.clone()); let key_manager_state = &state.into(); let merchant_key1 = mock_db .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), identifier.clone(), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let found_merchant_key1 = mock_db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); assert_eq!(found_merchant_key1.merchant_id, merchant_key1.merchant_id); assert_eq!(found_merchant_key1.key, merchant_key1.key); let insert_duplicate_merchant_key1_result = mock_db .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), identifier.clone(), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await; assert!(insert_duplicate_merchant_key1_result.is_err()); let non_existent_merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("non_existent")).unwrap(); let find_non_existent_merchant_key_result = mock_db .get_merchant_key_store_by_merchant_id( key_manager_state, &non_existent_merchant_id, &master_key.to_vec().into(), ) .await; assert!(find_non_existent_merchant_key_result.is_err()); let find_merchant_key_with_incorrect_master_key_result = mock_db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &vec![0; 32].into(), ) .await; assert!(find_merchant_key_with_incorrect_master_key_result.is_err()); } } <file_sep> pack="QBP-A" entity="merchant_key_store" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-04-06-092008_create_merchant_ek/up.sql" CREATE TABLE merchant_key_store( merchant_id VARCHAR(255) NOT NULL PRIMARY KEY, key bytea NOT NULL, created_at TIMESTAMP NOT NULL ); <file_sep> pack="QBP-A" entity="merchant_key_store" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-04-06-092008_create_merchant_ek/down.sql" DROP TABLE merchant_key_store; <file_sep> pack="QBP-A" entity="merchant_key_store" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_merchant_key_store.rs" // schema snippet for entity=merchant_key_store repo=hyperswitch // table: merchant_key_store columns: [] entities: [merchant_key_store] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/organization.rs<|crate|> router<|op|> select entity=organization repo=hyperswitch tables=organization joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="organization" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/organization.rs" 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, } #[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, } #[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, } = 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, } } } #[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, } = org_new; Self { id, organization_name, organization_details, metadata, created_at, modified_at, version, } } } #[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, } #[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, } #[cfg(feature = "v1")] impl OrganizationNew { pub fn new(id: id_type::OrganizationId, 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, } } } #[cfg(feature = "v2")] impl OrganizationNew { pub fn new(id: id_type::OrganizationId, 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, } } } #[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, } #[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, } pub enum OrganizationUpdate { Update { organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, }, } #[cfg(feature = "v1")] impl From<OrganizationUpdate> for OrganizationUpdateInternal { fn from(value: OrganizationUpdate) -> Self { match value { OrganizationUpdate::Update { organization_name, organization_details, metadata, } => Self { org_name: organization_name.clone(), organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), }, } } } #[cfg(feature = "v2")] impl From<OrganizationUpdate> for OrganizationUpdateInternal { fn from(value: OrganizationUpdate) -> Self { match value { OrganizationUpdate::Update { organization_name, organization_details, metadata, } => Self { organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), }, } } } #[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_sep> pack="QBP-A" entity="organization" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/organization.rs" use common_utils::id_type; use diesel::{associations::HasTable, ExpressionMethods}; #[cfg(feature = "v1")] use crate::schema::organization::dsl::org_id as dsl_identifier; #[cfg(feature = "v2")] use crate::schema_v2::organization::dsl::id as dsl_identifier; use crate::{organization::*, query::generics, PgPooledConn, StorageResult}; impl OrganizationNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Organization> { generics::generic_insert(conn, self).await } } impl Organization { pub async fn find_by_org_id( conn: &PgPooledConn, org_id: id_type::OrganizationId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl_identifier.eq(org_id), ) .await } pub async fn update_by_org_id( conn: &PgPooledConn, org_id: id_type::OrganizationId, update: OrganizationUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl_identifier.eq(org_id), OrganizationUpdateInternal::from(update), ) .await } } <file_sep> pack="QBP-A" entity="organization" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/organization.rs" use common_utils::{errors::CustomResult, id_type}; use diesel_models::{organization as storage, organization::OrganizationBridge}; use error_stack::report; use router_env::{instrument, tracing}; use crate::{connection, core::errors, services::Store}; #[async_trait::async_trait] pub trait OrganizationInterface { async fn insert_organization( &self, organization: storage::OrganizationNew, ) -> CustomResult<storage::Organization, errors::StorageError>; async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Organization, errors::StorageError>; async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: storage::OrganizationUpdate, ) -> CustomResult<storage::Organization, errors::StorageError>; } #[async_trait::async_trait] impl OrganizationInterface for Store { #[instrument(skip_all)] async fn insert_organization( &self, organization: storage::OrganizationNew, ) -> CustomResult<storage::Organization, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; organization .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Organization, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::Organization::find_by_org_id(&conn, org_id.to_owned()) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: storage::OrganizationUpdate, ) -> CustomResult<storage::Organization, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; storage::Organization::update_by_org_id(&conn, org_id.to_owned(), update) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl OrganizationInterface for super::MockDb { async fn insert_organization( &self, organization: storage::OrganizationNew, ) -> CustomResult<storage::Organization, errors::StorageError> { let mut organizations = self.organizations.lock().await; if organizations .iter() .any(|org| org.get_organization_id() == organization.get_organization_id()) { Err(errors::StorageError::DuplicateValue { entity: "org_id", key: None, })? } let org = storage::Organization::new(organization); organizations.push(org.clone()); Ok(org) } async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Organization, errors::StorageError> { let organizations = self.organizations.lock().await; organizations .iter() .find(|org| org.get_organization_id() == *org_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No organization available for org_id = {:?}", org_id )) .into(), ) } async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: storage::OrganizationUpdate, ) -> CustomResult<storage::Organization, errors::StorageError> { let mut organizations = self.organizations.lock().await; organizations .iter_mut() .find(|org| org.get_organization_id() == *org_id) .map(|org| match &update { storage::OrganizationUpdate::Update { organization_name, organization_details, metadata, } => { organization_name .as_ref() .map(|org_name| org.set_organization_name(org_name.to_owned())); organization_details.clone_into(&mut org.organization_details); metadata.clone_into(&mut org.metadata); org } }) .ok_or( errors::StorageError::ValueNotFound(format!( "No organization available for org_id = {:?}", org_id )) .into(), ) .cloned() } } <file_sep> pack="QBP-A" entity="organization" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql" ALTER TABLE ORGANIZATION ADD COLUMN org_id VARCHAR(32), ADD COLUMN org_name TEXT; ALTER TABLE merchant_account ADD COLUMN merchant_id VARCHAR(64), ADD COLUMN return_url VARCHAR(255), ADD COLUMN enable_payment_response_hash BOOLEAN DEFAULT FALSE, ADD COLUMN payment_response_hash_key VARCHAR(255), ADD COLUMN redirect_to_merchant_with_http_post BOOLEAN DEFAULT FALSE, ADD COLUMN sub_merchants_enabled BOOLEAN DEFAULT FALSE, ADD COLUMN parent_merchant_id VARCHAR(64), ADD COLUMN locker_id VARCHAR(64), ADD COLUMN intent_fulfillment_time BIGINT, ADD COLUMN default_profile VARCHAR(64), ADD COLUMN payment_link_config JSONB NULL, ADD COLUMN pm_collect_link_config JSONB NULL, ADD COLUMN is_recon_enabled BOOLEAN, ADD COLUMN webhook_details JSON NULL, ADD COLUMN routing_algorithm JSON, ADD COLUMN frm_routing_algorithm JSONB, ADD COLUMN payout_routing_algorithm JSONB; -- The default value is for temporary purpose only ALTER TABLE merchant_account ADD COLUMN primary_business_details JSON; ALTER TABLE business_profile ADD COLUMN profile_id VARCHAR(64), ADD COLUMN routing_algorithm JSON DEFAULT NULL, ADD COLUMN intent_fulfillment_time BIGINT DEFAULT NULL, ADD COLUMN frm_routing_algorithm JSONB DEFAULT NULL, ADD COLUMN payout_routing_algorithm JSONB DEFAULT NULL; ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS business_country "CountryAlpha2", ADD COLUMN IF NOT EXISTS business_label VARCHAR(255), ADD COLUMN IF NOT EXISTS business_sub_label VARCHAR(64), ADD COLUMN IF NOT EXISTS test_mode BOOLEAN, ADD COLUMN IF NOT EXISTS frm_configs jsonb, ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(128); ALTER TABLE customers ADD COLUMN customer_id VARCHAR(64), ADD COLUMN address_id VARCHAR(64); ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS payment_id VARCHAR(64), ADD COLUMN connector_id VARCHAR(64), ADD COLUMN shipping_address_id VARCHAR(64), ADD COLUMN billing_address_id VARCHAR(64), ADD COLUMN shipping_details BYTEA, ADD COLUMN billing_details BYTEA, ADD COLUMN statement_descriptor_suffix VARCHAR(255), ADD COLUMN business_country "CountryAlpha2", ADD COLUMN business_label VARCHAR(64), ADD COLUMN incremental_authorization_allowed BOOLEAN, ADD COLUMN merchant_decision VARCHAR(64), ADD COLUMN fingerprint_id VARCHAR(64), ADD COLUMN statement_descriptor_name VARCHAR(255), ADD COLUMN amount_to_capture BIGINT, ADD COLUMN off_session BOOLEAN, ADD COLUMN payment_confirm_source "PaymentSource", ADD COLUMN merchant_order_reference_id VARCHAR(255), ADD COLUMN is_payment_processor_token_flow BOOLEAN, ADD COLUMN charges jsonb; ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS attempt_id VARCHAR(64), ADD COLUMN amount bigint, ADD COLUMN currency "Currency", ADD COLUMN save_to_locker BOOLEAN, ADD COLUMN offer_amount bigint, ADD COLUMN payment_method VARCHAR, ADD COLUMN connector_transaction_id VARCHAR(128), ADD COLUMN connector_transaction_data VARCHAR(512), ADD COLUMN processor_transaction_data text, ADD COLUMN capture_method "CaptureMethod", ADD COLUMN capture_on TIMESTAMP, ADD COLUMN mandate_id VARCHAR(64), ADD COLUMN payment_method_type VARCHAR(64), ADD COLUMN business_sub_label VARCHAR(64), ADD COLUMN mandate_details JSONB, ADD COLUMN mandate_data JSONB, ADD COLUMN tax_amount bigint, ADD COLUMN straight_through_algorithm JSONB, ADD COLUMN confirm BOOLEAN, ADD COLUMN authentication_data JSON, ADD COLUMN payment_method_billing_address_id VARCHAR(64), ADD COLUMN connector_mandate_detail JSONB, ADD COLUMN charge_id VARCHAR(64); -- Create the index which was dropped because of dropping the column CREATE INDEX payment_attempt_connector_transaction_id_merchant_id_index ON payment_attempt (connector_transaction_id, merchant_id); CREATE UNIQUE INDEX payment_attempt_payment_id_merchant_id_attempt_id_index ON payment_attempt (payment_id, merchant_id, attempt_id); -- Payment Methods CREATE TYPE "PaymentMethodIssuerCode" AS ENUM ( 'jp_hdfc', 'jp_icici', 'jp_googlepay', 'jp_applepay', 'jp_phonepe', 'jp_wechat', 'jp_sofort', 'jp_giropay', 'jp_sepa', 'jp_bacs' ); ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS payment_method_id VARCHAR(64), ADD COLUMN IF NOT EXISTS accepted_currency "Currency" [ ], ADD COLUMN IF NOT EXISTS scheme VARCHAR(32), ADD COLUMN IF NOT EXISTS token VARCHAR(128), ADD COLUMN IF NOT EXISTS cardholder_name VARCHAR(255), ADD COLUMN IF NOT EXISTS issuer_name VARCHAR(64), ADD COLUMN IF NOT EXISTS issuer_country VARCHAR(64), ADD COLUMN IF NOT EXISTS payer_country TEXT [ ], ADD COLUMN IF NOT EXISTS is_stored BOOLEAN, ADD COLUMN IF NOT EXISTS direct_debit_token VARCHAR(128), ADD COLUMN IF NOT EXISTS swift_code VARCHAR(32), ADD COLUMN IF NOT EXISTS payment_method_issuer VARCHAR(128), ADD COLUMN IF NOT EXISTS metadata JSON, ADD COLUMN IF NOT EXISTS payment_method VARCHAR, ADD COLUMN IF NOT EXISTS payment_method_type VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_issuer_code "PaymentMethodIssuerCode"; ALTER TABLE refund ADD COLUMN connector_refund_data VARCHAR(512), ADD COLUMN connector_transaction_data VARCHAR(512); ALTER TABLE captures ADD COLUMN connector_capture_data VARCHAR(512); ALTER TABLE refund ADD COLUMN IF NOT EXISTS internal_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS refund_id VARCHAR(64), ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(64); <file_sep> pack="QBP-A" entity="organization" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-03-04-053541_add_api_version_to_organization/up.sql" -- Your SQL goes here ALTER TABLE organization ADD COLUMN IF NOT EXISTS version "ApiVersion" NOT NULL DEFAULT 'v1'; <file_sep> pack="QBP-A" entity="organization" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-03-04-053541_add_api_version_to_organization/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE organization DROP COLUMN version; <file_sep> pack="QBP-A" entity="organization" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_organization.rs" // schema snippet for entity=organization repo=hyperswitch // table: organization columns: [] entities: [organization] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/payments/payment_intent.rs<|crate|> storage_impl<|op|> select entity=payment_intent repo=hyperswitch tables=payment_intent joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="payment_intent" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/payment_intent.rs" use common_enums::{PaymentMethodType, RequestIncrementalAuthorization}; use common_types::primitive_wrappers::RequestExtendedAuthorizationBool; use common_utils::{encryption::Encryption, pii, types::MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::schema::payment_intent; #[cfg(feature = "v2")] use crate::schema_v2::payment_intent; #[cfg(feature = "v2")] use crate::types::{FeatureMetadata, OrderDetailsWithAmount}; use crate::{business_profile::PaymentLinkBackgroundImageConfig, enums as storage_enums}; #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: storage_enums::Currency, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::GlobalCustomerId>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub attempt_count: i16, pub profile_id: common_utils::id_type::ProfileId, pub payment_link_id: Option<String>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<serde_json::Value>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub enable_payment_link: Option<bool>, pub apply_mit_exemption: Option<bool>, pub customer_present: Option<bool>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub id: common_utils::id_type::GlobalPaymentId, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<serde_json::Value>, pub connector_metadata: Option<serde_json::Value>, pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, pub profile_id: Option<common_utils::id_type::ProfileId>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PaymentLinkConfigRequestForPayments { /// custom theme for the payment link pub theme: Option<String>, /// merchant display logo pub logo: Option<String>, /// Custom merchant name for payment link pub seller_name: Option<String>, /// Custom layout for sdk pub sdk_layout: Option<String>, /// Display only the sdk for payment link pub display_sdk_only: Option<bool>, /// Enable saved payment method option for payment link pub enabled_saved_payment_method: Option<bool>, /// Hide card nickname field option for payment link pub hide_card_nickname_field: Option<bool>, /// Show card form by default for payment link pub show_card_form_by_default: Option<bool>, /// Dynamic details related to merchant to be rendered in payment link pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>, /// Configurations for the background image for details section pub background_image: Option<PaymentLinkBackgroundImageConfig>, /// Custom layout for details section pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>, /// Text for payment link's handle confirm button pub payment_button_text: Option<String>, /// Skip the status screen after payment completion pub skip_status_screen: Option<bool>, /// Text for customizing message for card terms pub custom_message_for_card_terms: Option<String>, /// Custom background colour for payment link's handle confirm button pub payment_button_colour: Option<String>, /// Custom text colour for payment link's handle confirm button pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, /// SDK configuration rules pub sdk_ui_rules: Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: Option<bool>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct PaymentLinkTransactionDetails { /// Key for the transaction details pub key: String, /// Value for the transaction details pub value: String, /// UI configuration for the transaction details pub ui_configuration: Option<TransactionDetailsUiConfiguration>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkTransactionDetails); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct TransactionDetailsUiConfiguration { /// Position of the key-value pair in the UI pub position: Option<i8>, /// Whether the key should be bold pub is_key_bold: Option<bool>, /// Whether the value should be bold pub is_value_bold: Option<bool>, } common_utils::impl_to_sql_from_sql_json!(TransactionDetailsUiConfiguration); #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct TaxDetails { /// This is the tax related information that is calculated irrespective of any payment method. /// This is calculated when the order is created with shipping details pub default: Option<DefaultTax>, /// This is the tax related information that is calculated based on the payment method /// This is calculated when calling the /calculate_tax API pub payment_method_type: Option<PaymentMethodTypeTax>, } impl TaxDetails { /// Get the tax amount /// If default tax is present, return the default tax amount /// If default tax is not present, return the tax amount based on the payment method if it matches the provided payment method type pub fn get_tax_amount(&self, payment_method: Option<PaymentMethodType>) -> Option<MinorUnit> { self.payment_method_type .as_ref() .zip(payment_method) .filter(|(payment_method_type_tax, payment_method)| { payment_method_type_tax.pmt == *payment_method }) .map(|(payment_method_type_tax, _)| payment_method_type_tax.order_tax_amount) .or_else(|| self.get_default_tax_amount()) } /// Get the default tax amount pub fn get_default_tax_amount(&self) -> Option<MinorUnit> { self.default .as_ref() .map(|default_tax_details| default_tax_details.order_tax_amount) } } common_utils::impl_to_sql_from_sql_json!(TaxDetails); #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PaymentMethodTypeTax { pub order_tax_amount: MinorUnit, pub pmt: PaymentMethodType, } #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DefaultTax { pub order_tax_amount: MinorUnit, } #[cfg(feature = "v2")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: storage_enums::Currency, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::GlobalCustomerId>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub attempt_count: i16, pub profile_id: common_utils::id_type::ProfileId, pub payment_link_id: Option<String>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<serde_json::Value>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub enable_payment_link: Option<bool>, pub apply_mit_exemption: Option<bool>, pub id: common_utils::id_type::GlobalPaymentId, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, } #[cfg(feature = "v1")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<serde_json::Value>, pub connector_metadata: Option<serde_json::Value>, pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_decision: Option<String>, pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { /// Update the payment intent details on payment intent confirmation, before calling the connector ConfirmIntent { status: storage_enums::IntentStatus, active_attempt_id: common_utils::id_type::GlobalAttemptId, updated_by: String, }, /// Update the payment intent details on payment intent confirmation, after calling the connector ConfirmIntentPostUpdate { status: storage_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, }, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { ResponseUpdate { status: storage_enums::IntentStatus, amount_captured: Option<MinorUnit>, fingerprint_id: Option<String>, updated_by: String, incremental_authorization_allowed: Option<bool>, }, MetadataUpdate { metadata: serde_json::Value, updated_by: String, }, Update(Box<PaymentIntentUpdateFields>), PaymentCreateUpdate { return_url: Option<String>, status: Option<storage_enums::IntentStatus>, customer_id: Option<common_utils::id_type::CustomerId>, shipping_address_id: Option<String>, billing_address_id: Option<String>, customer_details: Option<Encryption>, updated_by: String, }, MerchantStatusUpdate { status: storage_enums::IntentStatus, shipping_address_id: Option<String>, billing_address_id: Option<String>, updated_by: String, }, PGStatusUpdate { status: storage_enums::IntentStatus, updated_by: String, incremental_authorization_allowed: Option<bool>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, attempt_count: i16, updated_by: String, }, StatusAndAttemptUpdate { status: storage_enums::IntentStatus, active_attempt_id: String, attempt_count: i16, updated_by: String, }, ApproveUpdate { status: storage_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, RejectUpdate { status: storage_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, SurchargeApplicableUpdate { surcharge_applicable: Option<bool>, updated_by: String, }, IncrementalAuthorizationAmountUpdate { amount: MinorUnit, }, AuthorizationCountUpdate { authorization_count: i32, }, CompleteAuthorizeUpdate { shipping_address_id: Option<String>, }, ManualUpdate { status: Option<storage_enums::IntentStatus>, updated_by: String, }, SessionResponseUpdate { tax_details: TaxDetails, shipping_address_id: Option<String>, updated_by: String, shipping_details: Option<Encryption>, }, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub status: storage_enums::IntentStatus, pub customer_id: Option<common_utils::id_type::CustomerId>, pub shipping_address: Option<Encryption>, pub billing_address: Option<Encryption>, pub return_url: Option<String>, pub description: Option<String>, pub statement_descriptor: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub is_payment_processor_token_flow: Option<bool>, pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub status: storage_enums::IntentStatus, pub customer_id: Option<common_utils::id_type::CustomerId>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub return_url: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<serde_json::Value>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<TaxDetails>, pub force_3ds_challenge: Option<bool>, } // TODO: uncomment fields as necessary #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { pub status: Option<storage_enums::IntentStatus>, pub prerouting_algorithm: Option<serde_json::Value>, pub amount_captured: Option<MinorUnit>, pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<Option<common_utils::id_type::GlobalAttemptId>>, pub amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub shipping_cost: Option<MinorUnit>, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub surcharge_applicable: Option<bool>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub customer_present: Option<bool>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub apply_mit_exemption: Option<bool>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub session_expiry: Option<PrimitiveDateTime>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub request_external_three_ds_authentication: Option<bool>, pub updated_by: String, pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { pub amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub status: Option<storage_enums::IntentStatus>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub return_url: Option<String>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub metadata: Option<serde_json::Value>, pub billing_address_id: Option<String>, pub shipping_address_id: Option<String>, pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub attempt_count: Option<i16>, pub merchant_decision: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<TaxDetails>, pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v1")] impl PaymentIntentUpdate { pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { let PaymentIntentUpdateInternal { amount, currency, status, amount_captured, customer_id, return_url, setup_future_usage, off_session, metadata, billing_address_id, shipping_address_id, modified_at: _, active_attempt_id, business_country, business_label, description, statement_descriptor_name, statement_descriptor_suffix, order_details, attempt_count, merchant_decision, payment_confirm_source, updated_by, surcharge_applicable, incremental_authorization_allowed, authorization_count, session_expiry, fingerprint_id, request_external_three_ds_authentication, frm_metadata, customer_details, billing_details, merchant_order_reference_id, shipping_details, is_payment_processor_token_flow, tax_details, force_3ds_challenge, } = self.into(); PaymentIntent { amount: amount.unwrap_or(source.amount), currency: currency.or(source.currency), status: status.unwrap_or(source.status), amount_captured: amount_captured.or(source.amount_captured), customer_id: customer_id.or(source.customer_id), return_url: return_url.or(source.return_url), setup_future_usage: setup_future_usage.or(source.setup_future_usage), off_session: off_session.or(source.off_session), metadata: metadata.or(source.metadata), billing_address_id: billing_address_id.or(source.billing_address_id), shipping_address_id: shipping_address_id.or(source.shipping_address_id), modified_at: common_utils::date_time::now(), active_attempt_id: active_attempt_id.unwrap_or(source.active_attempt_id), business_country: business_country.or(source.business_country), business_label: business_label.or(source.business_label), description: description.or(source.description), statement_descriptor_name: statement_descriptor_name .or(source.statement_descriptor_name), statement_descriptor_suffix: statement_descriptor_suffix .or(source.statement_descriptor_suffix), order_details: order_details.or(source.order_details), attempt_count: attempt_count.unwrap_or(source.attempt_count), merchant_decision: merchant_decision.or(source.merchant_decision), payment_confirm_source: payment_confirm_source.or(source.payment_confirm_source), updated_by, surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable), incremental_authorization_allowed: incremental_authorization_allowed .or(source.incremental_authorization_allowed), authorization_count: authorization_count.or(source.authorization_count), fingerprint_id: fingerprint_id.or(source.fingerprint_id), session_expiry: session_expiry.or(source.session_expiry), request_external_three_ds_authentication: request_external_three_ds_authentication .or(source.request_external_three_ds_authentication), frm_metadata: frm_metadata.or(source.frm_metadata), customer_details: customer_details.or(source.customer_details), billing_details: billing_details.or(source.billing_details), merchant_order_reference_id: merchant_order_reference_id .or(source.merchant_order_reference_id), shipping_details: shipping_details.or(source.shipping_details), is_payment_processor_token_flow: is_payment_processor_token_flow .or(source.is_payment_processor_token_flow), tax_details: tax_details.or(source.tax_details), force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge), ..source } } } #[cfg(feature = "v1")] impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fn from(payment_intent_update: PaymentIntentUpdate) -> Self { match payment_intent_update { PaymentIntentUpdate::MetadataUpdate { metadata, updated_by, } => Self { metadata: Some(metadata), modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::Update(value) => Self { amount: Some(value.amount), currency: Some(value.currency), setup_future_usage: value.setup_future_usage, status: Some(value.status), customer_id: value.customer_id, shipping_address_id: value.shipping_address_id, billing_address_id: value.billing_address_id, return_url: value.return_url, business_country: value.business_country, business_label: value.business_label, description: value.description, statement_descriptor_name: value.statement_descriptor_name, statement_descriptor_suffix: value.statement_descriptor_suffix, order_details: value.order_details, metadata: value.metadata, payment_confirm_source: value.payment_confirm_source, updated_by: value.updated_by, session_expiry: value.session_expiry, fingerprint_id: value.fingerprint_id, request_external_three_ds_authentication: value .request_external_three_ds_authentication, frm_metadata: value.frm_metadata, customer_details: value.customer_details, billing_details: value.billing_details, merchant_order_reference_id: value.merchant_order_reference_id, shipping_details: value.shipping_details, amount_captured: None, off_session: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, attempt_count: None, merchant_decision: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, is_payment_processor_token_flow: value.is_payment_processor_token_flow, tax_details: None, force_3ds_challenge: value.force_3ds_challenge, }, PaymentIntentUpdate::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details, updated_by, } => Self { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details, modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, amount_captured: None, setup_future_usage: None, off_session: None, metadata: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::PGStatusUpdate { status, updated_by, incremental_authorization_allowed, } => Self { status: Some(status), modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::MerchantStatusUpdate { status, shipping_address_id, billing_address_id, updated_by, } => Self { status: Some(status), shipping_address_id, billing_address_id, modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::ResponseUpdate { // amount, // currency, status, amount_captured, fingerprint_id, // customer_id, updated_by, incremental_authorization_allowed, } => Self { // amount, // currency: Some(currency), status: Some(status), amount_captured, fingerprint_id, // customer_id, return_url: None, modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, amount: None, currency: None, customer_id: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, authorization_count: None, session_expiry: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, attempt_count, updated_by, } => Self { active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::StatusAndAttemptUpdate { status, active_attempt_id, attempt_count, updated_by, } => Self { status: Some(status), active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::ApproveUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::RejectUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable, updated_by, } => Self { surcharge_applicable, updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self { amount: Some(amount), currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count, } => Self { authorization_count: Some(authorization_count), amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::CompleteAuthorizeUpdate { shipping_address_id, } => Self { shipping_address_id, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self { status, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::SessionResponseUpdate { tax_details, shipping_address_id, updated_by, shipping_details, } => Self { shipping_address_id, amount: None, tax_details: Some(tax_details), currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details, is_payment_processor_token_flow: None, force_3ds_challenge: None, }, } } } mod tests { #[test] fn test_backwards_compatibility() { let serialized_payment_intent = r#"{ "payment_id": "payment_12345", "merchant_id": "merchant_67890", "status": "succeeded", "amount": 10000, "currency": "USD", "amount_captured": null, "customer_id": "cust_123456", "description": "Test Payment", "return_url": "https://example.com/return", "metadata": null, "connector_id": "connector_001", "shipping_address_id": null, "billing_address_id": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "created_at": "2024-02-01T12:00:00Z", "modified_at": "2024-02-01T12:00:00Z", "last_synced": null, "setup_future_usage": null, "off_session": null, "client_secret": "sec_abcdef1234567890", "active_attempt_id": "attempt_123", "business_country": "US", "business_label": null, "order_details": null, "allowed_payment_method_types": "credit", "connector_metadata": null, "feature_metadata": null, "attempt_count": 1, "profile_id": null, "merchant_decision": null, "payment_link_id": null, "payment_confirm_source": null, "updated_by": "admin", "surcharge_applicable": null, "request_incremental_authorization": null, "incremental_authorization_allowed": null, "authorization_count": null, "session_expiry": null, "fingerprint_id": null, "frm_metadata": null }"#; let deserialized_payment_intent = serde_json::from_str::<super::PaymentIntent>(serialized_payment_intent); assert!(deserialized_payment_intent.is_ok()); } } <file_sep> pack="QBP-B" entity="payment_intent" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/payment_intent.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; #[cfg(feature = "v1")] use crate::schema::payment_intent::dsl; #[cfg(feature = "v2")] use crate::schema_v2::payment_intent::dsl; use crate::{ errors, payment_intent::{self, PaymentIntent, PaymentIntentNew}, PgPooledConn, StorageResult, }; impl PaymentIntentNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentIntent> { generics::generic_insert(conn, self).await } } impl PaymentIntent { #[cfg(feature = "v2")] pub async fn update( self, conn: &PgPooledConn, payment_intent_update: payment_intent::PaymentIntentUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.id.to_owned(), payment_intent_update, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, Ok(payment_intent) => Ok(payment_intent), } } #[cfg(feature = "v2")] pub async fn find_by_global_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalPaymentId, ) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await } #[cfg(feature = "v1")] pub async fn update( self, conn: &PgPooledConn, payment_intent: payment_intent::PaymentIntentUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::payment_id .eq(self.payment_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), payment_intent::PaymentIntentUpdateInternal::from(payment_intent), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, Ok(mut payment_intents) => payment_intents .pop() .ok_or(error_stack::report!(errors::DatabaseError::NotFound)), } } #[cfg(feature = "v2")] pub async fn find_by_merchant_reference_id_merchant_id( conn: &PgPooledConn, merchant_reference_id: &str, merchant_id: &common_utils::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 } // This query should be removed in the future because direct queries to the intent table without an intent ID are not allowed. // In an active-active setup, a lookup table should be implemented, and the merchant reference ID will serve as the idempotency key. #[cfg(feature = "v2")] pub async fn find_by_merchant_reference_id_profile_id( conn: &PgPooledConn, merchant_reference_id: &common_utils::id_type::PaymentReferenceId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), ) .await } #[cfg(feature = "v2")] pub async fn find_optional_by_merchant_reference_id_merchant_id( conn: &PgPooledConn, merchant_reference_id: &str, 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::merchant_reference_id.eq(merchant_reference_id.to_owned())), ) .await } #[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 } }
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/payments/payment_intent.rs<|crate|> storage_impl<|op|> select entity=payment_intent repo=hyperswitch tables=payment_intent joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="payment_intent" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/payments/payment_intent.rs" #[cfg(feature = "olap")] use api_models::payments::{AmountFilter, Order, SortBy, SortOn}; #[cfg(feature = "olap")] use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; use common_utils::{ ext_traits::{AsyncExt, Encode}, types::keymanager::KeyManagerState, }; #[cfg(feature = "olap")] use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl}; #[cfg(feature = "v1")] use diesel_models::payment_intent::PaymentIntentUpdate as DieselPaymentIntentUpdate; #[cfg(feature = "olap")] use diesel_models::query::generics::db_metrics; #[cfg(all(feature = "v1", feature = "olap"))] use diesel_models::schema::{ payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl}, payment_intent::dsl as pi_dsl, }; #[cfg(all(feature = "v2", feature = "olap"))] use diesel_models::schema_v2::{ payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl}, payment_intent::dsl as pi_dsl, }; use diesel_models::{ enums::MerchantStorageScheme, kv, payment_intent::PaymentIntent as DieselPaymentIntent, }; use error_stack::ResultExt; #[cfg(feature = "olap")] use hyperswitch_domain_models::payments::{ payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints, }; use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, payments::{ payment_intent::{PaymentIntentInterface, PaymentIntentUpdate}, PaymentIntent, }, }; use redis_interface::HsetnxReply; #[cfg(feature = "olap")] use router_env::logger; use router_env::{instrument, tracing}; #[cfg(feature = "olap")] use crate::connection; use crate::{ diesel_error_to_data_error, errors::{RedisErrorExt, StorageError}, kv_router_store::KVRouterStore, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, pg_connection_read, pg_connection_write}, DatabaseStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { type Error = StorageError; #[cfg(feature = "v1")] async fn insert_payment_intent( &self, state: &KeyManagerState, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let merchant_id = payment_intent.merchant_id.clone(); let payment_id = payment_intent.get_id().to_owned(); let field = payment_intent.get_id().get_hash_key_for_kv_store(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payment_intent( state, payment_intent, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let new_payment_intent = payment_intent .clone() .construct_new() .await .change_context(StorageError::EncryptionError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::PaymentIntent(Box::new( new_payment_intent, ))), }, }; let diesel_payment_intent = payment_intent .clone() .convert() .await .change_context(StorageError::EncryptionError)?; match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HSetNx( &field, &diesel_payment_intent, redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue { entity: "payment_intent", key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(payment_intent), Err(error) => Err(error.change_context(StorageError::KVError)), } } } } #[cfg(feature = "v2")] async fn insert_payment_intent( &self, state: &KeyManagerState, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payment_intent( state, payment_intent, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { todo!("Implement payment intent insert for kv") } } } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, Option<PaymentAttempt>)>, StorageError> { self.router_store .get_filtered_payment_intents_attempt( state, merchant_id, constraints, merchant_key_store, storage_scheme, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, payment_intent_update: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let merchant_id = this.merchant_id.clone(); let payment_id = this.get_id().to_owned(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let field = format!("pi_{}", this.get_id().get_string_repr()); let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, Op::Update(key.clone(), &field, Some(&this.updated_by)), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payment_intent( state, this, payment_intent_update, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let diesel_intent_update = DieselPaymentIntentUpdate::from(payment_intent_update); let origin_diesel_intent = this .convert() .await .change_context(StorageError::EncryptionError)?; let diesel_intent = diesel_intent_update .clone() .apply_changeset(origin_diesel_intent.clone()); // Check for database presence as well Maybe use a read replica here ? let redis_value = diesel_intent .encode_to_string_of_json() .change_context(StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new( kv::PaymentIntentUpdateMems { orig: origin_diesel_intent, update_data: diesel_intent_update, }, ))), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(StorageError::KVError)?; let payment_intent = PaymentIntent::convert_back( state, diesel_intent, merchant_key_store.key.get_inner(), merchant_id.into(), ) .await .change_context(StorageError::DecryptionError)?; Ok(payment_intent) } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, payment_intent_update: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payment_intent( state, this, payment_intent_update, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { todo!() } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let database_call = || async { let conn = pg_connection_read(self).await?; DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, Op::Find, )) .await; let diesel_payment_intent = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; let field = payment_id.get_hash_key_for_kv_store(); Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } }?; PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_intent_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn: bb8::PooledConnection< '_, async_bb8_diesel::ConnectionManager<diesel::PgConnection>, > = pg_connection_read(self).await?; let diesel_payment_intent = DieselPaymentIntent::find_by_global_id(&conn, id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; let merchant_id = diesel_payment_intent.merchant_id.clone(); PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intent_by_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { self.router_store .filter_payment_intent_by_constraints( state, merchant_id, filters, merchant_key_store, storage_scheme, ) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intents_by_time_range_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, time_range: &common_utils::types::TimeRange, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { self.router_store .filter_payment_intents_by_time_range_constraints( state, merchant_id, time_range, merchant_key_store, storage_scheme, ) .await } #[cfg(feature = "olap")] async fn get_intent_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> { self.router_store .get_intent_status_with_count(merchant_id, profile_id_list, time_range) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> { self.router_store .get_filtered_payment_intents_attempt( state, merchant_id, filters, merchant_key_store, storage_scheme, ) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<String>, StorageError> { self.router_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Option<String>>, StorageError> { self.router_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, state: &KeyManagerState, merchant_reference_id: &common_utils::id_type::PaymentReferenceId, profile_id: &common_utils::id_type::ProfileId, merchant_key_store: &MerchantKeyStore, storage_scheme: &MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payment_intent_by_merchant_reference_id_profile_id( state, merchant_reference_id, profile_id, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { todo!() } } } } #[async_trait::async_trait] impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_payment_intent( &self, state: &KeyManagerState, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_write(self).await?; let diesel_payment_intent = payment_intent .construct_new() .await .change_context(StorageError::EncryptionError)? .insert(&conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_write(self).await?; let diesel_payment_intent_update = DieselPaymentIntentUpdate::from(payment_intent); let diesel_payment_intent = this .convert() .await .change_context(StorageError::EncryptionError)? .update(&conn, diesel_payment_intent_update) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_write(self).await?; let diesel_payment_intent_update = diesel_models::PaymentIntentUpdateInternal::try_from(payment_intent) .change_context(StorageError::DeserializationFailed)?; let diesel_payment_intent = this .convert() .await .change_context(StorageError::EncryptionError)? .update(&conn, diesel_payment_intent_update) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_and_then(|diesel_payment_intent| async { PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_intent_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_read(self).await?; let diesel_payment_intent = DieselPaymentIntent::find_by_global_id(&conn, id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; let merchant_id = diesel_payment_intent.merchant_id.clone(); PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, state: &KeyManagerState, merchant_reference_id: &common_utils::id_type::PaymentReferenceId, profile_id: &common_utils::id_type::ProfileId, merchant_key_store: &MerchantKeyStore, _storage_scheme: &MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_read(self).await?; let diesel_payment_intent = DieselPaymentIntent::find_by_merchant_reference_id_profile_id( &conn, merchant_reference_id, profile_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; let merchant_id = diesel_payment_intent.merchant_id.clone(); PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_payment_intent_by_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { use futures::{future::try_join_all, FutureExt}; let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); //[#350]: Replace this with Boxable Expression and pass it into generic filter // when https://github.com/rust-lang/rust/issues/52662 becomes stable let mut query = <DieselPaymentIntent as HasTable>::table() .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .order(pi_dsl::created_at.desc()) .into_boxed(); match filters { PaymentIntentFetchConstraints::Single { payment_intent_id } => { query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned())); } PaymentIntentFetchConstraints::List(params) => { if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); } query = match (params.starting_at, &params.starting_after_id) { (Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_payment_id_merchant_id( state, starting_after_id, merchant_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, &params.ending_before_id) { (Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_payment_id_merchant_id( state, ending_before_id, merchant_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; if let Some(currency) = &params.currency { query = query.filter(pi_dsl::currency.eq_any(currency.clone())); } if let Some(status) = &params.status { query = query.filter(pi_dsl::status.eq_any(status.clone())); } } } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>( query.get_results_async::<DieselPaymentIntent>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map(|payment_intents| { try_join_all(payment_intents.into_iter().map(|diesel_payment_intent| { PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) }) .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payment records"), ) })? .await } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_payment_intents_by_time_range_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, time_range: &common_utils::types::TimeRange, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { // TODO: Remove this redundant function let payment_filters = (*time_range).into(); self.filter_payment_intent_by_constraints( state, merchant_id, &payment_filters, merchant_key_store, storage_scheme, ) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn get_intent_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = <DieselPaymentIntent as HasTable>::table() .group_by(pi_dsl::status) .select((pi_dsl::status, diesel::dsl::count_star())) .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .into_boxed(); if let Some(profile_id) = profile_id_list { query = query.filter(pi_dsl::profile_id.eq_any(profile_id)); } query = query.filter(pi_dsl::created_at.ge(time_range.start_time)); query = match time_range.end_time { Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)), None => query, }; logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>( query.get_results_async::<(common_enums::IntentStatus, i64)>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payment records"), ) .into() }) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> { use futures::{future::try_join_all, FutureExt}; use crate::DataModelExt; let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .inner_join( payment_attempt_schema::table.on(pa_dsl::attempt_id.eq(pi_dsl::active_attempt_id)), ) .filter(pa_dsl::merchant_id.eq(merchant_id.to_owned())) // Ensure merchant_ids match, as different merchants can share payment/attempt IDs. .into_boxed(); query = match constraints { PaymentIntentFetchConstraints::Single { payment_intent_id } => { query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned())) } PaymentIntentFetchConstraints::List(params) => { query = match params.order { Order { on: SortOn::Amount, by: SortBy::Asc, } => query.order(pi_dsl::amount.asc()), Order { on: SortOn::Amount, by: SortBy::Desc, } => query.order(pi_dsl::amount.desc()), Order { on: SortOn::Created, by: SortBy::Asc, } => query.order(pi_dsl::created_at.asc()), Order { on: SortOn::Created, by: SortBy::Desc, } => query.order(pi_dsl::created_at.desc()), }; if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { query = query.filter( pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()), ) } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); } query = match (params.starting_at, &params.starting_after_id) { (Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_payment_id_merchant_id( state, starting_after_id, merchant_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, &params.ending_before_id) { (Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_payment_id_merchant_id( state, ending_before_id, merchant_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); query = match params.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => query.filter(pi_dsl::amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => query.filter(pi_dsl::amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => query.filter(pi_dsl::amount.le(end)), _ => query, }; query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; let connectors = params .connector .as_ref() .map(|c| c.iter().map(|c| c.to_string()).collect::<Vec<String>>()); query = match connectors { Some(connectors) => query.filter(pa_dsl::connector.eq_any(connectors)), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; query = match &params.payment_method { Some(payment_method) => { query.filter(pa_dsl::payment_method.eq_any(payment_method.clone())) } None => query, }; query = match &params.payment_method_type { Some(payment_method_type) => query .filter(pa_dsl::payment_method_type.eq_any(payment_method_type.clone())), None => query, }; query = match &params.authentication_type { Some(authentication_type) => query .filter(pa_dsl::authentication_type.eq_any(authentication_type.clone())), None => query, }; query = match &params.merchant_connector_id { Some(merchant_connector_id) => query.filter( pa_dsl::merchant_connector_id.eq_any(merchant_connector_id.clone()), ), None => query, }; if let Some(card_network) = &params.card_network { query = query.filter(pa_dsl::card_network.eq_any(card_network.clone())); } if let Some(card_discovery) = &params.card_discovery { query = query.filter(pa_dsl::card_discovery.eq_any(card_discovery.clone())); } query } }; logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async::<( DieselPaymentIntent, diesel_models::payment_attempt::PaymentAttempt, )>(conn) .await .map(|results| { try_join_all(results.into_iter().map(|(pi, pa)| { PaymentIntent::convert_back( state, pi, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .map(|payment_intent| { payment_intent.map(|payment_intent| { (payment_intent, PaymentAttempt::from_storage_model(pa)) }) }) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) }) .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payment records"), ) })? .await } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, Option<PaymentAttempt>)>, StorageError> { use diesel::NullableExpressionMethods as _; use futures::{future::try_join_all, FutureExt}; use crate::DataModelExt; let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .left_join( payment_attempt_schema::table .on(pi_dsl::active_attempt_id.eq(pa_dsl::id.nullable())), ) // Filtering on merchant_id for payment_attempt is not required for v2 as payment_attempt_ids are globally unique .into_boxed(); query = match constraints { PaymentIntentFetchConstraints::Single { payment_intent_id } => { query.filter(pi_dsl::id.eq(payment_intent_id.to_owned())) } PaymentIntentFetchConstraints::List(params) => { query = match params.order { Order { on: SortOn::Amount, by: SortBy::Asc, } => query.order(pi_dsl::amount.asc()), Order { on: SortOn::Amount, by: SortBy::Desc, } => query.order(pi_dsl::amount.desc()), Order { on: SortOn::Created, by: SortBy::Asc, } => query.order(pi_dsl::created_at.asc()), Order { on: SortOn::Created, by: SortBy::Desc, } => query.order(pi_dsl::created_at.desc()), }; if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { query = query.filter( pi_dsl::merchant_reference_id.eq(merchant_order_reference_id.clone()), ) } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq(profile_id.clone())); } query = match (params.starting_at, &params.starting_after_id) { (Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_id( state, starting_after_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, &params.ending_before_id) { (Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_id( state, ending_before_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); query = match params.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => query.filter(pi_dsl::amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => query.filter(pi_dsl::amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => query.filter(pi_dsl::amount.le(end)), _ => query, }; query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq(*currency)), None => query, }; query = match &params.connector { Some(connector) => query.filter(pa_dsl::connector.eq(*connector)), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq(*status)), None => query, }; query = match &params.payment_method_type { Some(payment_method_type) => { query.filter(pa_dsl::payment_method_type_v2.eq(*payment_method_type)) } None => query, }; query = match &params.payment_method_subtype { Some(payment_method_subtype) => { query.filter(pa_dsl::payment_method_subtype.eq(*payment_method_subtype)) } None => query, }; query = match &params.authentication_type { Some(authentication_type) => { query.filter(pa_dsl::authentication_type.eq(*authentication_type)) } None => query, }; query = match &params.merchant_connector_id { Some(merchant_connector_id) => query .filter(pa_dsl::merchant_connector_id.eq(merchant_connector_id.clone())), None => query, }; if let Some(card_network) = &params.card_network { query = query.filter(pa_dsl::card_network.eq(card_network.clone())); } query } }; logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async::<( DieselPaymentIntent, Option<diesel_models::payment_attempt::PaymentAttempt>, )>(conn) .await .change_context(StorageError::DecryptionError) .async_and_then(|output| async { try_join_all(output.into_iter().map( |(pi, pa): (_, Option<diesel_models::payment_attempt::PaymentAttempt>)| async { let payment_intent = PaymentIntent::convert_back( state, pi, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ); let payment_attempt = pa .async_map(|val| { PaymentAttempt::convert_back( state, val, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) }) .map(|val| val.transpose()); let output = futures::try_join!(payment_intent, payment_attempt); output.change_context(StorageError::DecryptionError) }, )) .await }) .await .change_context(StorageError::DecryptionError) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Option<String>>, StorageError> { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() .select(pi_dsl::active_attempt_id) .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .order(pi_dsl::created_at.desc()) .into_boxed(); query = match constraints { PaymentIntentFetchConstraints::Single { payment_intent_id } => { query.filter(pi_dsl::id.eq(payment_intent_id.to_owned())) } PaymentIntentFetchConstraints::List(params) => { if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { query = query.filter( pi_dsl::merchant_reference_id.eq(merchant_order_reference_id.clone()), ) } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq(profile_id.clone())); } query = match params.starting_at { Some(starting_at) => query.filter(pi_dsl::created_at.ge(starting_at)), None => query, }; query = match params.ending_at { Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)), None => query, }; query = match params.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => query.filter(pi_dsl::amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => query.filter(pi_dsl::amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => query.filter(pi_dsl::amount.le(end)), _ => query, }; query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq(*currency)), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq(*status)), None => query, }; query } }; db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>( query.get_results_async::<Option<String>>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payment records"), ) .into() }) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<String>, StorageError> { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() .select(pi_dsl::active_attempt_id) .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .order(pi_dsl::created_at.desc()) .into_boxed(); query = match constraints { PaymentIntentFetchConstraints::Single { payment_intent_id } => { query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned())) } PaymentIntentFetchConstraints::List(params) => { if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { query = query.filter( pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()), ) } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); } query = match params.starting_at { Some(starting_at) => query.filter(pi_dsl::created_at.ge(starting_at)), None => query, }; query = match params.ending_at { Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)), None => query, }; query = match params.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => query.filter(pi_dsl::amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => query.filter(pi_dsl::amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => query.filter(pi_dsl::amount.le(end)), _ => query, }; query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; query } }; db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>( query.get_results_async::<String>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payment records"), ) .into() }) } } <file_sep> pack="QBP-B" entity="payment_intent" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-03-11-171330_add-force-3ds-challenge-in-payment-intent/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE payment_intent DROP COLUMN IF EXISTS force_3ds_challenge; <file_sep> pack="QBP-B" entity="payment_intent" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-03-20-085151_force-3ds-challenge-triggered/up.sql" -- Your SQL goes here ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS force_3ds_challenge_trigger boolean DEFAULT false; <file_sep> pack="QBP-B" entity="payment_intent" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-03-20-085151_force-3ds-challenge-triggered/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE payment_intent DROP COLUMN IF EXISTS force_3ds_challenge_trigger; <file_sep> pack="QBP-B" entity="payment_intent" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_payment_intent.rs" // schema snippet for entity=payment_intent repo=hyperswitch // table: payment_intent columns: [] entities: [payment_intent] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/mock_db/payment_intent.rs<|crate|> storage_impl<|op|> select entity=payment_intent repo=hyperswitch tables=payment_intent joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="payment_intent" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/payment_intent.rs" use common_enums::{PaymentMethodType, RequestIncrementalAuthorization}; use common_types::primitive_wrappers::RequestExtendedAuthorizationBool; use common_utils::{encryption::Encryption, pii, types::MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::schema::payment_intent; #[cfg(feature = "v2")] use crate::schema_v2::payment_intent; #[cfg(feature = "v2")] use crate::types::{FeatureMetadata, OrderDetailsWithAmount}; use crate::{business_profile::PaymentLinkBackgroundImageConfig, enums as storage_enums}; #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: storage_enums::Currency, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::GlobalCustomerId>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub attempt_count: i16, pub profile_id: common_utils::id_type::ProfileId, pub payment_link_id: Option<String>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<serde_json::Value>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub enable_payment_link: Option<bool>, pub apply_mit_exemption: Option<bool>, pub customer_present: Option<bool>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub id: common_utils::id_type::GlobalPaymentId, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<serde_json::Value>, pub connector_metadata: Option<serde_json::Value>, pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, pub profile_id: Option<common_utils::id_type::ProfileId>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PaymentLinkConfigRequestForPayments { /// custom theme for the payment link pub theme: Option<String>, /// merchant display logo pub logo: Option<String>, /// Custom merchant name for payment link pub seller_name: Option<String>, /// Custom layout for sdk pub sdk_layout: Option<String>, /// Display only the sdk for payment link pub display_sdk_only: Option<bool>, /// Enable saved payment method option for payment link pub enabled_saved_payment_method: Option<bool>, /// Hide card nickname field option for payment link pub hide_card_nickname_field: Option<bool>, /// Show card form by default for payment link pub show_card_form_by_default: Option<bool>, /// Dynamic details related to merchant to be rendered in payment link pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>, /// Configurations for the background image for details section pub background_image: Option<PaymentLinkBackgroundImageConfig>, /// Custom layout for details section pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>, /// Text for payment link's handle confirm button pub payment_button_text: Option<String>, /// Skip the status screen after payment completion pub skip_status_screen: Option<bool>, /// Text for customizing message for card terms pub custom_message_for_card_terms: Option<String>, /// Custom background colour for payment link's handle confirm button pub payment_button_colour: Option<String>, /// Custom text colour for payment link's handle confirm button pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, /// SDK configuration rules pub sdk_ui_rules: Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: Option<bool>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct PaymentLinkTransactionDetails { /// Key for the transaction details pub key: String, /// Value for the transaction details pub value: String, /// UI configuration for the transaction details pub ui_configuration: Option<TransactionDetailsUiConfiguration>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkTransactionDetails); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct TransactionDetailsUiConfiguration { /// Position of the key-value pair in the UI pub position: Option<i8>, /// Whether the key should be bold pub is_key_bold: Option<bool>, /// Whether the value should be bold pub is_value_bold: Option<bool>, } common_utils::impl_to_sql_from_sql_json!(TransactionDetailsUiConfiguration); #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct TaxDetails { /// This is the tax related information that is calculated irrespective of any payment method. /// This is calculated when the order is created with shipping details pub default: Option<DefaultTax>, /// This is the tax related information that is calculated based on the payment method /// This is calculated when calling the /calculate_tax API pub payment_method_type: Option<PaymentMethodTypeTax>, } impl TaxDetails { /// Get the tax amount /// If default tax is present, return the default tax amount /// If default tax is not present, return the tax amount based on the payment method if it matches the provided payment method type pub fn get_tax_amount(&self, payment_method: Option<PaymentMethodType>) -> Option<MinorUnit> { self.payment_method_type .as_ref() .zip(payment_method) .filter(|(payment_method_type_tax, payment_method)| { payment_method_type_tax.pmt == *payment_method }) .map(|(payment_method_type_tax, _)| payment_method_type_tax.order_tax_amount) .or_else(|| self.get_default_tax_amount()) } /// Get the default tax amount pub fn get_default_tax_amount(&self) -> Option<MinorUnit> { self.default .as_ref() .map(|default_tax_details| default_tax_details.order_tax_amount) } } common_utils::impl_to_sql_from_sql_json!(TaxDetails); #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PaymentMethodTypeTax { pub order_tax_amount: MinorUnit, pub pmt: PaymentMethodType, } #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DefaultTax { pub order_tax_amount: MinorUnit, } #[cfg(feature = "v2")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: storage_enums::Currency, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::GlobalCustomerId>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub attempt_count: i16, pub profile_id: common_utils::id_type::ProfileId, pub payment_link_id: Option<String>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<serde_json::Value>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub enable_payment_link: Option<bool>, pub apply_mit_exemption: Option<bool>, pub id: common_utils::id_type::GlobalPaymentId, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, } #[cfg(feature = "v1")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<serde_json::Value>, pub connector_metadata: Option<serde_json::Value>, pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_decision: Option<String>, pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { /// Update the payment intent details on payment intent confirmation, before calling the connector ConfirmIntent { status: storage_enums::IntentStatus, active_attempt_id: common_utils::id_type::GlobalAttemptId, updated_by: String, }, /// Update the payment intent details on payment intent confirmation, after calling the connector ConfirmIntentPostUpdate { status: storage_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, }, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { ResponseUpdate { status: storage_enums::IntentStatus, amount_captured: Option<MinorUnit>, fingerprint_id: Option<String>, updated_by: String, incremental_authorization_allowed: Option<bool>, }, MetadataUpdate { metadata: serde_json::Value, updated_by: String, }, Update(Box<PaymentIntentUpdateFields>), PaymentCreateUpdate { return_url: Option<String>, status: Option<storage_enums::IntentStatus>, customer_id: Option<common_utils::id_type::CustomerId>, shipping_address_id: Option<String>, billing_address_id: Option<String>, customer_details: Option<Encryption>, updated_by: String, }, MerchantStatusUpdate { status: storage_enums::IntentStatus, shipping_address_id: Option<String>, billing_address_id: Option<String>, updated_by: String, }, PGStatusUpdate { status: storage_enums::IntentStatus, updated_by: String, incremental_authorization_allowed: Option<bool>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, attempt_count: i16, updated_by: String, }, StatusAndAttemptUpdate { status: storage_enums::IntentStatus, active_attempt_id: String, attempt_count: i16, updated_by: String, }, ApproveUpdate { status: storage_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, RejectUpdate { status: storage_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, SurchargeApplicableUpdate { surcharge_applicable: Option<bool>, updated_by: String, }, IncrementalAuthorizationAmountUpdate { amount: MinorUnit, }, AuthorizationCountUpdate { authorization_count: i32, }, CompleteAuthorizeUpdate { shipping_address_id: Option<String>, }, ManualUpdate { status: Option<storage_enums::IntentStatus>, updated_by: String, }, SessionResponseUpdate { tax_details: TaxDetails, shipping_address_id: Option<String>, updated_by: String, shipping_details: Option<Encryption>, }, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub status: storage_enums::IntentStatus, pub customer_id: Option<common_utils::id_type::CustomerId>, pub shipping_address: Option<Encryption>, pub billing_address: Option<Encryption>, pub return_url: Option<String>, pub description: Option<String>, pub statement_descriptor: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub is_payment_processor_token_flow: Option<bool>, pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub status: storage_enums::IntentStatus, pub customer_id: Option<common_utils::id_type::CustomerId>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub return_url: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<serde_json::Value>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<TaxDetails>, pub force_3ds_challenge: Option<bool>, } // TODO: uncomment fields as necessary #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { pub status: Option<storage_enums::IntentStatus>, pub prerouting_algorithm: Option<serde_json::Value>, pub amount_captured: Option<MinorUnit>, pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<Option<common_utils::id_type::GlobalAttemptId>>, pub amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub shipping_cost: Option<MinorUnit>, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub surcharge_applicable: Option<bool>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub customer_present: Option<bool>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub apply_mit_exemption: Option<bool>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub session_expiry: Option<PrimitiveDateTime>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub request_external_three_ds_authentication: Option<bool>, pub updated_by: String, pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { pub amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub status: Option<storage_enums::IntentStatus>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub return_url: Option<String>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub metadata: Option<serde_json::Value>, pub billing_address_id: Option<String>, pub shipping_address_id: Option<String>, pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub attempt_count: Option<i16>, pub merchant_decision: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<TaxDetails>, pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v1")] impl PaymentIntentUpdate { pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { let PaymentIntentUpdateInternal { amount, currency, status, amount_captured, customer_id, return_url, setup_future_usage, off_session, metadata, billing_address_id, shipping_address_id, modified_at: _, active_attempt_id, business_country, business_label, description, statement_descriptor_name, statement_descriptor_suffix, order_details, attempt_count, merchant_decision, payment_confirm_source, updated_by, surcharge_applicable, incremental_authorization_allowed, authorization_count, session_expiry, fingerprint_id, request_external_three_ds_authentication, frm_metadata, customer_details, billing_details, merchant_order_reference_id, shipping_details, is_payment_processor_token_flow, tax_details, force_3ds_challenge, } = self.into(); PaymentIntent { amount: amount.unwrap_or(source.amount), currency: currency.or(source.currency), status: status.unwrap_or(source.status), amount_captured: amount_captured.or(source.amount_captured), customer_id: customer_id.or(source.customer_id), return_url: return_url.or(source.return_url), setup_future_usage: setup_future_usage.or(source.setup_future_usage), off_session: off_session.or(source.off_session), metadata: metadata.or(source.metadata), billing_address_id: billing_address_id.or(source.billing_address_id), shipping_address_id: shipping_address_id.or(source.shipping_address_id), modified_at: common_utils::date_time::now(), active_attempt_id: active_attempt_id.unwrap_or(source.active_attempt_id), business_country: business_country.or(source.business_country), business_label: business_label.or(source.business_label), description: description.or(source.description), statement_descriptor_name: statement_descriptor_name .or(source.statement_descriptor_name), statement_descriptor_suffix: statement_descriptor_suffix .or(source.statement_descriptor_suffix), order_details: order_details.or(source.order_details), attempt_count: attempt_count.unwrap_or(source.attempt_count), merchant_decision: merchant_decision.or(source.merchant_decision), payment_confirm_source: payment_confirm_source.or(source.payment_confirm_source), updated_by, surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable), incremental_authorization_allowed: incremental_authorization_allowed .or(source.incremental_authorization_allowed), authorization_count: authorization_count.or(source.authorization_count), fingerprint_id: fingerprint_id.or(source.fingerprint_id), session_expiry: session_expiry.or(source.session_expiry), request_external_three_ds_authentication: request_external_three_ds_authentication .or(source.request_external_three_ds_authentication), frm_metadata: frm_metadata.or(source.frm_metadata), customer_details: customer_details.or(source.customer_details), billing_details: billing_details.or(source.billing_details), merchant_order_reference_id: merchant_order_reference_id .or(source.merchant_order_reference_id), shipping_details: shipping_details.or(source.shipping_details), is_payment_processor_token_flow: is_payment_processor_token_flow .or(source.is_payment_processor_token_flow), tax_details: tax_details.or(source.tax_details), force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge), ..source } } } #[cfg(feature = "v1")] impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fn from(payment_intent_update: PaymentIntentUpdate) -> Self { match payment_intent_update { PaymentIntentUpdate::MetadataUpdate { metadata, updated_by, } => Self { metadata: Some(metadata), modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::Update(value) => Self { amount: Some(value.amount), currency: Some(value.currency), setup_future_usage: value.setup_future_usage, status: Some(value.status), customer_id: value.customer_id, shipping_address_id: value.shipping_address_id, billing_address_id: value.billing_address_id, return_url: value.return_url, business_country: value.business_country, business_label: value.business_label, description: value.description, statement_descriptor_name: value.statement_descriptor_name, statement_descriptor_suffix: value.statement_descriptor_suffix, order_details: value.order_details, metadata: value.metadata, payment_confirm_source: value.payment_confirm_source, updated_by: value.updated_by, session_expiry: value.session_expiry, fingerprint_id: value.fingerprint_id, request_external_three_ds_authentication: value .request_external_three_ds_authentication, frm_metadata: value.frm_metadata, customer_details: value.customer_details, billing_details: value.billing_details, merchant_order_reference_id: value.merchant_order_reference_id, shipping_details: value.shipping_details, amount_captured: None, off_session: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, attempt_count: None, merchant_decision: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, is_payment_processor_token_flow: value.is_payment_processor_token_flow, tax_details: None, force_3ds_challenge: value.force_3ds_challenge, }, PaymentIntentUpdate::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details, updated_by, } => Self { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details, modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, amount_captured: None, setup_future_usage: None, off_session: None, metadata: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::PGStatusUpdate { status, updated_by, incremental_authorization_allowed, } => Self { status: Some(status), modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::MerchantStatusUpdate { status, shipping_address_id, billing_address_id, updated_by, } => Self { status: Some(status), shipping_address_id, billing_address_id, modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::ResponseUpdate { // amount, // currency, status, amount_captured, fingerprint_id, // customer_id, updated_by, incremental_authorization_allowed, } => Self { // amount, // currency: Some(currency), status: Some(status), amount_captured, fingerprint_id, // customer_id, return_url: None, modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, amount: None, currency: None, customer_id: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, authorization_count: None, session_expiry: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, attempt_count, updated_by, } => Self { active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::StatusAndAttemptUpdate { status, active_attempt_id, attempt_count, updated_by, } => Self { status: Some(status), active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::ApproveUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::RejectUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable, updated_by, } => Self { surcharge_applicable, updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self { amount: Some(amount), currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count, } => Self { authorization_count: Some(authorization_count), amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::CompleteAuthorizeUpdate { shipping_address_id, } => Self { shipping_address_id, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self { status, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::SessionResponseUpdate { tax_details, shipping_address_id, updated_by, shipping_details, } => Self { shipping_address_id, amount: None, tax_details: Some(tax_details), currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details, is_payment_processor_token_flow: None, force_3ds_challenge: None, }, } } } mod tests { #[test] fn test_backwards_compatibility() { let serialized_payment_intent = r#"{ "payment_id": "payment_12345", "merchant_id": "merchant_67890", "status": "succeeded", "amount": 10000, "currency": "USD", "amount_captured": null, "customer_id": "cust_123456", "description": "Test Payment", "return_url": "https://example.com/return", "metadata": null, "connector_id": "connector_001", "shipping_address_id": null, "billing_address_id": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "created_at": "2024-02-01T12:00:00Z", "modified_at": "2024-02-01T12:00:00Z", "last_synced": null, "setup_future_usage": null, "off_session": null, "client_secret": "sec_abcdef1234567890", "active_attempt_id": "attempt_123", "business_country": "US", "business_label": null, "order_details": null, "allowed_payment_method_types": "credit", "connector_metadata": null, "feature_metadata": null, "attempt_count": 1, "profile_id": null, "merchant_decision": null, "payment_link_id": null, "payment_confirm_source": null, "updated_by": "admin", "surcharge_applicable": null, "request_incremental_authorization": null, "incremental_authorization_allowed": null, "authorization_count": null, "session_expiry": null, "fingerprint_id": null, "frm_metadata": null }"#; let deserialized_payment_intent = serde_json::from_str::<super::PaymentIntent>(serialized_payment_intent); assert!(deserialized_payment_intent.is_ok()); } } <file_sep> pack="QBP-B" entity="payment_intent" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/payment_intent.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; #[cfg(feature = "v1")] use crate::schema::payment_intent::dsl; #[cfg(feature = "v2")] use crate::schema_v2::payment_intent::dsl; use crate::{ errors, payment_intent::{self, PaymentIntent, PaymentIntentNew}, PgPooledConn, StorageResult, }; impl PaymentIntentNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentIntent> { generics::generic_insert(conn, self).await } } impl PaymentIntent { #[cfg(feature = "v2")] pub async fn update( self, conn: &PgPooledConn, payment_intent_update: payment_intent::PaymentIntentUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, self.id.to_owned(), payment_intent_update, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, Ok(payment_intent) => Ok(payment_intent), } } #[cfg(feature = "v2")] pub async fn find_by_global_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalPaymentId, ) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await } #[cfg(feature = "v1")] pub async fn update( self, conn: &PgPooledConn, payment_intent: payment_intent::PaymentIntentUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::payment_id .eq(self.payment_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), payment_intent::PaymentIntentUpdateInternal::from(payment_intent), ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, Ok(mut payment_intents) => payment_intents .pop() .ok_or(error_stack::report!(errors::DatabaseError::NotFound)), } } #[cfg(feature = "v2")] pub async fn find_by_merchant_reference_id_merchant_id( conn: &PgPooledConn, merchant_reference_id: &str, merchant_id: &common_utils::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 } // This query should be removed in the future because direct queries to the intent table without an intent ID are not allowed. // In an active-active setup, a lookup table should be implemented, and the merchant reference ID will serve as the idempotency key. #[cfg(feature = "v2")] pub async fn find_by_merchant_reference_id_profile_id( conn: &PgPooledConn, merchant_reference_id: &common_utils::id_type::PaymentReferenceId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), ) .await } #[cfg(feature = "v2")] pub async fn find_optional_by_merchant_reference_id_merchant_id( conn: &PgPooledConn, merchant_reference_id: &str, 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::merchant_reference_id.eq(merchant_reference_id.to_owned())), ) .await } #[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 } } <file_sep> pack="QBP-B" entity="payment_intent" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/mock_db/payment_intent.rs" use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, payments::{ payment_intent::{PaymentIntentInterface, PaymentIntentUpdate}, PaymentIntent, }, }; use super::MockDb; use crate::errors::StorageError; #[async_trait::async_trait] impl PaymentIntentInterface for MockDb { type Error = StorageError; #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intent_by_constraints( &self, _state: &KeyManagerState, _merchant_id: &common_utils::id_type::MerchantId, _filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result< Vec<( PaymentIntent, Option<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>, )>, StorageError, > { Err(StorageError::MockDbError)? } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intents_by_time_range_constraints( &self, _state: &KeyManagerState, _merchant_id: &common_utils::id_type::MerchantId, _time_range: &common_utils::types::TimeRange, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "olap")] async fn get_intent_status_with_count( &self, _merchant_id: &common_utils::id_type::MerchantId, _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, _time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::IntentStatus, i64)>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, _merchant_id: &common_utils::id_type::MerchantId, _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<String>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, _merchant_id: &common_utils::id_type::MerchantId, _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<Option<String>>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, _state: &KeyManagerState, _merchant_id: &common_utils::id_type::MerchantId, _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result< Vec<( PaymentIntent, hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, )>, StorageError, > { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[allow(clippy::panic)] async fn insert_payment_intent( &self, _state: &KeyManagerState, new: PaymentIntent, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { let mut payment_intents = self.payment_intents.lock().await; payment_intents.push(new.clone()); Ok(new) } #[cfg(feature = "v1")] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, update: PaymentIntentUpdate, key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { let mut payment_intents = self.payment_intents.lock().await; let payment_intent = payment_intents .iter_mut() .find(|item| item.get_id() == this.get_id() && item.merchant_id == this.merchant_id) .unwrap(); let diesel_payment_intent_update = diesel_models::PaymentIntentUpdate::from(update); let diesel_payment_intent = payment_intent .clone() .convert() .await .change_context(StorageError::EncryptionError)?; *payment_intent = PaymentIntent::convert_back( state, diesel_payment_intent_update.apply_changeset(diesel_payment_intent), key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; Ok(payment_intent.clone()) } #[cfg(feature = "v2")] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, update: PaymentIntentUpdate, key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { todo!() } #[cfg(feature = "v1")] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn find_payment_intent_by_payment_id_merchant_id( &self, _state: &KeyManagerState, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { let payment_intents = self.payment_intents.lock().await; Ok(payment_intents .iter() .find(|payment_intent| { payment_intent.get_id() == payment_id && payment_intent.merchant_id.eq(merchant_id) }) .cloned() .unwrap()) } #[cfg(feature = "v2")] async fn find_payment_intent_by_id( &self, _state: &KeyManagerState, id: &common_utils::id_type::GlobalPaymentId, _merchant_key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let payment_intents = self.payment_intents.lock().await; let payment_intent = payment_intents .iter() .find(|payment_intent| payment_intent.get_id() == id) .ok_or(StorageError::ValueNotFound( "PaymentIntent not found".to_string(), ))?; Ok(payment_intent.clone()) } #[cfg(feature = "v2")] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, _state: &KeyManagerState, merchant_reference_id: &common_utils::id_type::PaymentReferenceId, profile_id: &common_utils::id_type::ProfileId, _merchant_key_store: &MerchantKeyStore, _storage_scheme: &common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let payment_intents = self.payment_intents.lock().await; let payment_intent = payment_intents .iter() .find(|payment_intent| { payment_intent.merchant_reference_id.as_ref() == Some(merchant_reference_id) && payment_intent.profile_id.eq(profile_id) }) .ok_or(StorageError::ValueNotFound( "PaymentIntent not found".to_string(), ))?; Ok(payment_intent.clone()) } } <file_sep> pack="QBP-B" entity="payment_intent" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-03-11-171330_add-force-3ds-challenge-in-payment-intent/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE payment_intent DROP COLUMN IF EXISTS force_3ds_challenge;
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/mock_db/payment_intent.rs<|crate|> storage_impl<|op|> select entity=payment_intent repo=hyperswitch tables=payment_intent joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="payment_intent" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-03-20-085151_force-3ds-challenge-triggered/up.sql" -- Your SQL goes here ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS force_3ds_challenge_trigger boolean DEFAULT false; <file_sep> pack="QBP-B" entity="payment_intent" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-03-20-085151_force-3ds-challenge-triggered/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE payment_intent DROP COLUMN IF EXISTS force_3ds_challenge_trigger; <file_sep> pack="QBP-B" entity="payment_intent" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_payment_intent.rs" // schema snippet for entity=payment_intent repo=hyperswitch // table: payment_intent columns: [] entities: [payment_intent] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/payment_link.rs<|crate|> router<|op|> select entity=payment_link repo=hyperswitch tables=payment_link joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="payment_link" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/payment_link.rs" use common_utils::types::MinorUnit; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::payment_link}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = payment_link, primary_key(payment_link_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentLink { pub payment_link_id: String, pub payment_id: common_utils::id_type::PaymentId, pub link_to_pay: String, pub merchant_id: common_utils::id_type::MerchantId, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub fulfilment_time: Option<PrimitiveDateTime>, pub custom_merchant_name: Option<String>, pub payment_link_config: Option<serde_json::Value>, pub description: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub secure_link: Option<String>, } #[derive( Clone, Debug, Eq, PartialEq, Insertable, serde::Serialize, serde::Deserialize, router_derive::DebugAsDisplay, )] #[diesel(table_name = payment_link)] pub struct PaymentLinkNew { pub payment_link_id: String, pub payment_id: common_utils::id_type::PaymentId, pub link_to_pay: String, pub merchant_id: common_utils::id_type::MerchantId, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_modified_at: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub fulfilment_time: Option<PrimitiveDateTime>, pub custom_merchant_name: Option<String>, pub payment_link_config: Option<serde_json::Value>, pub description: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub secure_link: Option<String>, } <file_sep> pack="QBP-A" entity="payment_link" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/payment_link.rs" use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ payment_link::{PaymentLink, PaymentLinkNew}, schema::payment_link::dsl, PgPooledConn, StorageResult, }; impl PaymentLinkNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentLink> { generics::generic_insert(conn, self).await } } impl PaymentLink { pub async fn find_link_by_payment_link_id( conn: &PgPooledConn, payment_link_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_link_id.eq(payment_link_id.to_owned()), ) .await } } <file_sep> pack="QBP-A" entity="payment_link" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/payment_link.rs" use error_stack::report; use router_env::{instrument, tracing}; use crate::{ connection, core::errors::{self, CustomResult}, db::MockDb, services::Store, types::storage::{self, PaymentLinkDbExt}, }; #[async_trait::async_trait] pub trait PaymentLinkInterface { async fn find_payment_link_by_payment_link_id( &self, payment_link_id: &str, ) -> CustomResult<storage::PaymentLink, errors::StorageError>; async fn insert_payment_link( &self, _payment_link: storage::PaymentLinkNew, ) -> CustomResult<storage::PaymentLink, errors::StorageError>; async fn list_payment_link_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_link_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError>; } #[async_trait::async_trait] impl PaymentLinkInterface for Store { #[instrument(skip_all)] async fn find_payment_link_by_payment_link_id( &self, payment_link_id: &str, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::PaymentLink::find_link_by_payment_link_id(&conn, payment_link_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_payment_link( &self, payment_link_config: storage::PaymentLinkNew, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; payment_link_config .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_payment_link_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_link_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::PaymentLink::filter_by_constraints(&conn, merchant_id, payment_link_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl PaymentLinkInterface for MockDb { async fn insert_payment_link( &self, _payment_link: storage::PaymentLinkNew, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn find_payment_link_by_payment_link_id( &self, _payment_link_id: &str, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } async fn list_payment_link_by_merchant_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payment_link_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } } <file_sep> pack="QBP-A" entity="payment_link" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-11-24-115538_add_profile_id_payment_link/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE payment_link DROP COLUMN profile_id; <file_sep> pack="QBP-A" entity="payment_link" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-07-17-131830_alter_payment_link/up.sql" -- Add a new column for allowed domains and secure link endpoint ALTER table payment_link ADD COLUMN IF NOT EXISTS secure_link VARCHAR(255); <file_sep> pack="QBP-A" entity="payment_link" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-07-17-131830_alter_payment_link/down.sql" ALTER table payment_link DROP COLUMN IF EXISTS secure_link; <file_sep> pack="QBP-A" entity="payment_link" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_payment_link.rs" // schema snippet for entity=payment_link repo=hyperswitch // table: payment_link columns: [] entities: [payment_link] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/payment_method.rs<|crate|> storage_impl<|op|> select entity=payment_method repo=hyperswitch tables=payment_method joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="payment_method" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/payment_method.rs" 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(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] use crate::{enums as storage_enums, schema::payment_methods}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use crate::{enums as storage_enums, schema_v2::payment_methods}; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[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>, } #[cfg(all(feature = "v2", feature = "payment_methods_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 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, } impl PaymentMethod { #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub fn get_id(&self) -> &String { &self.payment_method_id } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId { &self.id } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[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>, } #[cfg(all(feature = "v2", feature = "payment_methods_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 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, } impl PaymentMethodNew { pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub fn get_id(&self) -> &String { &self.payment_method_id } #[cfg(all(feature = "v2", feature = "payment_methods_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(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[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>>, }, } #[cfg(all(feature = "v2", feature = "payment_methods_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>, }, 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(all(feature = "v2", feature = "payment_methods_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>, } #[cfg(all(feature = "v2", feature = "payment_methods_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, } = 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), } } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[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(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] 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), } } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] 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, }, } } } #[cfg(all(feature = "v2", feature = "payment_methods_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, }, 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, }, 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, }, 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, }, 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, }, 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, } => 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, }, 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, }, } } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_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(), 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(), } } } #[cfg(all(feature = "v2", feature = "payment_methods_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(), } } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[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(all(feature = "v2", feature = "payment_methods_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_sep> pack="QBP-B" entity="payment_method" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/payment_method.rs" use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl, Table, }; use error_stack::ResultExt; use super::generics; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] use crate::schema::payment_methods::dsl; #[cfg(all(feature = "v2", feature = "payment_methods_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(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] 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(all(feature = "v2", feature = "payment_methods_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") } }
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/payment_method.rs<|crate|> storage_impl<|op|> select entity=payment_method repo=hyperswitch tables=payment_method joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="payment_method" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/payment_method.rs" use diesel_models::payment_method::PaymentMethod; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for PaymentMethod {} use common_enums::enums::MerchantStorageScheme; use common_utils::{errors::CustomResult, id_type, types::keymanager::KeyManagerState}; use diesel_models::{ kv, payment_method::{PaymentMethodUpdate, PaymentMethodUpdateInternal}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, payment_methods::{PaymentMethod as DomainPaymentMethod, PaymentMethodInterface}, }; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ diesel_error_to_data_error, errors, kv_router_store::{ FilterResourceParams, FindResourceBy, InsertResourceParams, KVRouterStore, UpdateResourceParams, }, redis::kv_store::{Op, PartitionKey}, utils::{pg_connection_read, pg_connection_write}, DatabaseStore, RouterStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> { type Error = errors::StorageError; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( state, key_store, storage_scheme, PaymentMethod::find_by_payment_method_id(&conn, payment_method_id), FindResourceBy::LookupId(format!("payment_method_{}", payment_method_id)), ) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( state, key_store, storage_scheme, PaymentMethod::find_by_id(&conn, payment_method_id), FindResourceBy::LookupId(format!( "payment_method_{}", payment_method_id.get_string_repr() )), ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn find_payment_method_by_locker_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, locker_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( state, key_store, storage_scheme, PaymentMethod::find_by_locker_id(&conn, locker_id), FindResourceBy::LookupId(format!("payment_method_locker_{}", locker_id)), ) .await } // not supported in kv #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.router_store .get_payment_method_count_by_customer_id_merchant_id_status( customer_id, merchant_id, status, ) .await } #[instrument(skip_all)] async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.router_store .get_payment_method_count_by_merchant_id_status(merchant_id, status) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] async fn insert_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .insert_payment_method(state, key_store, payment_method, storage_scheme) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn insert_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_write(self).await?; let mut payment_method_new = payment_method .construct_new() .await .change_context(errors::StorageError::DecryptionError)?; payment_method_new.update_storage_scheme(storage_scheme); let key = PartitionKey::MerchantIdCustomerId { merchant_id: &payment_method_new.merchant_id.clone(), customer_id: &payment_method_new.customer_id.clone(), }; let identifier = format!("payment_method_id_{}", payment_method_new.get_id()); let lookup_id1 = format!("payment_method_{}", payment_method_new.get_id()); let mut reverse_lookups = vec![lookup_id1]; if let Some(locker_id) = &payment_method_new.locker_id { reverse_lookups.push(format!("payment_method_locker_{}", locker_id)) } let payment_method = (&payment_method_new.clone()).into(); self.insert_resource( state, key_store, storage_scheme, payment_method_new.clone().insert(&conn), payment_method, InsertResourceParams { insertable: kv::Insertable::PaymentMethod(payment_method_new.clone()), reverse_lookups, key, identifier, resource_type: "payment_method", }, ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let merchant_id = payment_method.merchant_id.clone(); let customer_id = payment_method.customer_id.clone(); let key = PartitionKey::MerchantIdCustomerId { merchant_id: &merchant_id, customer_id: &customer_id, }; let conn = pg_connection_write(self).await?; let field = format!("payment_method_id_{}", payment_method.get_id().clone()); let p_update: PaymentMethodUpdateInternal = payment_method_update.convert_to_payment_method_update(storage_scheme); let updated_payment_method = p_update.clone().apply_changeset(payment_method.clone()); self.update_resource( state, key_store, storage_scheme, payment_method .clone() .update_with_payment_method_id(&conn, p_update.clone()), updated_payment_method, UpdateResourceParams { updateable: kv::Updateable::PaymentMethodUpdate(Box::new( kv::PaymentMethodUpdateMems { orig: payment_method.clone(), update_data: p_update.clone(), }, )), operation: Op::Update( key.clone(), &field, payment_method.clone().updated_by.as_deref(), ), }, ) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .update_payment_method( state, key_store, payment_method, payment_method_update, storage_scheme, ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_by_customer_id_merchant_id_list( state, key_store, customer_id, merchant_id, limit, ) .await } // Need to fix this once we start moving to v2 for payment method #[cfg(all( feature = "v2", feature = "customer_v2", feature = "payment_methods_v2" ))] async fn find_payment_method_list_by_global_customer_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_list_by_global_customer_id(state, key_store, customer_id, limit) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.filter_resources( state, key_store, storage_scheme, PaymentMethod::find_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), |pm| pm.status == status, FilterResourceParams { key: PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }, pattern: "payment_method_id_*", limit, }, ) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_by_global_customer_id_merchant_id_status( state, key_store, customer_id, merchant_id, status, limit, storage_scheme, ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .delete_payment_method_by_merchant_id_payment_method_id( state, key_store, merchant_id, payment_method_id, ) .await } // Soft delete, Check if KV stuff is needed here #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn delete_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .delete_payment_method(state, key_store, payment_method) .await } // Check if KV stuff is needed here #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn find_payment_method_by_fingerprint_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.router_store .find_payment_method_by_fingerprint_id(state, key_store, fingerprint_id) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> { type Error = errors::StorageError; #[instrument(skip_all)] #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_payment_method_id(&conn, payment_method_id), ) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_id(&conn, payment_method_id), ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn find_payment_method_by_locker_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, locker_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_locker_id(&conn, locker_id), ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let conn = pg_connection_read(self).await?; PaymentMethod::get_count_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, ) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } #[instrument(skip_all)] async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let conn = pg_connection_read(self).await?; PaymentMethod::get_count_by_merchant_id_status(&conn, merchant_id, status) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } #[instrument(skip_all)] async fn insert_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method_new = payment_method .construct_new() .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database(state, key_store, payment_method_new.insert(&conn)) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database( state, key_store, payment_method.update_with_payment_method_id(&conn, payment_method_update.into()), ) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database( state, key_store, payment_method.update_with_id(&conn, payment_method_update.into()), ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id, limit), ) .await } // Need to fix this once we move to payment method for customer #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_payment_method_list_by_global_customer_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_global_customer_id(&conn, id, limit), ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), ) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_global_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_write(self).await?; self.call_database( state, key_store, PaymentMethod::delete_by_merchant_id_payment_method_id( &conn, merchant_id, payment_method_id, ), ) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn delete_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; let payment_method_update = PaymentMethodUpdate::StatusUpdate { status: Some(common_enums::PaymentMethodStatus::Inactive), }; self.call_database( state, key_store, payment_method.update_with_id(&conn, payment_method_update.into()), ) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn find_payment_method_by_fingerprint_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_fingerprint_id(&conn, fingerprint_id), ) .await } } #[async_trait::async_trait] impl PaymentMethodInterface for MockDb { type Error = errors::StorageError; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.find_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.get_id() == payment_method_id, "cannot find payment method".to_string(), ) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.find_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.get_id() == payment_method_id, "cannot find payment method".to_string(), ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn find_payment_method_by_locker_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, locker_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.find_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.locker_id == Some(locker_id.to_string()), "cannot find payment method".to_string(), ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let count = payment_methods .iter() .filter(|pm| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }) .count(); i64::try_from(count).change_context(errors::StorageError::MockDbError) } async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let count = payment_methods .iter() .filter(|pm| pm.merchant_id == *merchant_id && pm.status == status) .count(); i64::try_from(count).change_context(errors::StorageError::MockDbError) } async fn insert_payment_method( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let mut payment_methods = self.payment_methods.lock().await; let pm = Conversion::convert(payment_method.clone()) .await .change_context(errors::StorageError::DecryptionError)?; payment_methods.push(pm); Ok(payment_method) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, _limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.find_resources( state, key_store, payment_methods, |pm| pm.customer_id == *customer_id && pm.merchant_id == *merchant_id, "cannot find payment method".to_string(), ) .await } // Need to fix this once we complete v2 payment method #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_payment_method_list_by_global_customer_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, _id: &id_type::GlobalCustomerId, _limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { todo!() } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, _limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.find_resources( state, key_store, payment_methods, |pm| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }, "cannot find payment method".to_string(), ) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, _limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let find_pm_by = |pm: &&PaymentMethod| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }; let error_message = "cannot find payment method".to_string(); self.find_resources(state, key_store, payment_methods, find_pm_by, error_message) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let mut payment_methods = self.payment_methods.lock().await; match payment_methods .iter() .position(|pm| pm.merchant_id == *merchant_id && pm.get_id() == payment_method_id) { Some(index) => { let deleted_payment_method = payment_methods.remove(index); Ok(deleted_payment_method .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?) } None => Err(errors::StorageError::ValueNotFound( "cannot find payment method to delete".to_string(), ) .into()), } } async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update) .apply_changeset( Conversion::convert(payment_method.clone()) .await .change_context(errors::StorageError::EncryptionError)?, ); self.update_resource::<PaymentMethod, _>( state, key_store, self.payment_methods.lock().await, payment_method_updated, |pm| pm.get_id() == payment_method.get_id(), "cannot update payment method".to_string(), ) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn delete_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method_update = PaymentMethodUpdate::StatusUpdate { status: Some(common_enums::PaymentMethodStatus::Inactive), }; let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update) .apply_changeset( Conversion::convert(payment_method.clone()) .await .change_context(errors::StorageError::EncryptionError)?, ); self.update_resource::<PaymentMethod, _>( state, key_store, self.payment_methods.lock().await, payment_method_updated, |pm| pm.get_id() == payment_method.get_id(), "cannot find payment method".to_string(), ) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn find_payment_method_by_fingerprint_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.find_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.locker_fingerprint_id == Some(fingerprint_id.to_string()), "cannot find payment method".to_string(), ) .await } } <file_sep> pack="QBP-B" entity="payment_method" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-09-12-123315_add_network_token_locker_id_and_network_token_payment_method_data_and_network_token_ref_id_in_payment_methods/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE payment_methods DROP COLUMN IF EXISTS network_token_requestor_reference_id; ALTER TABLE payment_methods DROP COLUMN IF EXISTS network_token_locker_id; ALTER TABLE payment_methods DROP COLUMN IF EXISTS network_token_payment_method_data; <file_sep> pack="QBP-B" entity="payment_method" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql" ALTER TABLE ORGANIZATION ADD COLUMN org_id VARCHAR(32), ADD COLUMN org_name TEXT; ALTER TABLE merchant_account ADD COLUMN merchant_id VARCHAR(64), ADD COLUMN return_url VARCHAR(255), ADD COLUMN enable_payment_response_hash BOOLEAN DEFAULT FALSE, ADD COLUMN payment_response_hash_key VARCHAR(255), ADD COLUMN redirect_to_merchant_with_http_post BOOLEAN DEFAULT FALSE, ADD COLUMN sub_merchants_enabled BOOLEAN DEFAULT FALSE, ADD COLUMN parent_merchant_id VARCHAR(64), ADD COLUMN locker_id VARCHAR(64), ADD COLUMN intent_fulfillment_time BIGINT, ADD COLUMN default_profile VARCHAR(64), ADD COLUMN payment_link_config JSONB NULL, ADD COLUMN pm_collect_link_config JSONB NULL, ADD COLUMN is_recon_enabled BOOLEAN, ADD COLUMN webhook_details JSON NULL, ADD COLUMN routing_algorithm JSON, ADD COLUMN frm_routing_algorithm JSONB, ADD COLUMN payout_routing_algorithm JSONB; -- The default value is for temporary purpose only ALTER TABLE merchant_account ADD COLUMN primary_business_details JSON; ALTER TABLE business_profile ADD COLUMN profile_id VARCHAR(64), ADD COLUMN routing_algorithm JSON DEFAULT NULL, ADD COLUMN intent_fulfillment_time BIGINT DEFAULT NULL, ADD COLUMN frm_routing_algorithm JSONB DEFAULT NULL, ADD COLUMN payout_routing_algorithm JSONB DEFAULT NULL; ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS business_country "CountryAlpha2", ADD COLUMN IF NOT EXISTS business_label VARCHAR(255), ADD COLUMN IF NOT EXISTS business_sub_label VARCHAR(64), ADD COLUMN IF NOT EXISTS test_mode BOOLEAN, ADD COLUMN IF NOT EXISTS frm_configs jsonb, ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(128); ALTER TABLE customers ADD COLUMN customer_id VARCHAR(64), ADD COLUMN address_id VARCHAR(64); ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS payment_id VARCHAR(64), ADD COLUMN connector_id VARCHAR(64), ADD COLUMN shipping_address_id VARCHAR(64), ADD COLUMN billing_address_id VARCHAR(64), ADD COLUMN shipping_details BYTEA, ADD COLUMN billing_details BYTEA, ADD COLUMN statement_descriptor_suffix VARCHAR(255), ADD COLUMN business_country "CountryAlpha2", ADD COLUMN business_label VARCHAR(64), ADD COLUMN incremental_authorization_allowed BOOLEAN, ADD COLUMN merchant_decision VARCHAR(64), ADD COLUMN fingerprint_id VARCHAR(64), ADD COLUMN statement_descriptor_name VARCHAR(255), ADD COLUMN amount_to_capture BIGINT, ADD COLUMN off_session BOOLEAN, ADD COLUMN payment_confirm_source "PaymentSource", ADD COLUMN merchant_order_reference_id VARCHAR(255), ADD COLUMN is_payment_processor_token_flow BOOLEAN, ADD COLUMN charges jsonb; ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS attempt_id VARCHAR(64), ADD COLUMN amount bigint, ADD COLUMN currency "Currency", ADD COLUMN save_to_locker BOOLEAN, ADD COLUMN offer_amount bigint, ADD COLUMN payment_method VARCHAR, ADD COLUMN connector_transaction_id VARCHAR(128), ADD COLUMN connector_transaction_data VARCHAR(512), ADD COLUMN processor_transaction_data text, ADD COLUMN capture_method "CaptureMethod", ADD COLUMN capture_on TIMESTAMP, ADD COLUMN mandate_id VARCHAR(64), ADD COLUMN payment_method_type VARCHAR(64), ADD COLUMN business_sub_label VARCHAR(64), ADD COLUMN mandate_details JSONB, ADD COLUMN mandate_data JSONB, ADD COLUMN tax_amount bigint, ADD COLUMN straight_through_algorithm JSONB, ADD COLUMN confirm BOOLEAN, ADD COLUMN authentication_data JSON, ADD COLUMN payment_method_billing_address_id VARCHAR(64), ADD COLUMN connector_mandate_detail JSONB, ADD COLUMN charge_id VARCHAR(64); -- Create the index which was dropped because of dropping the column CREATE INDEX payment_attempt_connector_transaction_id_merchant_id_index ON payment_attempt (connector_transaction_id, merchant_id); CREATE UNIQUE INDEX payment_attempt_payment_id_merchant_id_attempt_id_index ON payment_attempt (payment_id, merchant_id, attempt_id); -- Payment Methods CREATE TYPE "PaymentMethodIssuerCode" AS ENUM ( 'jp_hdfc', 'jp_icici', 'jp_googlepay', 'jp_applepay', 'jp_phonepe', 'jp_wechat', 'jp_sofort', 'jp_giropay', 'jp_sepa', 'jp_bacs' ); ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS payment_method_id VARCHAR(64), ADD COLUMN IF NOT EXISTS accepted_currency "Currency" [ ], ADD COLUMN IF NOT EXISTS scheme VARCHAR(32), ADD COLUMN IF NOT EXISTS token VARCHAR(128), ADD COLUMN IF NOT EXISTS cardholder_name VARCHAR(255), ADD COLUMN IF NOT EXISTS issuer_name VARCHAR(64), ADD COLUMN IF NOT EXISTS issuer_country VARCHAR(64), ADD COLUMN IF NOT EXISTS payer_country TEXT [ ], ADD COLUMN IF NOT EXISTS is_stored BOOLEAN, ADD COLUMN IF NOT EXISTS direct_debit_token VARCHAR(128), ADD COLUMN IF NOT EXISTS swift_code VARCHAR(32), ADD COLUMN IF NOT EXISTS payment_method_issuer VARCHAR(128), ADD COLUMN IF NOT EXISTS metadata JSON, ADD COLUMN IF NOT EXISTS payment_method VARCHAR, ADD COLUMN IF NOT EXISTS payment_method_type VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_issuer_code "PaymentMethodIssuerCode"; ALTER TABLE refund ADD COLUMN connector_refund_data VARCHAR(512), ADD COLUMN connector_transaction_data VARCHAR(512); ALTER TABLE captures ADD COLUMN connector_capture_data VARCHAR(512); ALTER TABLE refund ADD COLUMN IF NOT EXISTS internal_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS refund_id VARCHAR(64), ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(64); <file_sep> pack="QBP-B" entity="payment_method" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/down.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR(64)` column for tables that had it removed. -- It must be ensured that the deployed version of the application includes the `id` column in any of its queries. -- Re-create the id column as this was used as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account ADD COLUMN id VARCHAR(64); ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account ADD COLUMN id VARCHAR(64); ------------------------ Customers ----------------------- ALTER TABLE customers ADD COLUMN id VARCHAR(64); ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent ADD COLUMN id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt ADD COLUMN id VARCHAR(64); ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods ADD COLUMN id VARCHAR(64); ------------------------ Address ----------------------- ALTER TABLE address ADD COLUMN id VARCHAR(64); ------------------------ Dispute ----------------------- ALTER TABLE dispute ADD COLUMN id VARCHAR(64); ------------------------ Mandate ----------------------- ALTER TABLE mandate ADD COLUMN id VARCHAR(64); ------------------------ Refund ----------------------- ALTER TABLE refund ADD COLUMN id VARCHAR(64); ------------------------ BlockList ----------------------- ALTER TABLE blocklist ADD COLUMN id VARCHAR(64); ------------------------ Roles ----------------------- ALTER TABLE roles ADD COLUMN id VARCHAR(64); ------------------------ Users ----------------------- ALTER TABLE users ADD COLUMN id VARCHAR(64); <file_sep> pack="QBP-B" entity="payment_method" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_payment_method.rs" // schema snippet for entity=payment_method repo=hyperswitch // table: payment_methods columns: [] entities: [payment_method] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/mock_db/payout_attempt.rs<|crate|> storage_impl<|op|> update entity=payout_attempt repo=hyperswitch tables=payout_attempt joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="payout_attempt" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/payout_attempt.rs" use common_utils::{ payout_method_utils, 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: String, 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>, } #[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: String, 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>, } #[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>, }, 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>, } 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, } } } 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, } => Self { connector_payout_id, status: Some(status), error_message, error_code, is_eligible, unified_code, unified_message, ..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, } = 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), ..source } } } <file_sep> pack="QBP-B" entity="payout_attempt" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/payout_attempt.rs" use std::collections::HashSet; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ associations::HasTable, query_dsl::methods::{DistinctDsl, FilterDsl, SelectDsl}, BoolExpressionMethods, ExpressionMethods, }; use error_stack::{report, ResultExt}; use super::generics; use crate::{ enums, errors::DatabaseError, payout_attempt::{ PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal, }, schema::{payout_attempt::dsl, payouts as payout_dsl}, Payouts, PgPooledConn, StorageResult, }; impl PayoutAttemptNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PayoutAttempt> { generics::generic_insert(conn, self).await } } impl PayoutAttempt { pub async fn update_with_attempt_id( self, conn: &PgPooledConn, payout_attempt_update: PayoutAttemptUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::payout_attempt_id .eq(self.payout_attempt_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), PayoutAttemptUpdateInternal::from(payout_attempt_update), ) .await { Err(error) => match error.current_context() { DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn find_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), ) .await } pub async fn find_by_merchant_id_payout_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_attempt_id.eq(payout_attempt_id.to_owned())), ) .await } pub async fn find_by_merchant_id_connector_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_payout_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_payout_id.eq(connector_payout_id.to_owned())), ) .await } pub async fn update_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &str, payout: PayoutAttemptUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), PayoutAttemptUpdateInternal::from(payout), ) .await? .first() .cloned() .ok_or_else(|| { report!(DatabaseError::NotFound).attach_printable("Error while updating payout") }) } pub async fn update_by_merchant_id_payout_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, payout: PayoutAttemptUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_attempt_id.eq(payout_attempt_id.to_owned())), PayoutAttemptUpdateInternal::from(payout), ) .await? .first() .cloned() .ok_or_else(|| { report!(DatabaseError::NotFound).attach_printable("Error while updating payout") }) } pub async fn get_filters_for_payouts( conn: &PgPooledConn, payouts: &[Payouts], merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<( Vec<String>, Vec<enums::Currency>, Vec<enums::PayoutStatus>, Vec<enums::PayoutType>, )> { let active_attempt_ids = payouts .iter() .map(|payout| { format!( "{}_{}", payout.payout_id.clone(), payout.attempt_count.clone() ) }) .collect::<Vec<String>>(); let active_payout_ids = payouts .iter() .map(|payout| payout.payout_id.clone()) .collect::<Vec<String>>(); let filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::payout_attempt_id.eq_any(active_attempt_ids)); let payouts_filter = <Payouts as HasTable>::table() .filter(payout_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(payout_dsl::payout_id.eq_any(active_payout_ids)); let payout_status: Vec<enums::PayoutStatus> = payouts .iter() .map(|payout| payout.status) .collect::<HashSet<enums::PayoutStatus>>() .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 = payouts_filter .clone() .select(payout_dsl::destination_currency) .distinct() .get_results_async::<enums::Currency>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by currency")? .into_iter() .collect::<Vec<enums::Currency>>(); let filter_payout_method = payouts_filter .clone() .select(payout_dsl::payout_type) .distinct() .get_results_async::<Option<enums::PayoutType>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by payout type")? .into_iter() .flatten() .collect::<Vec<enums::PayoutType>>(); Ok(( filter_connector, filter_currency, payout_status, filter_payout_method, )) } } <file_sep> pack="QBP-B" entity="payout_attempt" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/mock_db/payout_attempt.rs" use common_utils::errors::CustomResult; use diesel_models::enums as storage_enums; use hyperswitch_domain_models::payouts::{ payout_attempt::{ PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate, }, payouts::Payouts, }; use super::MockDb; use crate::errors::StorageError; #[async_trait::async_trait] impl PayoutAttemptInterface for MockDb { type Error = StorageError; async fn update_payout_attempt( &self, _this: &PayoutAttempt, _payout_attempt_update: PayoutAttemptUpdate, _payouts: &Payouts, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } async fn insert_payout_attempt( &self, _payout_attempt: PayoutAttemptNew, _payouts: &Payouts, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payout_attempt_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _connector_payout_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } async fn get_filters_for_payouts( &self, _payouts: &[Payouts], _merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult< hyperswitch_domain_models::payouts::payout_attempt::PayoutListFilters, StorageError, > { Err(StorageError::MockDbError)? } } <file_sep> pack="QBP-B" entity="payout_attempt" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-06-04-140449_create_index_for_connector_payout_id_and_merchant_id_in_payout_attempt/up.sql" CREATE INDEX connector_payout_id_merchant_id_index ON payout_attempt (connector_payout_id, merchant_id); <file_sep> pack="QBP-B" entity="payout_attempt" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-09-15-080630_add_addtional_payout_method_data_column_to_payout_attempt_table/up.sql" -- Your SQL goes here ALTER TABLE payout_attempt ADD COLUMN IF NOT EXISTS additional_payout_method_data JSONB DEFAULT NULL; <file_sep> pack="QBP-B" entity="payout_attempt" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-09-15-080630_add_addtional_payout_method_data_column_to_payout_attempt_table/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE payout_attempt DROP COLUMN IF EXISTS additional_payout_method_data; <file_sep> pack="QBP-B" entity="payout_attempt" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_payout_attempt.rs" // schema snippet for entity=payout_attempt repo=hyperswitch // table: payout_attempt columns: [] entities: [payout_attempt] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/payouts/payout_attempt.rs<|crate|> storage_impl<|op|> update entity=payout_attempt repo=hyperswitch tables=payout_attempt joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="payout_attempt" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/payout_attempt.rs" use common_utils::{ payout_method_utils, 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: String, 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>, } #[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: String, 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>, } #[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>, }, 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>, } 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, } } } 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, } => Self { connector_payout_id, status: Some(status), error_message, error_code, is_eligible, unified_code, unified_message, ..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, } = 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), ..source } } } <file_sep> pack="QBP-B" entity="payout_attempt" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/payout_attempt.rs" use std::collections::HashSet; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ associations::HasTable, query_dsl::methods::{DistinctDsl, FilterDsl, SelectDsl}, BoolExpressionMethods, ExpressionMethods, }; use error_stack::{report, ResultExt}; use super::generics; use crate::{ enums, errors::DatabaseError, payout_attempt::{ PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal, }, schema::{payout_attempt::dsl, payouts as payout_dsl}, Payouts, PgPooledConn, StorageResult, }; impl PayoutAttemptNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PayoutAttempt> { generics::generic_insert(conn, self).await } } impl PayoutAttempt { pub async fn update_with_attempt_id( self, conn: &PgPooledConn, payout_attempt_update: PayoutAttemptUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::payout_attempt_id .eq(self.payout_attempt_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), PayoutAttemptUpdateInternal::from(payout_attempt_update), ) .await { Err(error) => match error.current_context() { DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn find_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), ) .await } pub async fn find_by_merchant_id_payout_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_attempt_id.eq(payout_attempt_id.to_owned())), ) .await } pub async fn find_by_merchant_id_connector_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_payout_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_payout_id.eq(connector_payout_id.to_owned())), ) .await } pub async fn update_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &str, payout: PayoutAttemptUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_id.eq(payout_id.to_owned())), PayoutAttemptUpdateInternal::from(payout), ) .await? .first() .cloned() .ok_or_else(|| { report!(DatabaseError::NotFound).attach_printable("Error while updating payout") }) } pub async fn update_by_merchant_id_payout_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, payout: PayoutAttemptUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payout_attempt_id.eq(payout_attempt_id.to_owned())), PayoutAttemptUpdateInternal::from(payout), ) .await? .first() .cloned() .ok_or_else(|| { report!(DatabaseError::NotFound).attach_printable("Error while updating payout") }) } pub async fn get_filters_for_payouts( conn: &PgPooledConn, payouts: &[Payouts], merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<( Vec<String>, Vec<enums::Currency>, Vec<enums::PayoutStatus>, Vec<enums::PayoutType>, )> { let active_attempt_ids = payouts .iter() .map(|payout| { format!( "{}_{}", payout.payout_id.clone(), payout.attempt_count.clone() ) }) .collect::<Vec<String>>(); let active_payout_ids = payouts .iter() .map(|payout| payout.payout_id.clone()) .collect::<Vec<String>>(); let filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::payout_attempt_id.eq_any(active_attempt_ids)); let payouts_filter = <Payouts as HasTable>::table() .filter(payout_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(payout_dsl::payout_id.eq_any(active_payout_ids)); let payout_status: Vec<enums::PayoutStatus> = payouts .iter() .map(|payout| payout.status) .collect::<HashSet<enums::PayoutStatus>>() .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 = payouts_filter .clone() .select(payout_dsl::destination_currency) .distinct() .get_results_async::<enums::Currency>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by currency")? .into_iter() .collect::<Vec<enums::Currency>>(); let filter_payout_method = payouts_filter .clone() .select(payout_dsl::payout_type) .distinct() .get_results_async::<Option<enums::PayoutType>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by payout type")? .into_iter() .flatten() .collect::<Vec<enums::PayoutType>>(); Ok(( filter_connector, filter_currency, payout_status, filter_payout_method, )) } } <file_sep> pack="QBP-B" entity="payout_attempt" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/payouts/payout_attempt.rs" use std::str::FromStr; use api_models::enums::PayoutConnectors; use common_utils::{errors::CustomResult, ext_traits::Encode, fallback_reverse_lookup_not_found}; use diesel_models::{ enums::MerchantStorageScheme, kv, payout_attempt::{ PayoutAttempt as DieselPayoutAttempt, PayoutAttemptNew as DieselPayoutAttemptNew, PayoutAttemptUpdate as DieselPayoutAttemptUpdate, }, reverse_lookup::ReverseLookup, ReverseLookupNew, }; use error_stack::ResultExt; use hyperswitch_domain_models::payouts::{ payout_attempt::{ PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate, PayoutListFilters, }, payouts::Payouts, }; use redis_interface::HsetnxReply; use router_env::{instrument, logger, tracing}; use crate::{ diesel_error_to_data_error, errors, errors::RedisErrorExt, kv_router_store::KVRouterStore, lookup::ReverseLookupInterface, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, pg_connection_read, pg_connection_write}, DataModelExt, DatabaseStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> { type Error = errors::StorageError; #[instrument(skip_all)] async fn insert_payout_attempt( &self, new_payout_attempt: PayoutAttemptNew, payouts: &Payouts, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payout_attempt(new_payout_attempt, payouts, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let merchant_id = new_payout_attempt.merchant_id.clone(); let payout_attempt_id = new_payout_attempt.payout_id.clone(); let key = PartitionKey::MerchantIdPayoutAttemptId { merchant_id: &merchant_id, payout_attempt_id: &payout_attempt_id, }; let key_str = key.to_string(); let created_attempt = PayoutAttempt { payout_attempt_id: new_payout_attempt.payout_attempt_id.clone(), payout_id: new_payout_attempt.payout_id.clone(), additional_payout_method_data: new_payout_attempt .additional_payout_method_data .clone(), customer_id: new_payout_attempt.customer_id.clone(), merchant_id: new_payout_attempt.merchant_id.clone(), address_id: new_payout_attempt.address_id.clone(), connector: new_payout_attempt.connector.clone(), connector_payout_id: new_payout_attempt.connector_payout_id.clone(), payout_token: new_payout_attempt.payout_token.clone(), status: new_payout_attempt.status, is_eligible: new_payout_attempt.is_eligible, error_message: new_payout_attempt.error_message.clone(), error_code: new_payout_attempt.error_code.clone(), business_country: new_payout_attempt.business_country, business_label: new_payout_attempt.business_label.clone(), created_at: new_payout_attempt.created_at, last_modified_at: new_payout_attempt.last_modified_at, profile_id: new_payout_attempt.profile_id.clone(), merchant_connector_id: new_payout_attempt.merchant_connector_id.clone(), routing_info: new_payout_attempt.routing_info.clone(), unified_code: new_payout_attempt.unified_code.clone(), unified_message: new_payout_attempt.unified_message.clone(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::PayoutAttempt( new_payout_attempt.to_storage_model(), )), }, }; // Reverse lookup for payout_attempt_id let field = format!("poa_{}", created_attempt.payout_attempt_id); let reverse_lookup = ReverseLookupNew { lookup_id: format!( "poa_{}_{}", &created_attempt.merchant_id.get_string_repr(), &created_attempt.payout_attempt_id, ), pk_id: key_str.clone(), sk_id: field.clone(), source: "payout_attempt".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup, storage_scheme) .await?; match Box::pin(kv_wrapper::<DieselPayoutAttempt, _, _>( self, KvOperation::<DieselPayoutAttempt>::HSetNx( &field, &created_attempt.clone().to_storage_model(), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "payout attempt", key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(created_attempt), Err(error) => Err(error.change_context(errors::StorageError::KVError)), } } } } #[instrument(skip_all)] async fn update_payout_attempt( &self, this: &PayoutAttempt, payout_update: PayoutAttemptUpdate, payouts: &Payouts, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let key = PartitionKey::MerchantIdPayoutAttemptId { merchant_id: &this.merchant_id, payout_attempt_id: &this.payout_id, }; let field = format!("poa_{}", this.payout_attempt_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>( self, storage_scheme, Op::Update(key.clone(), &field, None), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payout_attempt(this, payout_update, payouts, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let diesel_payout_update = payout_update.clone().to_storage_model(); let origin_diesel_payout = this.clone().to_storage_model(); let diesel_payout = diesel_payout_update .clone() .apply_changeset(origin_diesel_payout.clone()); // Check for database presence as well Maybe use a read replica here ? let redis_value = diesel_payout .encode_to_string_of_json() .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PayoutAttemptUpdate( kv::PayoutAttemptUpdateMems { orig: origin_diesel_payout, update_data: diesel_payout_update, }, )), }, }; let updated_attempt = PayoutAttempt::from_storage_model( payout_update .to_storage_model() .apply_changeset(this.clone().to_storage_model()), ); let old_connector_payout_id = this.connector_payout_id.clone(); match ( old_connector_payout_id, updated_attempt.connector_payout_id.clone(), ) { (Some(old), Some(new)) if old != new => { add_connector_payout_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.payout_attempt_id.as_str(), new.as_str(), storage_scheme, ) .await?; } (None, Some(new)) => { add_connector_payout_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.payout_attempt_id.as_str(), new.as_str(), storage_scheme, ) .await?; } _ => {} } Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPayoutAttempt>::Hset((&field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(PayoutAttempt::from_storage_model(diesel_payout)) } } } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, payout_attempt_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!("poa_{}_{payout_attempt_id}", merchant_id.get_string_repr()); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, self.router_store .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, payout_attempt_id, storage_scheme ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, payout_attempt_id, storage_scheme, ) .await }, )) .await } } } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_payout_id: &str, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_id, connector_payout_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!( "po_conn_payout_{}_{connector_payout_id}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, self.router_store .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_id, connector_payout_id, storage_scheme, ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_id, connector_payout_id, storage_scheme, ) .await }, )) .await } } } #[instrument(skip_all)] async fn get_filters_for_payouts( &self, payouts: &[Payouts], merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutListFilters, errors::StorageError> { self.router_store .get_filters_for_payouts(payouts, merchant_id, storage_scheme) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> { type Error = errors::StorageError; #[instrument(skip_all)] async fn insert_payout_attempt( &self, new: PayoutAttemptNew, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; new.to_storage_model() .insert(&conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PayoutAttempt::from_storage_model) } #[instrument(skip_all)] async fn update_payout_attempt( &self, this: &PayoutAttempt, payout: PayoutAttemptUpdate, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; this.clone() .to_storage_model() .update_with_attempt_id(&conn, payout.to_storage_model()) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PayoutAttempt::from_storage_model) } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPayoutAttempt::find_by_merchant_id_payout_attempt_id( &conn, merchant_id, payout_attempt_id, ) .await .map(PayoutAttempt::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_payout_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPayoutAttempt::find_by_merchant_id_connector_payout_id( &conn, merchant_id, connector_payout_id, ) .await .map(PayoutAttempt::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[instrument(skip_all)] async fn get_filters_for_payouts( &self, payouts: &[Payouts], merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PayoutListFilters, errors::StorageError> { let conn = pg_connection_read(self).await?; let payouts = payouts .iter() .cloned() .map(|payouts| payouts.to_storage_model()) .collect::<Vec<diesel_models::Payouts>>(); DieselPayoutAttempt::get_filters_for_payouts(&conn, payouts.as_slice(), merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map( |(connector, currency, status, payout_method)| PayoutListFilters { connector: connector .iter() .filter_map(|c| { PayoutConnectors::from_str(c) .map_err(|e| { logger::error!( "Failed to parse payout connector '{}' - {}", c, e ); }) .ok() }) .collect(), currency, status, payout_method, }, ) } } impl DataModelExt for PayoutAttempt { type StorageModel = DieselPayoutAttempt; fn to_storage_model(self) -> Self::StorageModel { DieselPayoutAttempt { payout_attempt_id: self.payout_attempt_id, payout_id: self.payout_id, customer_id: self.customer_id, merchant_id: self.merchant_id, address_id: self.address_id, connector: self.connector, connector_payout_id: self.connector_payout_id, payout_token: self.payout_token, status: self.status, is_eligible: self.is_eligible, error_message: self.error_message, error_code: self.error_code, business_country: self.business_country, business_label: self.business_label, created_at: self.created_at, last_modified_at: self.last_modified_at, profile_id: self.profile_id, merchant_connector_id: self.merchant_connector_id, routing_info: self.routing_info, unified_code: self.unified_code, unified_message: self.unified_message, additional_payout_method_data: self.additional_payout_method_data, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { payout_attempt_id: storage_model.payout_attempt_id, payout_id: storage_model.payout_id, customer_id: storage_model.customer_id, merchant_id: storage_model.merchant_id, address_id: storage_model.address_id, connector: storage_model.connector, connector_payout_id: storage_model.connector_payout_id, payout_token: storage_model.payout_token, status: storage_model.status, is_eligible: storage_model.is_eligible, error_message: storage_model.error_message, error_code: storage_model.error_code, business_country: storage_model.business_country, business_label: storage_model.business_label, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at, profile_id: storage_model.profile_id, merchant_connector_id: storage_model.merchant_connector_id, routing_info: storage_model.routing_info, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, additional_payout_method_data: storage_model.additional_payout_method_data, } } } impl DataModelExt for PayoutAttemptNew { type StorageModel = DieselPayoutAttemptNew; fn to_storage_model(self) -> Self::StorageModel { DieselPayoutAttemptNew { payout_attempt_id: self.payout_attempt_id, payout_id: self.payout_id, customer_id: self.customer_id, merchant_id: self.merchant_id, address_id: self.address_id, connector: self.connector, connector_payout_id: self.connector_payout_id, payout_token: self.payout_token, status: self.status, is_eligible: self.is_eligible, error_message: self.error_message, error_code: self.error_code, business_country: self.business_country, business_label: self.business_label, created_at: self.created_at, last_modified_at: self.last_modified_at, profile_id: self.profile_id, merchant_connector_id: self.merchant_connector_id, routing_info: self.routing_info, unified_code: self.unified_code, unified_message: self.unified_message, additional_payout_method_data: self.additional_payout_method_data, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { payout_attempt_id: storage_model.payout_attempt_id, payout_id: storage_model.payout_id, customer_id: storage_model.customer_id, merchant_id: storage_model.merchant_id, address_id: storage_model.address_id, connector: storage_model.connector, connector_payout_id: storage_model.connector_payout_id, payout_token: storage_model.payout_token, status: storage_model.status, is_eligible: storage_model.is_eligible, error_message: storage_model.error_message, error_code: storage_model.error_code, business_country: storage_model.business_country, business_label: storage_model.business_label, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at, profile_id: storage_model.profile_id, merchant_connector_id: storage_model.merchant_connector_id, routing_info: storage_model.routing_info, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, additional_payout_method_data: storage_model.additional_payout_method_data, } } } impl DataModelExt for PayoutAttemptUpdate { type StorageModel = DieselPayoutAttemptUpdate; fn to_storage_model(self) -> Self::StorageModel { match self { Self::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, } => DieselPayoutAttemptUpdate::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, }, Self::PayoutTokenUpdate { payout_token } => { DieselPayoutAttemptUpdate::PayoutTokenUpdate { payout_token } } Self::BusinessUpdate { business_country, business_label, address_id, customer_id, } => DieselPayoutAttemptUpdate::BusinessUpdate { business_country, business_label, address_id, customer_id, }, Self::UpdateRouting { connector, routing_info, merchant_connector_id, } => DieselPayoutAttemptUpdate::UpdateRouting { connector, routing_info, merchant_connector_id, }, Self::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, } => DieselPayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, }, } } #[allow(clippy::todo)] fn from_storage_model(_storage_model: Self::StorageModel) -> Self { todo!("Reverse map should no longer be needed") } } #[inline] #[instrument(skip_all)] async fn add_connector_payout_id_to_reverse_lookup<T: DatabaseStore>( store: &KVRouterStore<T>, key: &str, merchant_id: &common_utils::id_type::MerchantId, updated_attempt_attempt_id: &str, connector_payout_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let field = format!("poa_{}", updated_attempt_attempt_id); let reverse_lookup_new = ReverseLookupNew { lookup_id: format!( "po_conn_payout_{}_{}", merchant_id.get_string_repr(), connector_payout_id ), pk_id: key.to_owned(), sk_id: field.clone(), source: "payout_attempt".to_string(), updated_by: storage_scheme.to_string(), }; store .insert_reverse_lookup(reverse_lookup_new, storage_scheme) .await } <file_sep> pack="QBP-B" entity="payout_attempt" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-06-04-140449_create_index_for_connector_payout_id_and_merchant_id_in_payout_attempt/up.sql" CREATE INDEX connector_payout_id_merchant_id_index ON payout_attempt (connector_payout_id, merchant_id); <file_sep> pack="QBP-B" entity="payout_attempt" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-09-15-080630_add_addtional_payout_method_data_column_to_payout_attempt_table/up.sql" -- Your SQL goes here ALTER TABLE payout_attempt ADD COLUMN IF NOT EXISTS additional_payout_method_data JSONB DEFAULT NULL; <file_sep> pack="QBP-B" entity="payout_attempt" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-09-15-080630_add_addtional_payout_method_data_column_to_payout_attempt_table/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE payout_attempt DROP COLUMN IF EXISTS additional_payout_method_data; <file_sep> pack="QBP-B" entity="payout_attempt" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_payout_attempt.rs" // schema snippet for entity=payout_attempt repo=hyperswitch // table: payout_attempt columns: [] entities: [payout_attempt] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/relay.rs<|crate|> router<|op|> select entity=relay repo=hyperswitch tables=relay joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="relay" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/relay.rs" use common_utils::pii; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::relay}; #[derive( Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = relay)] pub struct Relay { pub id: common_utils::id_type::RelayId, pub connector_resource_id: String, pub connector_id: common_utils::id_type::MerchantConnectorAccountId, pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub relay_type: storage_enums::RelayType, pub request_data: Option<pii::SecretSerdeValue>, pub status: storage_enums::RelayStatus, pub connector_reference_id: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub response_data: Option<pii::SecretSerdeValue>, } #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, router_derive::Setter, )] #[diesel(table_name = relay)] pub struct RelayNew { pub id: common_utils::id_type::RelayId, pub connector_resource_id: String, pub connector_id: common_utils::id_type::MerchantConnectorAccountId, pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub relay_type: storage_enums::RelayType, pub request_data: Option<pii::SecretSerdeValue>, pub status: storage_enums::RelayStatus, pub connector_reference_id: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub response_data: Option<pii::SecretSerdeValue>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = relay)] pub struct RelayUpdateInternal { pub connector_reference_id: Option<String>, pub status: Option<storage_enums::RelayStatus>, pub error_code: Option<String>, pub error_message: Option<String>, pub modified_at: PrimitiveDateTime, } <file_sep> pack="QBP-A" entity="relay" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/relay.rs" use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ errors, relay::{Relay, RelayNew, RelayUpdateInternal}, schema::relay::dsl, PgPooledConn, StorageResult, }; impl RelayNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Relay> { generics::generic_insert(conn, self).await } } impl Relay { pub async fn update( self, conn: &PgPooledConn, relay: RelayUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, dsl::id.eq(self.id.to_owned()), relay) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } pub async fn find_by_id( conn: &PgPooledConn, id: &common_utils::id_type::RelayId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } pub async fn find_by_profile_id_connector_reference_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, connector_reference_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::connector_reference_id.eq(connector_reference_id.to_owned())), ) .await } } <file_sep> pack="QBP-A" entity="relay" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/relay.rs" use common_utils::types::keymanager::KeyManagerState; use diesel_models; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion}; use storage_impl::MockDb; use super::domain; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, services::Store, }; #[async_trait::async_trait] pub trait RelayInterface { async fn insert_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; async fn update_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: hyperswitch_domain_models::relay::Relay, relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; async fn find_relay_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; async fn find_relay_by_profile_id_connector_reference_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; } #[async_trait::async_trait] impl RelayInterface for Store { async fn insert_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn update_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: hyperswitch_domain_models::relay::Relay, relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; Conversion::convert(current_state) .await .change_context(errors::StorageError::EncryptionError)? .update( &conn, diesel_models::relay::RelayUpdateInternal::from(relay_update), ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_relay_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_models::relay::Relay::find_by_id(&conn, relay_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_relay_by_profile_id_connector_reference_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_models::relay::Relay::find_by_profile_id_connector_reference_id( &conn, profile_id, connector_reference_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } } #[async_trait::async_trait] impl RelayInterface for MockDb { async fn insert_relay( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_relay( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _current_state: hyperswitch_domain_models::relay::Relay, _relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_relay_by_id( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_relay_by_profile_id_connector_reference_id( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _profile_id: &common_utils::id_type::ProfileId, _connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl RelayInterface for KafkaStore { async fn insert_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .insert_relay(key_manager_state, merchant_key_store, new) .await } async fn update_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: hyperswitch_domain_models::relay::Relay, relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .update_relay( key_manager_state, merchant_key_store, current_state, relay_update, ) .await } async fn find_relay_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .find_relay_by_id(key_manager_state, merchant_key_store, relay_id) .await } async fn find_relay_by_profile_id_connector_reference_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .find_relay_by_profile_id_connector_reference_id( key_manager_state, merchant_key_store, profile_id, connector_reference_id, ) .await } } <file_sep> pack="QBP-A" entity="relay" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-17-141811_add_relay_table/up.sql" -- Your SQL goes here CREATE TYPE "RelayStatus" AS ENUM ('created', 'pending', 'failure', 'success'); CREATE TYPE "RelayType" AS ENUM ('refund'); CREATE TABLE relay ( id VARCHAR(64) PRIMARY KEY, connector_resource_id VARCHAR(128) NOT NULL, connector_id VARCHAR(64) NOT NULL, profile_id VARCHAR(64) NOT NULL, merchant_id VARCHAR(64) NOT NULL, relay_type "RelayType" NOT NULL, request_data JSONB DEFAULT NULL, status "RelayStatus" NOT NULL, connector_reference_id VARCHAR(128), error_code VARCHAR(64), error_message TEXT, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, modified_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, response_data JSONB DEFAULT NULL ); <file_sep> pack="QBP-A" entity="relay" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-17-141811_add_relay_table/down.sql" -- This file should undo anything in `up.sql` DROP TABLE relay; DROP TYPE IF EXISTS "RelayStatus"; DROP TYPE IF EXISTS "RelayType"; <file_sep> pack="QBP-A" entity="relay" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-01-07-105739_create_index_for_relay/up.sql" -- Your SQL goes here CREATE UNIQUE INDEX relay_profile_id_connector_reference_id_index ON relay (profile_id, connector_reference_id); <file_sep> pack="QBP-A" entity="relay" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_relay.rs" // schema snippet for entity=relay repo=hyperswitch // table: relay columns: [] entities: [relay] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/reverse_lookup.rs<|crate|> router<|op|> select entity=reverse_lookup repo=hyperswitch tables=reverse_lookup joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="reverse_lookup" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/reverse_lookup.rs" use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::reverse_lookup; /// This reverse lookup table basically looks up id's and get result_id that you want. This is /// useful for KV where you can't lookup without key #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, Eq, PartialEq, )] #[diesel(table_name = reverse_lookup, primary_key(lookup_id), check_for_backend(diesel::pg::Pg))] pub struct ReverseLookup { /// Primary key. The key id. pub lookup_id: String, /// the `field` in KV database. Which is used to differentiate between two same keys pub sk_id: String, /// the value id. i.e the id you want to access KV table. pub pk_id: String, /// the source of insertion for reference pub source: String, pub updated_by: String, } #[derive( Clone, Debug, Insertable, router_derive::DebugAsDisplay, Eq, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = reverse_lookup)] pub struct ReverseLookupNew { pub lookup_id: String, pub pk_id: String, pub sk_id: String, pub source: String, pub updated_by: String, } impl From<ReverseLookupNew> for ReverseLookup { fn from(new: ReverseLookupNew) -> Self { Self { lookup_id: new.lookup_id, sk_id: new.sk_id, pk_id: new.pk_id, source: new.source, updated_by: new.updated_by, } } } <file_sep> pack="QBP-A" entity="reverse_lookup" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/reverse_lookup.rs" use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ reverse_lookup::{ReverseLookup, ReverseLookupNew}, schema::reverse_lookup::dsl, PgPooledConn, StorageResult, }; impl ReverseLookupNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ReverseLookup> { generics::generic_insert(conn, self).await } pub async fn batch_insert( reverse_lookups: Vec<Self>, conn: &PgPooledConn, ) -> StorageResult<()> { generics::generic_insert::<_, _, ReverseLookup>(conn, reverse_lookups).await?; Ok(()) } } impl ReverseLookup { pub async fn find_by_lookup_id(lookup_id: &str, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::lookup_id.eq(lookup_id.to_owned()), ) .await } } <file_sep> pack="QBP-A" entity="reverse_lookup" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/reverse_lookup.rs" use super::{MockDb, Store}; use crate::{ errors::{self, CustomResult}, types::storage::{ enums, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }, }; #[async_trait::async_trait] pub trait ReverseLookupInterface { async fn insert_reverse_lookup( &self, _new: ReverseLookupNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError>; async fn get_lookup_by_lookup_id( &self, _id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError>; } #[cfg(not(feature = "kv_store"))] mod storage { use error_stack::report; use router_env::{instrument, tracing}; use super::{ReverseLookupInterface, Store}; use crate::{ connection, errors::{self, CustomResult}, types::storage::{ enums, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }, }; #[async_trait::async_trait] impl ReverseLookupInterface for Store { #[instrument(skip_all)] async fn insert_reverse_lookup( &self, new: ReverseLookupNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn get_lookup_by_lookup_id( &self, id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; ReverseLookup::find_by_lookup_id(id, &conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[cfg(feature = "kv_store")] mod storage { use error_stack::{report, ResultExt}; use redis_interface::SetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::{ReverseLookupInterface, Store}; use crate::{ connection, core::errors::utils::RedisErrorExt, errors::{self, CustomResult}, types::storage::{ enums, kv, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }, utils::db_utils, }; #[async_trait::async_trait] impl ReverseLookupInterface for Store { #[instrument(skip_all)] async fn insert_reverse_lookup( &self, new: ReverseLookupNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, ReverseLookup>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } enums::MerchantStorageScheme::RedisKv => { let created_rev_lookup = ReverseLookup { lookup_id: new.lookup_id.clone(), sk_id: new.sk_id.clone(), pk_id: new.pk_id.clone(), source: new.source.clone(), updated_by: storage_scheme.to_string(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::ReverseLookUp(new)), }, }; match Box::pin(kv_wrapper::<ReverseLookup, _, _>( self, KvOperation::SetNx(&created_rev_lookup, redis_entry), PartitionKey::CombinationKey { combination: &format!( "reverse_lookup_{}", &created_rev_lookup.lookup_id ), }, )) .await .map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))? .try_into_setnx() { Ok(SetnxReply::KeySet) => Ok(created_rev_lookup), Ok(SetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "reverse_lookup", key: Some(created_rev_lookup.lookup_id.clone()), } .into()), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } #[instrument(skip_all)] async fn get_lookup_by_lookup_id( &self, id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; ReverseLookup::find_by_lookup_id(id, &conn) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, ReverseLookup>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let redis_fut = async { Box::pin(kv_wrapper( self, KvOperation::<ReverseLookup>::Get, PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{id}"), }, )) .await? .try_into_get() }; Box::pin(db_utils::try_redis_get_else_try_database_get( redis_fut, database_call, )) .await } } } } } #[async_trait::async_trait] impl ReverseLookupInterface for MockDb { async fn insert_reverse_lookup( &self, new: ReverseLookupNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let reverse_lookup_insert = ReverseLookup::from(new); self.reverse_lookups .lock() .await .push(reverse_lookup_insert.clone()); Ok(reverse_lookup_insert) } async fn get_lookup_by_lookup_id( &self, lookup_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { self.reverse_lookups .lock() .await .iter() .find(|reverse_lookup| reverse_lookup.lookup_id == lookup_id) .ok_or( errors::StorageError::ValueNotFound(format!( "No reverse lookup found for lookup_id = {}", lookup_id )) .into(), ) .cloned() } } <file_sep> pack="QBP-A" entity="reverse_lookup" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2022-12-12-132936_reverse_lookup/up.sql" CREATE TABLE reverse_lookup ( lookup_id VARCHAR(255) NOT NULL PRIMARY KEY, sk_id VARCHAR(50) NOT NULL, pk_id VARCHAR(255) NOT NULL, source VARCHAR(30) NOT NULL ); CREATE INDEX lookup_id_index ON reverse_lookup (lookup_id); <file_sep> pack="QBP-A" entity="reverse_lookup" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2022-12-12-132936_reverse_lookup/down.sql" DROP TABLE IF EXISTS reverse_lookup; <file_sep> pack="QBP-A" entity="reverse_lookup" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-10-13-090450_add_updated_by_for_tables/up.sql" ALTER TABLE payment_intent ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE payment_attempt ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE refund ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE connector_response ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE reverse_lookup ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE address ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; <file_sep> pack="QBP-A" entity="reverse_lookup" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_reverse_lookup.rs" // schema snippet for entity=reverse_lookup repo=hyperswitch // table: reverse_lookup columns: [] entities: [reverse_lookup] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/reverse_lookup.rs<|crate|> storage_impl<|op|> select entity=reverse_lookup repo=hyperswitch tables=reverse_lookup joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-B" entity="reverse_lookup" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/reverse_lookup.rs" use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::reverse_lookup; /// This reverse lookup table basically looks up id's and get result_id that you want. This is /// useful for KV where you can't lookup without key #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, Eq, PartialEq, )] #[diesel(table_name = reverse_lookup, primary_key(lookup_id), check_for_backend(diesel::pg::Pg))] pub struct ReverseLookup { /// Primary key. The key id. pub lookup_id: String, /// the `field` in KV database. Which is used to differentiate between two same keys pub sk_id: String, /// the value id. i.e the id you want to access KV table. pub pk_id: String, /// the source of insertion for reference pub source: String, pub updated_by: String, } #[derive( Clone, Debug, Insertable, router_derive::DebugAsDisplay, Eq, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = reverse_lookup)] pub struct ReverseLookupNew { pub lookup_id: String, pub pk_id: String, pub sk_id: String, pub source: String, pub updated_by: String, } impl From<ReverseLookupNew> for ReverseLookup { fn from(new: ReverseLookupNew) -> Self { Self { lookup_id: new.lookup_id, sk_id: new.sk_id, pk_id: new.pk_id, source: new.source, updated_by: new.updated_by, } } } <file_sep> pack="QBP-B" entity="reverse_lookup" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/reverse_lookup.rs" use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ reverse_lookup::{ReverseLookup, ReverseLookupNew}, schema::reverse_lookup::dsl, PgPooledConn, StorageResult, }; impl ReverseLookupNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ReverseLookup> { generics::generic_insert(conn, self).await } pub async fn batch_insert( reverse_lookups: Vec<Self>, conn: &PgPooledConn, ) -> StorageResult<()> { generics::generic_insert::<_, _, ReverseLookup>(conn, reverse_lookups).await?; Ok(()) } } impl ReverseLookup { pub async fn find_by_lookup_id(lookup_id: &str, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::lookup_id.eq(lookup_id.to_owned()), ) .await } } <file_sep> pack="QBP-B" entity="reverse_lookup" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/storage_impl/src/reverse_lookup.rs" use diesel_models::reverse_lookup::ReverseLookup; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for ReverseLookup {} <file_sep> pack="QBP-B" entity="reverse_lookup" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2022-12-12-132936_reverse_lookup/up.sql" CREATE TABLE reverse_lookup ( lookup_id VARCHAR(255) NOT NULL PRIMARY KEY, sk_id VARCHAR(50) NOT NULL, pk_id VARCHAR(255) NOT NULL, source VARCHAR(30) NOT NULL ); CREATE INDEX lookup_id_index ON reverse_lookup (lookup_id); <file_sep> pack="QBP-B" entity="reverse_lookup" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2022-12-12-132936_reverse_lookup/down.sql" DROP TABLE IF EXISTS reverse_lookup; <file_sep> pack="QBP-B" entity="reverse_lookup" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-10-13-090450_add_updated_by_for_tables/up.sql" ALTER TABLE payment_intent ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE payment_attempt ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE refund ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE connector_response ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE reverse_lookup ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; ALTER TABLE address ADD column updated_by VARCHAR(32) NOT NULL DEFAULT 'postgres_only'; <file_sep> pack="QBP-B" entity="reverse_lookup" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_reverse_lookup.rs" // schema snippet for entity=reverse_lookup repo=hyperswitch // table: reverse_lookup columns: [] entities: [reverse_lookup] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/role.rs<|crate|> router<|op|> select entity=role repo=hyperswitch tables=role joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="role" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/role.rs" use common_utils::id_type; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::roles}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = roles, primary_key(role_id), check_for_backend(diesel::pg::Pg))] pub struct Role { pub role_name: String, pub role_id: String, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, pub scope: enums::RoleScope, pub created_at: PrimitiveDateTime, pub created_by: String, pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, pub profile_id: Option<id_type::ProfileId>, pub tenant_id: id_type::TenantId, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = roles)] pub struct RoleNew { pub role_name: String, pub role_id: String, pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, pub scope: enums::RoleScope, pub created_at: PrimitiveDateTime, pub created_by: String, pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, pub profile_id: Option<id_type::ProfileId>, pub tenant_id: id_type::TenantId, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = roles)] pub struct RoleUpdateInternal { groups: Option<Vec<enums::PermissionGroup>>, role_name: Option<String>, last_modified_by: String, last_modified_at: PrimitiveDateTime, } pub enum RoleUpdate { UpdateDetails { groups: Option<Vec<enums::PermissionGroup>>, role_name: Option<String>, last_modified_at: PrimitiveDateTime, last_modified_by: String, }, } impl From<RoleUpdate> for RoleUpdateInternal { fn from(value: RoleUpdate) -> Self { match value { RoleUpdate::UpdateDetails { groups, role_name, last_modified_by, last_modified_at, } => Self { groups, role_name, last_modified_at, last_modified_by, }, } } } #[derive(Clone, Debug)] pub enum ListRolesByEntityPayload { Profile(id_type::MerchantId, id_type::ProfileId), Merchant(id_type::MerchantId), Organization, } <file_sep> pack="QBP-A" entity="role" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/role.rs" use async_bb8_diesel::AsyncRunQueryDsl; use common_enums::EntityType; use common_utils::id_type; use diesel::{ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; use strum::IntoEnumIterator; use crate::{ enums::RoleScope, errors, query::generics, role::*, schema::roles::dsl, PgPooledConn, StorageResult, }; impl RoleNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Role> { generics::generic_insert(conn, self).await } } impl Role { fn get_entity_list( current_entity: EntityType, is_lineage_data_required: bool, ) -> Vec<EntityType> { is_lineage_data_required .then(|| { EntityType::iter() .filter(|variant| *variant <= current_entity) .collect() }) .unwrap_or(vec![current_entity]) } pub async fn find_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id.eq(role_id.to_owned()), ) .await } pub async fn find_by_role_id_in_lineage( conn: &PgPooledConn, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id .eq(role_id.to_owned()) .and(dsl::tenant_id.eq(tenant_id.to_owned())) .and(dsl::org_id.eq(org_id.to_owned())) .and( dsl::scope .eq(RoleScope::Organization) .or(dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::scope.eq(RoleScope::Merchant))) .or(dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::scope.eq(RoleScope::Profile))), ), ) .await } pub async fn find_by_role_id_org_id_tenant_id( conn: &PgPooledConn, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id .eq(role_id.to_owned()) .and(dsl::tenant_id.eq(tenant_id.to_owned())) .and(dsl::org_id.eq(org_id.to_owned())), ) .await } pub async fn update_by_role_id( conn: &PgPooledConn, role_id: &str, role_update: RoleUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::role_id.eq(role_id.to_owned()), RoleUpdateInternal::from(role_update), ) .await } pub async fn delete_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id.eq(role_id.to_owned()), ) .await } //TODO: Remove once generic_list_roles_by_entity_type is stable pub async fn generic_roles_list_for_org( conn: &PgPooledConn, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .filter(dsl::tenant_id.eq(tenant_id).and(dsl::org_id.eq(org_id))) .into_boxed(); if let Some(merchant_id) = merchant_id { query = query.filter( (dsl::merchant_id .eq(merchant_id) .and(dsl::scope.eq(RoleScope::Merchant))) .or(dsl::scope.eq(RoleScope::Organization)), ); } if let Some(entity_type) = entity_type { query = query.filter(dsl::entity_type.eq(entity_type)) } if let Some(limit) = limit { query = query.limit(limit.into()); } router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => { Err(report!(err)).change_context(errors::DatabaseError::NotFound) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } } pub async fn generic_list_roles_by_entity_type( conn: &PgPooledConn, payload: ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .into_boxed() .filter(dsl::tenant_id.eq(tenant_id)) .filter(dsl::org_id.eq(org_id)); match payload { ListRolesByEntityPayload::Organization => { let entity_in_vec = Self::get_entity_list(EntityType::Organization, is_lineage_data_required); query = query.filter(dsl::entity_type.eq_any(entity_in_vec)) } ListRolesByEntityPayload::Merchant(merchant_id) => { let entity_in_vec = Self::get_entity_list(EntityType::Merchant, is_lineage_data_required); query = query .filter( dsl::scope .eq(RoleScope::Organization) .or(dsl::merchant_id.eq(merchant_id)), ) .filter(dsl::entity_type.eq_any(entity_in_vec)) } ListRolesByEntityPayload::Profile(merchant_id, profile_id) => { let entity_in_vec = Self::get_entity_list(EntityType::Profile, is_lineage_data_required); query = query .filter( dsl::scope .eq(RoleScope::Organization) .or(dsl::scope .eq(RoleScope::Merchant) .and(dsl::merchant_id.eq(merchant_id.clone()))) .or(dsl::profile_id.eq(profile_id)), ) .filter(dsl::entity_type.eq_any(entity_in_vec)) } }; router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => Err(report!(err)).change_context(errors::DatabaseError::Others), } } } <file_sep> pack="QBP-A" entity="role" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/role.rs" use common_utils::id_type; use diesel_models::{ enums::{EntityType, RoleScope}, role as storage, }; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait RoleInterface { async fn insert_role( &self, role: storage::RoleNew, ) -> CustomResult<storage::Role, errors::StorageError>; async fn find_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError>; async fn find_role_by_role_id_in_lineage( &self, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError>; async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError>; async fn update_role_by_role_id( &self, role_id: &str, role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError>; async fn delete_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError>; //TODO: Remove once generic_list_roles_by_entity_type is stable async fn list_roles_for_org_by_parameters( &self, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError>; async fn generic_list_roles_by_entity_type( &self, payload: storage::ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError>; } #[async_trait::async_trait] impl RoleInterface for Store { #[instrument(skip_all)] async fn insert_role( &self, role: storage::RoleNew, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; role.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id(&conn, role_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_role_by_role_id_in_lineage( &self, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id_in_lineage( &conn, role_id, merchant_id, org_id, profile_id, tenant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id_org_id_tenant_id(&conn, role_id, org_id, tenant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_role_by_role_id( &self, role_id: &str, role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Role::update_by_role_id(&conn, role_id, role_update) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Role::delete_by_role_id(&conn, role_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } //TODO: Remove once generic_list_roles_by_entity_type is stable #[instrument(skip_all)] async fn list_roles_for_org_by_parameters( &self, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::generic_roles_list_for_org( &conn, tenant_id.to_owned(), org_id.to_owned(), merchant_id.cloned(), entity_type, limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn generic_list_roles_by_entity_type( &self, payload: storage::ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::generic_list_roles_by_entity_type( &conn, payload, is_lineage_data_required, tenant_id, org_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl RoleInterface for MockDb { async fn insert_role( &self, role: storage::RoleNew, ) -> CustomResult<storage::Role, errors::StorageError> { let mut roles = self.roles.lock().await; if roles .iter() .any(|role_inner| role_inner.role_id == role.role_id) { Err(errors::StorageError::DuplicateValue { entity: "role_id", key: None, })? } let role = storage::Role { role_name: role.role_name, role_id: role.role_id, merchant_id: role.merchant_id, org_id: role.org_id, groups: role.groups, scope: role.scope, entity_type: role.entity_type, created_by: role.created_by, created_at: role.created_at, last_modified_at: role.last_modified_at, last_modified_by: role.last_modified_by, profile_id: role.profile_id, tenant_id: role.tenant_id, }; roles.push(role.clone()); Ok(role) } async fn find_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let roles = self.roles.lock().await; roles .iter() .find(|role| role.role_id == role_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No role available role_id = {role_id}" )) .into(), ) } async fn find_role_by_role_id_in_lineage( &self, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let roles = self.roles.lock().await; roles .iter() .find(|role| { role.role_id == role_id && (role.tenant_id == *tenant_id) && role.org_id == *org_id && ((role.scope == RoleScope::Organization) || (role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant) || (role .profile_id .as_ref() .is_some_and(|profile_id_from_role| { profile_id_from_role == profile_id && role.scope == RoleScope::Profile }))) }) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No role available in merchant scope for role_id = {role_id}, \ merchant_id = {merchant_id:?} and org_id = {org_id:?}" )) .into(), ) } async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let roles = self.roles.lock().await; roles .iter() .find(|role| { role.role_id == role_id && role.org_id == *org_id && role.tenant_id == *tenant_id }) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No role available in org scope for role_id = {role_id} and org_id = {org_id:?}" )) .into(), ) } async fn update_role_by_role_id( &self, role_id: &str, role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError> { let mut roles = self.roles.lock().await; roles .iter_mut() .find(|role| role.role_id == role_id) .map(|role| { *role = match role_update { storage::RoleUpdate::UpdateDetails { groups, role_name, last_modified_at, last_modified_by, } => storage::Role { groups: groups.unwrap_or(role.groups.to_owned()), role_name: role_name.unwrap_or(role.role_name.to_owned()), last_modified_by, last_modified_at, ..role.to_owned() }, }; role.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No role available for role_id = {role_id}" )) .into(), ) } async fn delete_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let mut roles = self.roles.lock().await; let role_index = roles .iter() .position(|role| role.role_id == role_id) .ok_or(errors::StorageError::ValueNotFound(format!( "No role available for role_id = {role_id}" )))?; Ok(roles.remove(role_index)) } //TODO: Remove once generic_list_roles_by_entity_type is stable #[instrument(skip_all)] async fn list_roles_for_org_by_parameters( &self, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let roles = self.roles.lock().await; let limit_usize = limit.unwrap_or(u32::MAX).try_into().unwrap_or(usize::MAX); let roles_list: Vec<_> = roles .iter() .filter(|role| { let matches_merchant = match merchant_id { Some(merchant_id) => role.merchant_id == *merchant_id, None => true, }; matches_merchant && role.org_id == *org_id && role.tenant_id == *tenant_id && Some(role.entity_type) == entity_type }) .take(limit_usize) .cloned() .collect(); Ok(roles_list) } #[instrument(skip_all)] async fn generic_list_roles_by_entity_type( &self, payload: storage::ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let roles = self.roles.lock().await; let roles_list: Vec<_> = roles .iter() .filter(|role| match &payload { storage::ListRolesByEntityPayload::Organization => { let entity_in_vec = if is_lineage_data_required { vec![ EntityType::Organization, EntityType::Merchant, EntityType::Profile, ] } else { vec![EntityType::Organization] }; role.tenant_id == tenant_id && role.org_id == org_id && entity_in_vec.contains(&role.entity_type) } storage::ListRolesByEntityPayload::Merchant(merchant_id) => { let entity_in_vec = if is_lineage_data_required { vec![EntityType::Merchant, EntityType::Profile] } else { vec![EntityType::Merchant] }; role.tenant_id == tenant_id && role.org_id == org_id && (role.scope == RoleScope::Organization || role.merchant_id == *merchant_id) && entity_in_vec.contains(&role.entity_type) } storage::ListRolesByEntityPayload::Profile(merchant_id, profile_id) => { let entity_in_vec = [EntityType::Profile]; let matches_merchant = role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant; let matches_profile = role.profile_id .as_ref() .is_some_and(|profile_id_from_role| { profile_id_from_role == profile_id && role.scope == RoleScope::Profile }); role.tenant_id == tenant_id && role.org_id == org_id && (role.scope == RoleScope::Organization || matches_merchant || matches_profile) && entity_in_vec.contains(&role.entity_type) } }) .cloned() .collect(); Ok(roles_list) } } <file_sep> pack="QBP-A" entity="role" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-28-121104_add_column_tenant_id_to_roles/up.sql" -- Your SQL goes here ALTER TABLE roles ADD COLUMN IF NOT EXISTS tenant_id VARCHAR(64) NOT NULL DEFAULT 'public'; <file_sep> pack="QBP-A" entity="role" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-28-121104_add_column_tenant_id_to_roles/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE roles DROP COLUMN IF EXISTS tenant_id; <file_sep> pack="QBP-A" entity="role" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/down.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR(64)` column for tables that had it removed. -- It must be ensured that the deployed version of the application includes the `id` column in any of its queries. -- Re-create the id column as this was used as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account ADD COLUMN id VARCHAR(64); ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account ADD COLUMN id VARCHAR(64); ------------------------ Customers ----------------------- ALTER TABLE customers ADD COLUMN id VARCHAR(64); ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent ADD COLUMN id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt ADD COLUMN id VARCHAR(64); ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods ADD COLUMN id VARCHAR(64); ------------------------ Address ----------------------- ALTER TABLE address ADD COLUMN id VARCHAR(64); ------------------------ Dispute ----------------------- ALTER TABLE dispute ADD COLUMN id VARCHAR(64); ------------------------ Mandate ----------------------- ALTER TABLE mandate ADD COLUMN id VARCHAR(64); ------------------------ Refund ----------------------- ALTER TABLE refund ADD COLUMN id VARCHAR(64); ------------------------ BlockList ----------------------- ALTER TABLE blocklist ADD COLUMN id VARCHAR(64); ------------------------ Roles ----------------------- ALTER TABLE roles ADD COLUMN id VARCHAR(64); ------------------------ Users ----------------------- ALTER TABLE users ADD COLUMN id VARCHAR(64); <file_sep> pack="QBP-A" entity="role" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_role.rs" // schema snippet for entity=role repo=hyperswitch // table: roles columns: [] entities: [role] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/routing_algorithm.rs<|crate|> router<|op|> select entity=routing_algorithm repo=hyperswitch tables=routing_algorithm joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="routing_algorithm" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/routing_algorithm.rs" use common_utils::id_type; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::{enums, schema::routing_algorithm}; #[derive(Clone, Debug, Identifiable, Insertable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = routing_algorithm, primary_key(algorithm_id), check_for_backend(diesel::pg::Pg))] pub struct RoutingAlgorithm { pub algorithm_id: id_type::RoutingId, pub profile_id: id_type::ProfileId, pub merchant_id: id_type::MerchantId, pub name: String, pub description: Option<String>, pub kind: enums::RoutingAlgorithmKind, pub algorithm_data: serde_json::Value, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub algorithm_for: enums::TransactionType, } pub struct RoutingAlgorithmMetadata { pub algorithm_id: id_type::RoutingId, pub name: String, pub description: Option<String>, pub kind: enums::RoutingAlgorithmKind, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub algorithm_for: enums::TransactionType, } pub struct RoutingProfileMetadata { pub profile_id: id_type::ProfileId, pub algorithm_id: id_type::RoutingId, pub name: String, pub description: Option<String>, pub kind: enums::RoutingAlgorithmKind, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub algorithm_for: enums::TransactionType, } <file_sep> pack="QBP-A" entity="routing_algorithm" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/routing_algorithm.rs" use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl}; use error_stack::{report, ResultExt}; use time::PrimitiveDateTime; use crate::{ enums, errors::DatabaseError, query::generics, routing_algorithm::{RoutingAlgorithm, RoutingProfileMetadata}, schema::routing_algorithm::dsl, PgPooledConn, StorageResult, }; impl RoutingAlgorithm { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { generics::generic_insert(conn, self).await } pub async fn find_by_algorithm_id_merchant_id( conn: &PgPooledConn, algorithm_id: &common_utils::id_type::RoutingId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::algorithm_id .eq(algorithm_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .await } pub async fn find_by_algorithm_id_profile_id( conn: &PgPooledConn, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::algorithm_id .eq(algorithm_id.to_owned()) .and(dsl::profile_id.eq(profile_id.to_owned())), ) .await } pub async fn find_metadata_by_algorithm_id_profile_id( conn: &PgPooledConn, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<RoutingProfileMetadata> { Self::table() .select(( dsl::profile_id, dsl::algorithm_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter( dsl::algorithm_id .eq(algorithm_id.to_owned()) .and(dsl::profile_id.eq(profile_id.to_owned())), ) .limit(1) .load_async::<( common_utils::id_type::ProfileId, common_utils::id_type::RoutingId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .next() .ok_or(report!(DatabaseError::NotFound)) .map( |( profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, } }, ) } pub async fn list_metadata_by_profile_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, limit: i64, offset: i64, ) -> StorageResult<Vec<RoutingProfileMetadata>> { Ok(Self::table() .select(( dsl::algorithm_id, dsl::profile_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter(dsl::profile_id.eq(profile_id.to_owned())) .limit(limit) .offset(offset) .load_async::<( common_utils::id_type::RoutingId, common_utils::id_type::ProfileId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .map( |( algorithm_id, profile_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, profile_id, } }, ) .collect()) } pub async fn list_metadata_by_merchant_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, limit: i64, offset: i64, ) -> StorageResult<Vec<RoutingProfileMetadata>> { Ok(Self::table() .select(( dsl::profile_id, dsl::algorithm_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .limit(limit) .offset(offset) .order(dsl::modified_at.desc()) .load_async::<( common_utils::id_type::ProfileId, common_utils::id_type::RoutingId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .map( |( profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, } }, ) .collect()) } pub async fn list_metadata_by_merchant_id_transaction_type( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, transaction_type: &enums::TransactionType, limit: i64, offset: i64, ) -> StorageResult<Vec<RoutingProfileMetadata>> { Ok(Self::table() .select(( dsl::profile_id, dsl::algorithm_id, dsl::name, dsl::description, dsl::kind, dsl::created_at, dsl::modified_at, dsl::algorithm_for, )) .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::algorithm_for.eq(transaction_type.to_owned())) .limit(limit) .offset(offset) .order(dsl::modified_at.desc()) .load_async::<( common_utils::id_type::ProfileId, common_utils::id_type::RoutingId, String, Option<String>, enums::RoutingAlgorithmKind, PrimitiveDateTime, PrimitiveDateTime, enums::TransactionType, )>(conn) .await .change_context(DatabaseError::Others)? .into_iter() .map( |( profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, )| { RoutingProfileMetadata { profile_id, algorithm_id, name, description, kind, created_at, modified_at, algorithm_for, } }, ) .collect()) } } <file_sep> pack="QBP-A" entity="routing_algorithm" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/routing_algorithm.rs" use diesel_models::routing_algorithm as routing_storage; use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::mock_db::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; type StorageResult<T> = CustomResult<T, errors::StorageError>; #[async_trait::async_trait] pub trait RoutingAlgorithmInterface { async fn insert_routing_algorithm( &self, routing_algorithm: routing_storage::RoutingAlgorithm, ) -> StorageResult<routing_storage::RoutingAlgorithm>; async fn find_routing_algorithm_by_profile_id_algorithm_id( &self, profile_id: &common_utils::id_type::ProfileId, algorithm_id: &common_utils::id_type::RoutingId, ) -> StorageResult<routing_storage::RoutingAlgorithm>; async fn find_routing_algorithm_by_algorithm_id_merchant_id( &self, algorithm_id: &common_utils::id_type::RoutingId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<routing_storage::RoutingAlgorithm>; async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( &self, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<routing_storage::RoutingProfileMetadata>; async fn list_routing_algorithm_metadata_by_profile_id( &self, profile_id: &common_utils::id_type::ProfileId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>; async fn list_routing_algorithm_metadata_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>; async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type( &self, merchant_id: &common_utils::id_type::MerchantId, transaction_type: &common_enums::TransactionType, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>; } #[async_trait::async_trait] impl RoutingAlgorithmInterface for Store { #[instrument(skip_all)] async fn insert_routing_algorithm( &self, routing_algorithm: routing_storage::RoutingAlgorithm, ) -> StorageResult<routing_storage::RoutingAlgorithm> { let conn = connection::pg_connection_write(self).await?; routing_algorithm .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_routing_algorithm_by_profile_id_algorithm_id( &self, profile_id: &common_utils::id_type::ProfileId, algorithm_id: &common_utils::id_type::RoutingId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::find_by_algorithm_id_profile_id( &conn, algorithm_id, profile_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_routing_algorithm_by_algorithm_id_merchant_id( &self, algorithm_id: &common_utils::id_type::RoutingId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::find_by_algorithm_id_merchant_id( &conn, algorithm_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( &self, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<routing_storage::RoutingProfileMetadata> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::find_metadata_by_algorithm_id_profile_id( &conn, algorithm_id, profile_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_routing_algorithm_metadata_by_profile_id( &self, profile_id: &common_utils::id_type::ProfileId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::list_metadata_by_profile_id( &conn, profile_id, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_routing_algorithm_metadata_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::list_metadata_by_merchant_id( &conn, merchant_id, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type( &self, merchant_id: &common_utils::id_type::MerchantId, transaction_type: &common_enums::TransactionType, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::list_metadata_by_merchant_id_transaction_type( &conn, merchant_id, transaction_type, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl RoutingAlgorithmInterface for MockDb { async fn insert_routing_algorithm( &self, _routing_algorithm: routing_storage::RoutingAlgorithm, ) -> StorageResult<routing_storage::RoutingAlgorithm> { Err(errors::StorageError::MockDbError)? } async fn find_routing_algorithm_by_profile_id_algorithm_id( &self, _profile_id: &common_utils::id_type::ProfileId, _algorithm_id: &common_utils::id_type::RoutingId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { Err(errors::StorageError::MockDbError)? } async fn find_routing_algorithm_by_algorithm_id_merchant_id( &self, _algorithm_id: &common_utils::id_type::RoutingId, _merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { Err(errors::StorageError::MockDbError)? } async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( &self, _algorithm_id: &common_utils::id_type::RoutingId, _profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<routing_storage::RoutingProfileMetadata> { Err(errors::StorageError::MockDbError)? } async fn list_routing_algorithm_metadata_by_profile_id( &self, _profile_id: &common_utils::id_type::ProfileId, _limit: i64, _offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { Err(errors::StorageError::MockDbError)? } async fn list_routing_algorithm_metadata_by_merchant_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _limit: i64, _offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { Err(errors::StorageError::MockDbError)? } async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type( &self, _merchant_id: &common_utils::id_type::MerchantId, _transaction_type: &common_enums::TransactionType, _limit: i64, _offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { Err(errors::StorageError::MockDbError)? } } <file_sep> pack="QBP-A" entity="routing_algorithm" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-10-19-101558_create_routing_algorithm_table/up.sql" -- Your SQL goes here CREATE TYPE "RoutingAlgorithmKind" AS ENUM ('single', 'priority', 'volume_split', 'advanced'); CREATE TABLE routing_algorithm ( algorithm_id VARCHAR(64) PRIMARY KEY, profile_id VARCHAR(64) NOT NULL, merchant_id VARCHAR(64) NOT NULL, name VARCHAR(64) NOT NULL, description VARCHAR(256), kind "RoutingAlgorithmKind" NOT NULL, algorithm_data JSONB NOT NULL, created_at TIMESTAMP NOT NULL, modified_at TIMESTAMP NOT NULL ); CREATE INDEX routing_algorithm_profile_id_modified_at ON routing_algorithm (profile_id, modified_at DESC); CREATE INDEX routing_algorithm_merchant_id_modified_at ON routing_algorithm (merchant_id, modified_at DESC); <file_sep> pack="QBP-A" entity="routing_algorithm" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2023-10-19-101558_create_routing_algorithm_table/down.sql" -- This file should undo anything in `up.sql` DROP TABLE routing_algorithm; DROP TYPE "RoutingAlgorithmKind"; <file_sep> pack="QBP-A" entity="routing_algorithm" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-01-29-100008_routing_info_for_payout_attempts/up.sql" -- Your SQL goes here ALTER TABLE payout_attempt ALTER COLUMN connector TYPE JSONB USING jsonb_build_object ( 'routed_through', connector, 'algorithm', NULL ); ALTER TABLE payout_attempt ADD COLUMN routing_info JSONB; UPDATE payout_attempt SET routing_info = connector -> 'algorithm' WHERE connector ->> 'algorithm' IS NOT NULL; ALTER TABLE payout_attempt ALTER COLUMN connector TYPE VARCHAR(64) USING connector ->> 'routed_through'; ALTER TABLE payout_attempt ALTER COLUMN connector DROP NOT NULL; CREATE type "TransactionType" as ENUM('payment', 'payout'); ALTER TABLE routing_algorithm ADD COLUMN algorithm_for "TransactionType" DEFAULT 'payment' NOT NULL; ALTER TABLE routing_algorithm ALTER COLUMN algorithm_for DROP DEFAULT; <file_sep> pack="QBP-A" entity="routing_algorithm" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_routing_algorithm.rs" // schema snippet for entity=routing_algorithm repo=hyperswitch // table: routing_algorithm columns: [] entities: [routing_algorithm] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user/sample_data.rs<|crate|> router<|op|> select entity=sample_data repo=hyperswitch tables=sample_data joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="sample_data" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/user/sample_data.rs" use common_enums::{ AttemptStatus, AuthenticationType, CaptureMethod, Currency, PaymentExperience, PaymentMethod, PaymentMethodType, }; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::types::{ConnectorTransactionId, MinorUnit}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::schema::payment_attempt; #[cfg(feature = "v2")] use crate::schema_v2::payment_attempt; use crate::{ enums::{MandateDataType, MandateDetails}, ConnectorMandateReferenceId, 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<String>, 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>, } #[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, } } } <file_sep> pack="QBP-A" entity="sample_data" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/user/sample_data.rs" use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{associations::HasTable, debug_query, ExpressionMethods, TextExpressionMethods}; use error_stack::ResultExt; use router_env::logger; #[cfg(feature = "v1")] use crate::schema::{ payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl, refund::dsl as refund_dsl, }; #[cfg(feature = "v2")] use crate::schema_v2::{ payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl, refund::dsl as refund_dsl, }; use crate::{ errors, schema::dispute::dsl as dispute_dsl, user, Dispute, DisputeNew, PaymentAttempt, PaymentIntent, PaymentIntentNew, PgPooledConn, Refund, RefundNew, StorageResult, }; #[cfg(feature = "v1")] pub async fn insert_payment_intents( conn: &PgPooledConn, batch: Vec<PaymentIntentNew>, ) -> StorageResult<Vec<PaymentIntent>> { let query = diesel::insert_into(<PaymentIntent>::table()).values(batch); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while inserting payment intents") } #[cfg(feature = "v1")] pub async fn insert_payment_attempts( conn: &PgPooledConn, batch: Vec<user::sample_data::PaymentAttemptBatchNew>, ) -> StorageResult<Vec<PaymentAttempt>> { let query = diesel::insert_into(<PaymentAttempt>::table()).values(batch); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while inserting payment attempts") } pub async fn insert_refunds( conn: &PgPooledConn, batch: Vec<RefundNew>, ) -> StorageResult<Vec<Refund>> { let query = diesel::insert_into(<Refund>::table()).values(batch); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while inserting refunds") } pub async fn insert_disputes( conn: &PgPooledConn, batch: Vec<DisputeNew>, ) -> StorageResult<Vec<Dispute>> { let query = diesel::insert_into(<Dispute>::table()).values(batch); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while inserting disputes") } #[cfg(feature = "v1")] pub async fn delete_payment_intents( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<PaymentIntent>> { let query = diesel::delete(<PaymentIntent>::table()) .filter(payment_intent_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(payment_intent_dsl::payment_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting payment intents") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) } #[cfg(feature = "v2")] pub async fn delete_payment_intents( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<PaymentIntent>> { let query = diesel::delete(<PaymentIntent>::table()) .filter(payment_intent_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(payment_intent_dsl::merchant_reference_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting payment intents") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) } pub async fn delete_payment_attempts( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<PaymentAttempt>> { let query = diesel::delete(<PaymentAttempt>::table()) .filter(payment_attempt_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(payment_attempt_dsl::payment_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting payment attempts") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) } pub async fn delete_refunds( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<Refund>> { let query = diesel::delete(<Refund>::table()) .filter(refund_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(refund_dsl::payment_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting refunds") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) } pub async fn delete_disputes( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Vec<Dispute>> { let query = diesel::delete(<Dispute>::table()) .filter(dispute_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dispute_dsl::dispute_id.like("test_%")); logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting disputes") .and_then(|result| match result.len() { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(result) } 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) .attach_printable("No records deleted")), _ => Ok(result), }) } <file_sep> pack="QBP-A" entity="sample_data" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user/sample_data.rs" use common_utils::types::keymanager::KeyManagerState; #[cfg(feature = "v1")] use diesel_models::user::sample_data::PaymentAttemptBatchNew; use diesel_models::{ dispute::{Dispute, DisputeNew}, errors::DatabaseError, query::user::sample_data as sample_data_queries, refund::{Refund, RefundNew}, }; use error_stack::{Report, ResultExt}; use futures::{future::try_join_all, FutureExt}; use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, payments::{payment_attempt::PaymentAttempt, PaymentIntent}, }; use storage_impl::{errors::StorageError, DataModelExt}; use crate::{connection::pg_connection_write, core::errors::CustomResult, services::Store}; #[async_trait::async_trait] pub trait BatchSampleDataInterface { #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, state: &KeyManagerState, batch: Vec<PaymentIntent>, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, batch: Vec<PaymentAttemptBatchNew>, ) -> CustomResult<Vec<PaymentAttempt>, StorageError>; #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, batch: Vec<RefundNew>, ) -> CustomResult<Vec<Refund>, StorageError>; #[cfg(feature = "v1")] async fn insert_disputes_batch_for_sample_data( &self, batch: Vec<DisputeNew>, ) -> CustomResult<Vec<Dispute>, StorageError>; #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<PaymentAttempt>, StorageError>; #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Refund>, StorageError>; #[cfg(feature = "v1")] async fn delete_disputes_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Dispute>, StorageError>; } #[async_trait::async_trait] impl BatchSampleDataInterface for Store { #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, state: &KeyManagerState, batch: Vec<PaymentIntent>, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; let new_intents = try_join_all(batch.into_iter().map(|payment_intent| async { payment_intent .construct_new() .await .change_context(StorageError::EncryptionError) })) .await?; sample_data_queries::insert_payment_intents(&conn, new_intents) .await .map_err(diesel_error_to_data_error) .map(|v| { try_join_all(v.into_iter().map(|payment_intent| { PaymentIntent::convert_back( state, payment_intent, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })? .await } #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, batch: Vec<PaymentAttemptBatchNew>, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::insert_payment_attempts(&conn, batch) .await .map_err(diesel_error_to_data_error) .map(|res| { res.into_iter() .map(PaymentAttempt::from_storage_model) .collect() }) } #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, batch: Vec<RefundNew>, ) -> CustomResult<Vec<Refund>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::insert_refunds(&conn, batch) .await .map_err(diesel_error_to_data_error) } #[cfg(feature = "v1")] async fn insert_disputes_batch_for_sample_data( &self, batch: Vec<DisputeNew>, ) -> CustomResult<Vec<Dispute>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::insert_disputes(&conn, batch) .await .map_err(diesel_error_to_data_error) } #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_payment_intents(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) .map(|v| { try_join_all(v.into_iter().map(|payment_intent| { PaymentIntent::convert_back( state, payment_intent, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })? .await } #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_payment_attempts(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) .map(|res| { res.into_iter() .map(PaymentAttempt::from_storage_model) .collect() }) } #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Refund>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_refunds(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) } #[cfg(feature = "v1")] async fn delete_disputes_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Dispute>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_disputes(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) } } #[async_trait::async_trait] impl BatchSampleDataInterface for storage_impl::MockDb { #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, _state: &KeyManagerState, _batch: Vec<PaymentIntent>, _key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, _batch: Vec<PaymentAttemptBatchNew>, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, _batch: Vec<RefundNew>, ) -> CustomResult<Vec<Refund>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn insert_disputes_batch_for_sample_data( &self, _batch: Vec<DisputeNew>, ) -> CustomResult<Vec<Dispute>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, _state: &KeyManagerState, _merchant_id: &common_utils::id_type::MerchantId, _key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Refund>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_disputes_for_sample_data( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Dispute>, StorageError> { Err(StorageError::MockDbError)? } } // TODO: This error conversion is re-used from storage_impl and is not DRY when it should be // Ideally the impl's here should be defined in that crate avoiding this re-definition fn diesel_error_to_data_error(diesel_error: Report<DatabaseError>) -> Report<StorageError> { let new_err = match diesel_error.current_context() { DatabaseError::DatabaseConnectionError => StorageError::DatabaseConnectionError, DatabaseError::NotFound => StorageError::ValueNotFound("Value not found".to_string()), DatabaseError::UniqueViolation => StorageError::DuplicateValue { entity: "entity ", key: None, }, err => StorageError::DatabaseError(error_stack::report!(*err)), }; diesel_error.change_context(new_err) } <file_sep> pack="QBP-A" entity="sample_data" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-10-28-125949_add_dispute_currency_column_in_dispute_table/up.sql" -- Your SQL goes here ALTER TABLE dispute ADD COLUMN IF NOT EXISTS dispute_currency "Currency"; <file_sep> pack="QBP-A" entity="sample_data" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-10-28-125949_add_dispute_currency_column_in_dispute_table/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE dispute DROP COLUMN IF EXISTS dispute_currency; <file_sep> pack="QBP-A" entity="sample_data" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/down.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR(64)` column for tables that had it removed. -- It must be ensured that the deployed version of the application includes the `id` column in any of its queries. -- Re-create the id column as this was used as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account ADD COLUMN id VARCHAR(64); ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account ADD COLUMN id VARCHAR(64); ------------------------ Customers ----------------------- ALTER TABLE customers ADD COLUMN id VARCHAR(64); ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent ADD COLUMN id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt ADD COLUMN id VARCHAR(64); ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods ADD COLUMN id VARCHAR(64); ------------------------ Address ----------------------- ALTER TABLE address ADD COLUMN id VARCHAR(64); ------------------------ Dispute ----------------------- ALTER TABLE dispute ADD COLUMN id VARCHAR(64); ------------------------ Mandate ----------------------- ALTER TABLE mandate ADD COLUMN id VARCHAR(64); ------------------------ Refund ----------------------- ALTER TABLE refund ADD COLUMN id VARCHAR(64); ------------------------ BlockList ----------------------- ALTER TABLE blocklist ADD COLUMN id VARCHAR(64); ------------------------ Roles ----------------------- ALTER TABLE roles ADD COLUMN id VARCHAR(64); ------------------------ Users ----------------------- ALTER TABLE users ADD COLUMN id VARCHAR(64); <file_sep> pack="QBP-A" entity="sample_data" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_sample_data.rs" // schema snippet for entity=sample_data repo=hyperswitch // table: dispute columns: [] entities: [dispute] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user/theme.rs<|crate|> router<|op|> select entity=theme repo=hyperswitch tables=theme joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="theme" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/user/theme.rs" use common_enums::EntityType; use common_utils::{ date_time, id_type, types::theme::{EmailThemeConfig, ThemeLineage}, }; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::schema::themes; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = themes, primary_key(theme_id), check_for_backend(diesel::pg::Pg))] pub struct Theme { pub theme_id: String, pub tenant_id: id_type::TenantId, pub org_id: Option<id_type::OrganizationId>, pub merchant_id: Option<id_type::MerchantId>, pub profile_id: Option<id_type::ProfileId>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub entity_type: EntityType, pub theme_name: String, pub email_primary_color: String, pub email_foreground_color: String, pub email_background_color: String, pub email_entity_name: String, pub email_entity_logo_url: String, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = themes)] pub struct ThemeNew { pub theme_id: String, pub tenant_id: id_type::TenantId, pub org_id: Option<id_type::OrganizationId>, pub merchant_id: Option<id_type::MerchantId>, pub profile_id: Option<id_type::ProfileId>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub entity_type: EntityType, pub theme_name: String, pub email_primary_color: String, pub email_foreground_color: String, pub email_background_color: String, pub email_entity_name: String, pub email_entity_logo_url: String, } impl ThemeNew { pub fn new( theme_id: String, theme_name: String, lineage: ThemeLineage, email_config: EmailThemeConfig, ) -> Self { let now = date_time::now(); Self { theme_id, theme_name, tenant_id: lineage.tenant_id().to_owned(), org_id: lineage.org_id().cloned(), merchant_id: lineage.merchant_id().cloned(), profile_id: lineage.profile_id().cloned(), entity_type: lineage.entity_type(), created_at: now, last_modified_at: now, email_primary_color: email_config.primary_color, email_foreground_color: email_config.foreground_color, email_background_color: email_config.background_color, email_entity_name: email_config.entity_name, email_entity_logo_url: email_config.entity_logo_url, } } } impl Theme { pub fn email_config(&self) -> EmailThemeConfig { EmailThemeConfig { primary_color: self.email_primary_color.clone(), foreground_color: self.email_foreground_color.clone(), background_color: self.email_background_color.clone(), entity_name: self.email_entity_name.clone(), entity_logo_url: self.email_entity_logo_url.clone(), } } } <file_sep> pack="QBP-A" entity="theme" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/user/theme.rs" use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::types::theme::ThemeLineage; use diesel::{ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError, sql_types::{Bool, Nullable}, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; use router_env::logger; use crate::{ errors::DatabaseError, query::generics::{ self, db_metrics::{track_database_call, DatabaseOperation}, }, schema::themes::dsl, user::theme::{Theme, ThemeNew}, PgPooledConn, StorageResult, }; impl ThemeNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Theme> { generics::generic_insert(conn, self).await } } impl Theme { fn lineage_filter( lineage: ThemeLineage, ) -> Box< dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>> + 'static, > { match lineage { ThemeLineage::Tenant { tenant_id } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.is_null()) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()) .nullable(), ), ThemeLineage::Organization { tenant_id, org_id } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()), ), ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.is_null()), ), ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => Box::new( 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_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::theme_id.eq(theme_id), ) .await } pub async fn find_most_specific_theme_in_lineage( conn: &PgPooledConn, lineage: ThemeLineage, ) -> StorageResult<Self> { let query = <Self as HasTable>::table().into_boxed(); let query = lineage .get_same_and_higher_lineages() .into_iter() .fold(query, |mut query, lineage| { query = query.or_filter(Self::lineage_filter(lineage)); query }); logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); let data: Vec<Self> = match track_database_call::<Self, _, _>( query.get_results_async(conn), DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => Err(report!(err)).change_context(DatabaseError::NotFound), _ => Err(report!(err)).change_context(DatabaseError::Others), }, }?; data.into_iter() .min_by_key(|theme| theme.entity_type) .ok_or(report!(DatabaseError::NotFound)) } pub async fn find_by_lineage( conn: &PgPooledConn, lineage: ThemeLineage, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, Self::lineage_filter(lineage), ) .await } pub async fn delete_by_theme_id_and_lineage( conn: &PgPooledConn, theme_id: String, lineage: ThemeLineage, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::theme_id .eq(theme_id) .and(Self::lineage_filter(lineage)), ) .await } } <file_sep> pack="QBP-A" entity="theme" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user/theme.rs" use common_utils::types::theme::ThemeLineage; use diesel_models::user::theme as storage; use error_stack::report; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait ThemeInterface { async fn insert_theme( &self, theme: storage::ThemeNew, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn delete_theme_by_lineage_and_theme_id( &self, theme_id: String, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError>; } #[async_trait::async_trait] impl ThemeInterface for Store { async fn insert_theme( &self, theme: storage::ThemeNew, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; theme .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Theme::find_by_theme_id(&conn, theme_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Theme::find_most_specific_theme_in_lineage(&conn, lineage) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Theme::find_by_lineage(&conn, lineage) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn delete_theme_by_lineage_and_theme_id( &self, theme_id: String, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Theme::delete_by_theme_id_and_lineage(&conn, theme_id, lineage) .await .map_err(|error| report!(errors::StorageError::from(error))) } } fn check_theme_with_lineage(theme: &storage::Theme, lineage: &ThemeLineage) -> bool { match lineage { ThemeLineage::Tenant { tenant_id } => { &theme.tenant_id == tenant_id && theme.org_id.is_none() && theme.merchant_id.is_none() && theme.profile_id.is_none() } ThemeLineage::Organization { tenant_id, org_id } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme.merchant_id.is_none() && theme.profile_id.is_none() } ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme .merchant_id .as_ref() .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) && theme.profile_id.is_none() } ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme .merchant_id .as_ref() .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) && theme .profile_id .as_ref() .is_some_and(|profile_id_inner| profile_id_inner == profile_id) } } } #[async_trait::async_trait] impl ThemeInterface for MockDb { async fn insert_theme( &self, new_theme: storage::ThemeNew, ) -> CustomResult<storage::Theme, errors::StorageError> { let mut themes = self.themes.lock().await; for theme in themes.iter() { if new_theme.theme_id == theme.theme_id { return Err(errors::StorageError::DuplicateValue { entity: "theme_id", key: None, } .into()); } if new_theme.tenant_id == theme.tenant_id && new_theme.org_id == theme.org_id && new_theme.merchant_id == theme.merchant_id && new_theme.profile_id == theme.profile_id { return Err(errors::StorageError::DuplicateValue { entity: "lineage", key: None, } .into()); } } let theme = storage::Theme { theme_id: new_theme.theme_id, tenant_id: new_theme.tenant_id, org_id: new_theme.org_id, merchant_id: new_theme.merchant_id, profile_id: new_theme.profile_id, created_at: new_theme.created_at, last_modified_at: new_theme.last_modified_at, entity_type: new_theme.entity_type, theme_name: new_theme.theme_name, email_primary_color: new_theme.email_primary_color, email_foreground_color: new_theme.email_foreground_color, email_background_color: new_theme.email_background_color, email_entity_name: new_theme.email_entity_name, email_entity_logo_url: new_theme.email_entity_logo_url, }; themes.push(theme.clone()); Ok(theme) } async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError> { let themes = self.themes.lock().await; themes .iter() .find(|theme| theme.theme_id == theme_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "Theme with id {} not found", theme_id )) .into(), ) } async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let themes = self.themes.lock().await; let lineages = lineage.get_same_and_higher_lineages(); themes .iter() .filter(|theme| { lineages .iter() .any(|lineage| check_theme_with_lineage(theme, lineage)) }) .min_by_key(|theme| theme.entity_type) .ok_or( errors::StorageError::ValueNotFound("No theme found in lineage".to_string()).into(), ) .cloned() } async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let themes = self.themes.lock().await; themes .iter() .find(|theme| check_theme_with_lineage(theme, &lineage)) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "Theme with lineage {:?} not found", lineage )) .into(), ) } async fn delete_theme_by_lineage_and_theme_id( &self, theme_id: String, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let mut themes = self.themes.lock().await; let index = themes .iter() .position(|theme| { theme.theme_id == theme_id && check_theme_with_lineage(theme, &lineage) }) .ok_or(errors::StorageError::ValueNotFound(format!( "Theme with id {} and lineage {:?} not found", theme_id, lineage )))?; let theme = themes.remove(index); Ok(theme) } } <file_sep> pack="QBP-A" entity="theme" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/up.sql" -- Your SQL goes here ALTER TABLE themes ADD COLUMN IF NOT EXISTS entity_type VARCHAR(64) NOT NULL; ALTER TABLE themes ADD COLUMN IF NOT EXISTS theme_name VARCHAR(64) NOT NULL; <file_sep> pack="QBP-A" entity="theme" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-05-131123_add-email-theme-data-in-themes/up.sql" -- Your SQL goes here ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_primary_color VARCHAR(64) NOT NULL DEFAULT '#006DF9'; ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_foreground_color VARCHAR(64) NOT NULL DEFAULT '#000000'; ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_background_color VARCHAR(64) NOT NULL DEFAULT '#FFFFFF'; ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_entity_name VARCHAR(64) NOT NULL DEFAULT 'Hyperswitch'; ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_entity_logo_url TEXT NOT NULL DEFAULT 'https://app.hyperswitch.io/email-assets/HyperswitchLogo.png'; <file_sep> pack="QBP-A" entity="theme" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-05-131123_add-email-theme-data-in-themes/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE themes DROP COLUMN IF EXISTS email_primary_color; ALTER TABLE themes DROP COLUMN IF EXISTS email_foreground_color; ALTER TABLE themes DROP COLUMN IF EXISTS email_background_color; ALTER TABLE themes DROP COLUMN IF EXISTS email_entity_name; ALTER TABLE themes DROP COLUMN IF EXISTS email_entity_logo_url; <file_sep> pack="QBP-A" entity="theme" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_theme.rs" // schema snippet for entity=theme repo=hyperswitch // table: themes columns: [] entities: [theme] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user.rs<|crate|> router<|op|> select entity=user repo=hyperswitch tables=user joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="user" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/user.rs" use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; use crate::{diesel_impl::OptionalDieselArray, enums::TotpStatus, schema::users}; pub mod dashboard_metadata; pub mod sample_data; pub mod theme; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = users, primary_key(user_id), check_for_backend(diesel::pg::Pg))] pub struct User { pub user_id: String, pub email: pii::Email, pub name: Secret<String>, pub password: Option<Secret<String>>, pub is_verified: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub totp_status: TotpStatus, pub totp_secret: Option<Encryption>, #[diesel(deserialize_as = OptionalDieselArray<Secret<String>>)] pub totp_recovery_codes: Option<Vec<Secret<String>>>, pub last_password_modified_at: Option<PrimitiveDateTime>, } #[derive( router_derive::Setter, Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay, )] #[diesel(table_name = users)] pub struct UserNew { pub user_id: String, pub email: pii::Email, pub name: Secret<String>, pub password: Option<Secret<String>>, pub is_verified: bool, pub created_at: Option<PrimitiveDateTime>, pub last_modified_at: Option<PrimitiveDateTime>, pub totp_status: TotpStatus, pub totp_secret: Option<Encryption>, pub totp_recovery_codes: Option<Vec<Secret<String>>>, pub last_password_modified_at: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = users)] pub struct UserUpdateInternal { name: Option<String>, password: Option<Secret<String>>, is_verified: Option<bool>, last_modified_at: PrimitiveDateTime, totp_status: Option<TotpStatus>, totp_secret: Option<Encryption>, totp_recovery_codes: Option<Vec<Secret<String>>>, last_password_modified_at: Option<PrimitiveDateTime>, } #[derive(Debug)] pub enum UserUpdate { VerifyUser, AccountUpdate { name: Option<String>, is_verified: Option<bool>, }, TotpUpdate { totp_status: Option<TotpStatus>, totp_secret: Option<Encryption>, totp_recovery_codes: Option<Vec<Secret<String>>>, }, PasswordUpdate { password: Secret<String>, }, } impl From<UserUpdate> for UserUpdateInternal { fn from(user_update: UserUpdate) -> Self { let last_modified_at = common_utils::date_time::now(); match user_update { UserUpdate::VerifyUser => Self { name: None, password: None, is_verified: Some(true), last_modified_at, totp_status: None, totp_secret: None, totp_recovery_codes: None, last_password_modified_at: None, }, UserUpdate::AccountUpdate { name, is_verified } => Self { name, password: None, is_verified, last_modified_at, totp_status: None, totp_secret: None, totp_recovery_codes: None, last_password_modified_at: None, }, UserUpdate::TotpUpdate { totp_status, totp_secret, totp_recovery_codes, } => Self { name: None, password: None, is_verified: None, last_modified_at, totp_status, totp_secret, totp_recovery_codes, last_password_modified_at: None, }, UserUpdate::PasswordUpdate { password } => Self { name: None, password: Some(password), is_verified: None, last_modified_at, last_password_modified_at: Some(last_modified_at), totp_status: None, totp_secret: None, totp_recovery_codes: None, }, } } } <file_sep> pack="QBP-A" entity="user" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/user.rs" use common_utils::pii; use diesel::{associations::HasTable, ExpressionMethods}; pub mod sample_data; pub mod theme; use crate::{ query::generics, schema::users::dsl as users_dsl, user::*, PgPooledConn, StorageResult, }; impl UserNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<User> { generics::generic_insert(conn, self).await } } impl User { pub async fn find_by_user_email( conn: &PgPooledConn, user_email: &pii::Email, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, users_dsl::email.eq(user_email.to_owned()), ) .await } pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, users_dsl::user_id.eq(user_id.to_owned()), ) .await } pub async fn update_by_user_id( conn: &PgPooledConn, user_id: &str, user_update: UserUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, users_dsl::user_id.eq(user_id.to_owned()), UserUpdateInternal::from(user_update), ) .await } pub async fn update_by_user_email( conn: &PgPooledConn, user_email: &pii::Email, user_update: UserUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, users_dsl::email.eq(user_email.to_owned()), UserUpdateInternal::from(user_update), ) .await } pub async fn delete_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, users_dsl::user_id.eq(user_id.to_owned()), ) .await } pub async fn find_users_by_user_ids( conn: &PgPooledConn, user_ids: Vec<String>, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, _, >(conn, users_dsl::user_id.eq_any(user_ids), None, None, None) .await } } <file_sep> pack="QBP-A" entity="user" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user.rs" use diesel_models::user as storage; use error_stack::report; use masking::Secret; use router_env::{instrument, tracing}; use super::{domain, MockDb}; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; pub mod sample_data; pub mod theme; #[async_trait::async_trait] pub trait UserInterface { async fn insert_user( &self, user_data: storage::UserNew, ) -> CustomResult<storage::User, errors::StorageError>; async fn find_user_by_email( &self, user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError>; async fn find_user_by_id( &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError>; async fn update_user_by_user_id( &self, user_id: &str, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError>; async fn update_user_by_email( &self, user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError>; async fn delete_user_by_user_id( &self, user_id: &str, ) -> CustomResult<bool, errors::StorageError>; async fn find_users_by_user_ids( &self, user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError>; } #[async_trait::async_trait] impl UserInterface for Store { #[instrument(skip_all)] async fn insert_user( &self, user_data: storage::UserNew, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; user_data .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_by_email( &self, user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::User::find_by_user_email(&conn, user_email.get_inner()) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_by_id( &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::User::find_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_by_user_id( &self, user_id: &str, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::User::update_by_user_id(&conn, user_id, user) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_by_email( &self, user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::User::update_by_user_email(&conn, user_email.get_inner(), user) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_user_by_user_id( &self, user_id: &str, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::User::delete_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_users_by_user_ids( &self, user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::User::find_users_by_user_ids(&conn, user_ids) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl UserInterface for MockDb { async fn insert_user( &self, user_data: storage::UserNew, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; if users .iter() .any(|user| user.email == user_data.email || user.user_id == user_data.user_id) { Err(errors::StorageError::DuplicateValue { entity: "email or user_id", key: None, })? } let time_now = common_utils::date_time::now(); let user = storage::User { user_id: user_data.user_id, email: user_data.email, name: user_data.name, password: user_data.password, is_verified: user_data.is_verified, created_at: user_data.created_at.unwrap_or(time_now), last_modified_at: user_data.created_at.unwrap_or(time_now), totp_status: user_data.totp_status, totp_secret: user_data.totp_secret, totp_recovery_codes: user_data.totp_recovery_codes, last_password_modified_at: user_data.last_password_modified_at, }; users.push(user.clone()); Ok(user) } async fn find_user_by_email( &self, user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let users = self.users.lock().await; users .iter() .find(|user| user.email.eq(user_email.get_inner())) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for email = {user_email:?}" )) .into(), ) } async fn find_user_by_id( &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError> { let users = self.users.lock().await; users .iter() .find(|user| user.user_id == user_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )) .into(), ) } async fn update_user_by_user_id( &self, user_id: &str, update_user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; users .iter_mut() .find(|user| user.user_id == user_id) .map(|user| { *user = match &update_user { storage::UserUpdate::VerifyUser => storage::User { is_verified: true, ..user.to_owned() }, storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User { name: name.clone().map(Secret::new).unwrap_or(user.name.clone()), is_verified: is_verified.unwrap_or(user.is_verified), ..user.to_owned() }, storage::UserUpdate::TotpUpdate { totp_status, totp_secret, totp_recovery_codes, } => storage::User { totp_status: totp_status.unwrap_or(user.totp_status), totp_secret: totp_secret.clone().or(user.totp_secret.clone()), totp_recovery_codes: totp_recovery_codes .clone() .or(user.totp_recovery_codes.clone()), ..user.to_owned() }, storage::UserUpdate::PasswordUpdate { password } => storage::User { password: Some(password.clone()), last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, }; user.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )) .into(), ) } async fn update_user_by_email( &self, user_email: &domain::UserEmail, update_user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; users .iter_mut() .find(|user| user.email.eq(user_email.get_inner())) .map(|user| { *user = match &update_user { storage::UserUpdate::VerifyUser => storage::User { is_verified: true, ..user.to_owned() }, storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User { name: name.clone().map(Secret::new).unwrap_or(user.name.clone()), is_verified: is_verified.unwrap_or(user.is_verified), ..user.to_owned() }, storage::UserUpdate::TotpUpdate { totp_status, totp_secret, totp_recovery_codes, } => storage::User { totp_status: totp_status.unwrap_or(user.totp_status), totp_secret: totp_secret.clone().or(user.totp_secret.clone()), totp_recovery_codes: totp_recovery_codes .clone() .or(user.totp_recovery_codes.clone()), ..user.to_owned() }, storage::UserUpdate::PasswordUpdate { password } => storage::User { password: Some(password.clone()), last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, }; user.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for user_email = {user_email:?}" )) .into(), ) } async fn delete_user_by_user_id( &self, user_id: &str, ) -> CustomResult<bool, errors::StorageError> { let mut users = self.users.lock().await; let user_index = users .iter() .position(|user| user.user_id == user_id) .ok_or(errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )))?; users.remove(user_index); Ok(true) } async fn find_users_by_user_ids( &self, _user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } <file_sep> pack="QBP-A" entity="user" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-09-01-094614_remove-preferred-merchant-from-users/up.sql" -- Your SQL goes here ALTER TABLE users DROP COLUMN preferred_merchant_id; <file_sep> pack="QBP-A" entity="user" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-09-01-094614_remove-preferred-merchant-from-users/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE users ADD COLUMN preferred_merchant_id VARCHAR(64); <file_sep> pack="QBP-A" entity="user" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/down.sql" -- This file contains queries to re-create the `id` column as a `VARCHAR(64)` column for tables that had it removed. -- It must be ensured that the deployed version of the application includes the `id` column in any of its queries. -- Re-create the id column as this was used as the primary key with a different type ------------------------ Merchant Account ----------------------- ALTER TABLE merchant_account ADD COLUMN id VARCHAR(64); ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account ADD COLUMN id VARCHAR(64); ------------------------ Customers ----------------------- ALTER TABLE customers ADD COLUMN id VARCHAR(64); ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent ADD COLUMN id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt ADD COLUMN id VARCHAR(64); ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods ADD COLUMN id VARCHAR(64); ------------------------ Address ----------------------- ALTER TABLE address ADD COLUMN id VARCHAR(64); ------------------------ Dispute ----------------------- ALTER TABLE dispute ADD COLUMN id VARCHAR(64); ------------------------ Mandate ----------------------- ALTER TABLE mandate ADD COLUMN id VARCHAR(64); ------------------------ Refund ----------------------- ALTER TABLE refund ADD COLUMN id VARCHAR(64); ------------------------ BlockList ----------------------- ALTER TABLE blocklist ADD COLUMN id VARCHAR(64); ------------------------ Roles ----------------------- ALTER TABLE roles ADD COLUMN id VARCHAR(64); ------------------------ Users ----------------------- ALTER TABLE users ADD COLUMN id VARCHAR(64); <file_sep> pack="QBP-A" entity="user" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_user.rs" // schema snippet for entity=user repo=hyperswitch // table: users columns: [] entities: [user] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user_authentication_method.rs<|crate|> router<|op|> select entity=user_authentication_method repo=hyperswitch tables=user_authentication_method joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="user_authentication_method" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/user_authentication_method.rs" use common_utils::encryption::Encryption; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::user_authentication_methods}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = user_authentication_methods, check_for_backend(diesel::pg::Pg))] pub struct UserAuthenticationMethod { pub id: String, pub auth_id: String, pub owner_id: String, pub owner_type: enums::Owner, pub auth_type: enums::UserAuthType, pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub allow_signup: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub email_domain: String, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = user_authentication_methods)] pub struct UserAuthenticationMethodNew { pub id: String, pub auth_id: String, pub owner_id: String, pub owner_type: enums::Owner, pub auth_type: enums::UserAuthType, pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub allow_signup: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub email_domain: String, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = user_authentication_methods)] pub struct OrgAuthenticationMethodUpdateInternal { pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub last_modified_at: PrimitiveDateTime, pub email_domain: Option<String>, } pub enum UserAuthenticationMethodUpdate { UpdateConfig { private_config: Option<Encryption>, public_config: Option<serde_json::Value>, }, EmailDomain { email_domain: String, }, } impl From<UserAuthenticationMethodUpdate> for OrgAuthenticationMethodUpdateInternal { fn from(value: UserAuthenticationMethodUpdate) -> Self { let last_modified_at = common_utils::date_time::now(); match value { UserAuthenticationMethodUpdate::UpdateConfig { private_config, public_config, } => Self { private_config, public_config, last_modified_at, email_domain: None, }, UserAuthenticationMethodUpdate::EmailDomain { email_domain } => Self { private_config: None, public_config: None, last_modified_at, email_domain: Some(email_domain), }, } } } <file_sep> pack="QBP-A" entity="user_authentication_method" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/user_authentication_method.rs" use diesel::{associations::HasTable, ExpressionMethods}; use crate::{ query::generics, schema::user_authentication_methods::dsl, user_authentication_method::*, PgPooledConn, StorageResult, }; impl UserAuthenticationMethodNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserAuthenticationMethod> { generics::generic_insert(conn, self).await } } impl UserAuthenticationMethod { pub async fn get_user_authentication_method_by_id( conn: &PgPooledConn, id: &str, ) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await } pub async fn list_user_authentication_methods_for_auth_id( conn: &PgPooledConn, auth_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::auth_id.eq(auth_id.to_owned()), None, None, Some(dsl::last_modified_at.asc()), ) .await } pub async fn list_user_authentication_methods_for_owner_id( conn: &PgPooledConn, owner_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::owner_id.eq(owner_id.to_owned()), None, None, Some(dsl::last_modified_at.asc()), ) .await } pub async fn update_user_authentication_method( conn: &PgPooledConn, id: &str, user_authentication_method_update: UserAuthenticationMethodUpdate, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::id.eq(id.to_owned()), OrgAuthenticationMethodUpdateInternal::from(user_authentication_method_update), ) .await } pub async fn list_user_authentication_methods_for_email_domain( conn: &PgPooledConn, email_domain: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::email_domain.eq(email_domain.to_owned()), None, None, Some(dsl::last_modified_at.asc()), ) .await } } <file_sep> pack="QBP-A" entity="user_authentication_method" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user_authentication_method.rs" use diesel_models::user_authentication_method as storage; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait UserAuthenticationMethodInterface { async fn insert_user_authentication_method( &self, user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; async fn get_user_authentication_method_by_id( &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; async fn list_user_authentication_methods_for_owner_id( &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; async fn update_user_authentication_method( &self, id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; async fn list_user_authentication_methods_for_email_domain( &self, email_domain: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; } #[async_trait::async_trait] impl UserAuthenticationMethodInterface for Store { #[instrument(skip_all)] async fn insert_user_authentication_method( &self, user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; user_authentication_method .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn get_user_authentication_method_by_id( &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::get_user_authentication_method_by_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::list_user_authentication_methods_for_auth_id( &conn, auth_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_owner_id( &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::list_user_authentication_methods_for_owner_id( &conn, owner_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_authentication_method( &self, id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UserAuthenticationMethod::update_user_authentication_method( &conn, id, user_authentication_method_update, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_email_domain( &self, email_domain: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::list_user_authentication_methods_for_email_domain( &conn, email_domain, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl UserAuthenticationMethodInterface for MockDb { async fn insert_user_authentication_method( &self, user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let mut user_authentication_methods = self.user_authentication_methods.lock().await; let existing_auth_id = user_authentication_methods .iter() .find(|uam| uam.owner_id == user_authentication_method.owner_id) .map(|uam| uam.auth_id.clone()); let auth_id = existing_auth_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); let user_authentication_method = storage::UserAuthenticationMethod { id: uuid::Uuid::new_v4().to_string(), auth_id, owner_id: user_authentication_method.auth_id, owner_type: user_authentication_method.owner_type, auth_type: user_authentication_method.auth_type, public_config: user_authentication_method.public_config, private_config: user_authentication_method.private_config, allow_signup: user_authentication_method.allow_signup, created_at: user_authentication_method.created_at, last_modified_at: user_authentication_method.last_modified_at, email_domain: user_authentication_method.email_domain, }; user_authentication_methods.push(user_authentication_method.clone()); Ok(user_authentication_method) } #[instrument(skip_all)] async fn get_user_authentication_method_by_id( &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_method = user_authentication_methods .iter() .find(|&auth_method_inner| auth_method_inner.id == id); if let Some(user_authentication_method) = user_authentication_method { Ok(user_authentication_method.to_owned()) } else { return Err(errors::StorageError::ValueNotFound(format!( "No user authentication method found for id = {}", id )) .into()); } } async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_methods_list: Vec<_> = user_authentication_methods .iter() .filter(|auth_method_inner| auth_method_inner.auth_id == auth_id) .cloned() .collect(); if user_authentication_methods_list.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No user authentication method found for auth_id = {}", auth_id )) .into()); } Ok(user_authentication_methods_list) } async fn list_user_authentication_methods_for_owner_id( &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_methods_list: Vec<_> = user_authentication_methods .iter() .filter(|auth_method_inner| auth_method_inner.owner_id == owner_id) .cloned() .collect(); if user_authentication_methods_list.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No user authentication method found for owner_id = {}", owner_id )) .into()); } Ok(user_authentication_methods_list) } async fn update_user_authentication_method( &self, id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let mut user_authentication_methods = self.user_authentication_methods.lock().await; user_authentication_methods .iter_mut() .find(|auth_method_inner| auth_method_inner.id == id) .map(|auth_method_inner| { *auth_method_inner = match user_authentication_method_update { storage::UserAuthenticationMethodUpdate::UpdateConfig { private_config, public_config, } => storage::UserAuthenticationMethod { private_config, public_config, last_modified_at: common_utils::date_time::now(), ..auth_method_inner.to_owned() }, storage::UserAuthenticationMethodUpdate::EmailDomain { email_domain } => { storage::UserAuthenticationMethod { email_domain: email_domain.to_owned(), last_modified_at: common_utils::date_time::now(), ..auth_method_inner.to_owned() } } }; auth_method_inner.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No authentication method available for the id = {id}" )) .into(), ) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_email_domain( &self, email_domain: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_methods_list: Vec<_> = user_authentication_methods .iter() .filter(|auth_method_inner| auth_method_inner.email_domain == email_domain) .cloned() .collect(); Ok(user_authentication_methods_list) } } <file_sep> pack="QBP-A" entity="user_authentication_method" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-06-10-084722_create_user_authentication_methods_table/down.sql" -- This file should undo anything in `up.sql` DROP INDEX IF EXISTS auth_id_index; DROP INDEX IF EXISTS owner_id_index; DROP TABLE IF EXISTS user_authentication_methods; <file_sep> pack="QBP-A" entity="user_authentication_method" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-11-092624_add-email-domain-in-auth-methods/up.sql" -- Your SQL goes here ALTER TABLE user_authentication_methods ADD COLUMN email_domain VARCHAR(64); UPDATE user_authentication_methods SET email_domain = auth_id WHERE email_domain IS NULL; ALTER TABLE user_authentication_methods ALTER COLUMN email_domain SET NOT NULL; CREATE INDEX email_domain_index ON user_authentication_methods (email_domain); <file_sep> pack="QBP-A" entity="user_authentication_method" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-12-11-092624_add-email-domain-in-auth-methods/down.sql" -- This file should undo anything in `up.sql` DROP INDEX email_domain_index; ALTER TABLE user_authentication_methods DROP COLUMN email_domain; <file_sep> pack="QBP-A" entity="user_authentication_method" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_user_authentication_method.rs" // schema snippet for entity=user_authentication_method repo=hyperswitch // table: user_authentication_methods columns: [] entities: [user_authentication_method] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user_key_store.rs<|crate|> router<|op|> select entity=user_key_store repo=hyperswitch tables=user_key_store joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="user_key_store" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/user_key_store.rs" use common_utils::encryption::Encryption; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::schema::user_key_store; #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, )] #[diesel(table_name = user_key_store, primary_key(user_id), check_for_backend(diesel::pg::Pg))] pub struct UserKeyStore { pub user_id: String, pub key: Encryption, pub created_at: PrimitiveDateTime, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Insertable)] #[diesel(table_name = user_key_store)] pub struct UserKeyStoreNew { pub user_id: String, pub key: Encryption, pub created_at: PrimitiveDateTime, } <file_sep> pack="QBP-A" entity="user_key_store" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/user_key_store.rs" use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ schema::user_key_store::dsl, user_key_store::{UserKeyStore, UserKeyStoreNew}, PgPooledConn, StorageResult, }; impl UserKeyStoreNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserKeyStore> { generics::generic_insert(conn, self).await } } impl UserKeyStore { pub async fn get_all_user_key_stores( conn: &PgPooledConn, from: u32, limit: u32, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, _, >( conn, dsl::user_id.ne_all(vec!["".to_string()]), Some(limit.into()), Some(from.into()), None, ) .await } pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::user_id.eq(user_id.to_owned()), ) .await } } <file_sep> pack="QBP-A" entity="user_key_store" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user_key_store.rs" use common_utils::{ errors::CustomResult, types::keymanager::{self, KeyManagerState}, }; use error_stack::{report, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; use storage_impl::MockDb; use crate::{ connection, core::errors, services::Store, types::domain::{ self, behaviour::{Conversion, ReverseConversion}, }, }; #[async_trait::async_trait] pub trait UserKeyStoreInterface { async fn insert_user_key_store( &self, state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; async fn get_user_key_store_by_user_id( &self, state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; async fn get_all_user_key_store( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError>; } #[async_trait::async_trait] impl UserKeyStoreInterface for Store { #[instrument(skip_all)] async fn insert_user_key_store( &self, state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let user_id = user_key_store.user_id.clone(); user_key_store .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_models::user_key_store::UserKeyStore::find_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert(state, key, keymanager::Identifier::User(user_id.to_owned())) .await .change_context(errors::StorageError::DecryptionError) } async fn get_all_user_key_store( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let key_stores = diesel_models::user_key_store::UserKeyStore::get_all_user_key_stores( &conn, from, limit, ) .await .map_err(|err| report!(errors::StorageError::from(err)))?; futures::future::try_join_all(key_stores.into_iter().map(|key_store| async { let user_id = key_store.user_id.clone(); key_store .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) })) .await } } #[async_trait::async_trait] impl UserKeyStoreInterface for MockDb { #[instrument(skip_all)] async fn insert_user_key_store( &self, state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { let mut locked_user_key_store = self.user_key_store.lock().await; if locked_user_key_store .iter() .any(|user_key| user_key.user_id == user_key_store.user_id) { Err(errors::StorageError::DuplicateValue { entity: "user_key_store", key: Some(user_key_store.user_id.clone()), })?; } let user_key_store = Conversion::convert(user_key_store) .await .change_context(errors::StorageError::MockDbError)?; locked_user_key_store.push(user_key_store.clone()); let user_id = user_key_store.user_id.clone(); user_key_store .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) } async fn get_all_user_key_store( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, _from: u32, _limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let user_key_store = self.user_key_store.lock().await; futures::future::try_join_all(user_key_store.iter().map(|user_key| async { let user_id = user_key.user_id.clone(); user_key .to_owned() .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) })) .await } #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { self.user_key_store .lock() .await .iter() .find(|user_key_store| user_key_store.user_id == user_id) .cloned() .ok_or(errors::StorageError::ValueNotFound(format!( "No user_key_store is found for user_id={}", user_id )))? .convert(state, key, keymanager::Identifier::User(user_id.to_owned())) .await .change_context(errors::StorageError::DecryptionError) } } <file_sep> pack="QBP-A" entity="user_key_store" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-05-06-105026_user_key_store_table/up.sql" -- Your SQL goes here CREATE TABLE IF NOT EXISTS user_key_store ( user_id VARCHAR(64) PRIMARY KEY, key bytea NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now() ); <file_sep> pack="QBP-A" entity="user_key_store" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-05-06-105026_user_key_store_table/down.sql" -- This file should undo anything in `up.sql` DROP TABLE IF EXISTS user_key_store; <file_sep> pack="QBP-A" entity="user_key_store" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_user_key_store.rs" // schema snippet for entity=user_key_store repo=hyperswitch // table: user_key_store columns: [] entities: [user_key_store] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> /Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user_role.rs<|crate|> router<|op|> select entity=user_role repo=hyperswitch tables=user_role joins=none pack=query_boundary lang=rust_sql<|meta_end|> <file_sep> pack="QBP-A" entity="user_role" role="model" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/user_role.rs" use std::hash::Hash; use common_enums::EntityType; use common_utils::{consts, id_type}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums, schema::user_roles}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Eq)] #[diesel(table_name = user_roles, check_for_backend(diesel::pg::Pg))] pub struct UserRole { pub id: i32, pub user_id: String, pub merchant_id: Option<id_type::MerchantId>, pub role_id: String, pub org_id: Option<id_type::OrganizationId>, pub status: enums::UserStatus, pub created_by: String, pub last_modified_by: String, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub profile_id: Option<id_type::ProfileId>, pub entity_id: Option<String>, pub entity_type: Option<EntityType>, pub version: enums::UserRoleVersion, pub tenant_id: id_type::TenantId, } impl UserRole { pub fn get_entity_id_and_type(&self) -> Option<(String, EntityType)> { match (self.version, self.entity_type, self.role_id.as_str()) { (enums::UserRoleVersion::V1, None, consts::ROLE_ID_ORGANIZATION_ADMIN) => { let org_id = self.org_id.clone()?.get_string_repr().to_string(); Some((org_id, EntityType::Organization)) } (enums::UserRoleVersion::V1, None, _) => { let merchant_id = self.merchant_id.clone()?.get_string_repr().to_string(); Some((merchant_id, EntityType::Merchant)) } (enums::UserRoleVersion::V1, Some(_), _) => { self.entity_id.clone().zip(self.entity_type) } (enums::UserRoleVersion::V2, _, _) => self.entity_id.clone().zip(self.entity_type), } } } impl Hash for UserRole { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.user_id.hash(state); if let Some((entity_id, entity_type)) = self.get_entity_id_and_type() { entity_id.hash(state); entity_type.hash(state); } } } impl PartialEq for UserRole { fn eq(&self, other: &Self) -> bool { match ( self.get_entity_id_and_type(), other.get_entity_id_and_type(), ) { ( Some((self_entity_id, self_entity_type)), Some((other_entity_id, other_entity_type)), ) => { self.user_id == other.user_id && self_entity_id == other_entity_id && self_entity_type == other_entity_type } _ => self.user_id == other.user_id, } } } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = user_roles)] pub struct UserRoleNew { pub user_id: String, pub merchant_id: Option<id_type::MerchantId>, pub role_id: String, pub org_id: Option<id_type::OrganizationId>, pub status: enums::UserStatus, pub created_by: String, pub last_modified_by: String, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub profile_id: Option<id_type::ProfileId>, pub entity_id: Option<String>, pub entity_type: Option<EntityType>, pub version: enums::UserRoleVersion, pub tenant_id: id_type::TenantId, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = user_roles)] pub struct UserRoleUpdateInternal { role_id: Option<String>, status: Option<enums::UserStatus>, last_modified_by: Option<String>, last_modified: PrimitiveDateTime, } #[derive(Clone)] pub enum UserRoleUpdate { UpdateStatus { status: enums::UserStatus, modified_by: String, }, UpdateRole { role_id: String, modified_by: String, }, } impl From<UserRoleUpdate> for UserRoleUpdateInternal { fn from(value: UserRoleUpdate) -> Self { let last_modified = common_utils::date_time::now(); match value { UserRoleUpdate::UpdateRole { role_id, modified_by, } => Self { role_id: Some(role_id), last_modified_by: Some(modified_by), status: None, last_modified, }, UserRoleUpdate::UpdateStatus { status, modified_by, } => Self { status: Some(status), last_modified, last_modified_by: Some(modified_by), role_id: None, }, } } } <file_sep> pack="QBP-A" entity="user_role" role="query" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/diesel_models/src/query/user_role.rs" 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_sep> pack="QBP-A" entity="user_role" role="boundary" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/crates/router/src/db/user_role.rs" use common_utils::id_type; use diesel_models::{ enums::{self, UserStatus}, user_role as storage, }; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; pub struct ListUserRolesByOrgIdPayload<'a> { pub user_id: Option<&'a String>, pub tenant_id: &'a id_type::TenantId, pub org_id: &'a id_type::OrganizationId, pub merchant_id: Option<&'a id_type::MerchantId>, pub profile_id: Option<&'a id_type::ProfileId>, pub version: Option<enums::UserRoleVersion>, pub limit: Option<u32>, } pub struct ListUserRolesByUserIdPayload<'a> { pub user_id: &'a str, pub tenant_id: &'a id_type::TenantId, pub org_id: Option<&'a id_type::OrganizationId>, pub merchant_id: Option<&'a id_type::MerchantId>, pub profile_id: Option<&'a id_type::ProfileId>, pub entity_id: Option<&'a String>, pub version: Option<enums::UserRoleVersion>, pub status: Option<UserStatus>, pub limit: Option<u32>, } #[async_trait::async_trait] pub trait UserRoleInterface { async fn insert_user_role( &self, user_role: storage::UserRoleNew, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; async fn list_user_roles_by_user_id_across_tenants( &self, user_id: &str, limit: Option<u32>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; } #[async_trait::async_trait] impl UserRoleInterface for Store { #[instrument(skip_all)] async fn insert_user_role( &self, user_role: storage::UserRoleNew, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; user_role .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::find_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), tenant_id.to_owned(), org_id.to_owned(), merchant_id.to_owned(), profile_id.to_owned(), version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UserRole::update_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), tenant_id.to_owned(), org_id.to_owned(), merchant_id.cloned(), profile_id.cloned(), update, version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UserRole::delete_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), tenant_id.to_owned(), org_id.to_owned(), merchant_id.to_owned(), profile_id.to_owned(), version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::generic_user_roles_list_for_user( &conn, payload.user_id.to_owned(), payload.tenant_id.to_owned(), payload.org_id.cloned(), payload.merchant_id.cloned(), payload.profile_id.cloned(), payload.entity_id.cloned(), payload.status, payload.version, payload.limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_user_roles_by_user_id_across_tenants( &self, user_id: &str, limit: Option<u32>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::list_user_roles_by_user_id_across_tenants( &conn, user_id.to_owned(), limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::generic_user_roles_list_for_org_and_extra( &conn, payload.user_id.cloned(), payload.tenant_id.to_owned(), payload.org_id.to_owned(), payload.merchant_id.cloned(), payload.profile_id.cloned(), payload.version, payload.limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl UserRoleInterface for MockDb { async fn insert_user_role( &self, user_role: storage::UserRoleNew, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut db_user_roles = self.user_roles.lock().await; if db_user_roles .iter() .any(|user_role_inner| user_role_inner.user_id == user_role.user_id) { Err(errors::StorageError::DuplicateValue { entity: "user_id", key: None, })? } let user_role = storage::UserRole { id: i32::try_from(db_user_roles.len()) .change_context(errors::StorageError::MockDbError)?, user_id: user_role.user_id, merchant_id: user_role.merchant_id, role_id: user_role.role_id, status: user_role.status, created_by: user_role.created_by, created_at: user_role.created_at, last_modified: user_role.last_modified, last_modified_by: user_role.last_modified_by, org_id: user_role.org_id, profile_id: None, entity_id: None, entity_type: None, version: enums::UserRoleVersion::V1, tenant_id: user_role.tenant_id, }; db_user_roles.push(user_role.clone()); Ok(user_role) } async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let user_roles = self.user_roles.lock().await; for user_role in user_roles.iter() { let tenant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.is_none() && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let org_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let merchant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == Some(merchant_id) && user_role.profile_id.is_none(); let profile_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == Some(merchant_id) && user_role.profile_id.as_ref() == Some(profile_id); // Check if any condition matches and the version matches if user_role.user_id == user_id && (tenant_level_check || org_level_check || merchant_level_check || profile_level_check) && user_role.version == version { return Ok(user_role.clone()); } } Err(errors::StorageError::ValueNotFound(format!( "No user role available for user_id = {} in the current token hierarchy", user_id )) .into()) } async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; for user_role in user_roles.iter_mut() { let tenant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.is_none() && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let org_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let merchant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == merchant_id && user_role.profile_id.is_none(); let profile_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == merchant_id && user_role.profile_id.as_ref() == profile_id; // Check if any condition matches and the version matches if user_role.user_id == user_id && (tenant_level_check || org_level_check || merchant_level_check || profile_level_check) && user_role.version == version { match &update { storage::UserRoleUpdate::UpdateRole { role_id, modified_by, } => { user_role.role_id = role_id.to_string(); user_role.last_modified_by = modified_by.to_string(); } storage::UserRoleUpdate::UpdateStatus { status, modified_by, } => { user_role.status = *status; user_role.last_modified_by = modified_by.to_string(); } } return Ok(user_role.clone()); } } Err( errors::StorageError::ValueNotFound("Cannot find user role to update".to_string()) .into(), ) } async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; // Find the position of the user role to delete let index = user_roles.iter().position(|role| { let tenant_level_check = role.tenant_id == *tenant_id && role.org_id.is_none() && role.merchant_id.is_none() && role.profile_id.is_none(); let org_level_check = role.tenant_id == *tenant_id && role.org_id.as_ref() == Some(org_id) && role.merchant_id.is_none() && role.profile_id.is_none(); let merchant_level_check = role.tenant_id == *tenant_id && role.org_id.as_ref() == Some(org_id) && role.merchant_id.as_ref() == Some(merchant_id) && role.profile_id.is_none(); let profile_level_check = role.tenant_id == *tenant_id && role.org_id.as_ref() == Some(org_id) && role.merchant_id.as_ref() == Some(merchant_id) && role.profile_id.as_ref() == Some(profile_id); // Check if the user role matches the conditions and the version matches role.user_id == user_id && (tenant_level_check || org_level_check || merchant_level_check || profile_level_check) && role.version == version }); // Remove and return the user role if found match index { Some(idx) => Ok(user_roles.remove(idx)), None => Err(errors::StorageError::ValueNotFound( "Cannot find user role to delete".to_string(), ) .into()), } } async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let user_roles = self.user_roles.lock().await; let mut filtered_roles: Vec<_> = user_roles .iter() .filter_map(|role| { let mut filter_condition = role.user_id == payload.user_id; role.org_id .as_ref() .zip(payload.org_id) .inspect(|(role_org_id, org_id)| { filter_condition = filter_condition && role_org_id == org_id }); role.merchant_id.as_ref().zip(payload.merchant_id).inspect( |(role_merchant_id, merchant_id)| { filter_condition = filter_condition && role_merchant_id == merchant_id }, ); role.profile_id.as_ref().zip(payload.profile_id).inspect( |(role_profile_id, profile_id)| { filter_condition = filter_condition && role_profile_id == profile_id }, ); role.entity_id.as_ref().zip(payload.entity_id).inspect( |(role_entity_id, entity_id)| { filter_condition = filter_condition && role_entity_id == entity_id }, ); payload .version .inspect(|ver| filter_condition = filter_condition && ver == &role.version); payload.status.inspect(|status| { filter_condition = filter_condition && status == &role.status }); filter_condition.then(|| role.to_owned()) }) .collect(); if let Some(Ok(limit)) = payload.limit.map(|val| val.try_into()) { filtered_roles = filtered_roles.into_iter().take(limit).collect(); } Ok(filtered_roles) } async fn list_user_roles_by_user_id_across_tenants( &self, user_id: &str, limit: Option<u32>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let user_roles = self.user_roles.lock().await; let filtered_roles: Vec<_> = user_roles .iter() .filter(|role| role.user_id == user_id) .cloned() .collect(); if let Some(Ok(limit)) = limit.map(|val| val.try_into()) { return Ok(filtered_roles.into_iter().take(limit).collect()); } Ok(filtered_roles) } async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let user_roles = self.user_roles.lock().await; let mut filtered_roles = Vec::new(); for role in user_roles.iter() { let role_org_id = role .org_id .as_ref() .ok_or(report!(errors::StorageError::MockDbError))?; let mut filter_condition = role_org_id == payload.org_id; if let Some(user_id) = payload.user_id { filter_condition = filter_condition && user_id == &role.user_id } role.merchant_id.as_ref().zip(payload.merchant_id).inspect( |(role_merchant_id, merchant_id)| { filter_condition = filter_condition && role_merchant_id == merchant_id }, ); role.profile_id.as_ref().zip(payload.profile_id).inspect( |(role_profile_id, profile_id)| { filter_condition = filter_condition && role_profile_id == profile_id }, ); payload .version .inspect(|ver| filter_condition = filter_condition && ver == &role.version); if filter_condition { filtered_roles.push(role.clone()) } } Ok(filtered_roles) } } <file_sep> pack="QBP-A" entity="user_role" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-08-06-103905_drop_user_id_merchant_id_unique_in_user_roles/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE user_roles ADD CONSTRAINT user_merchant_unique UNIQUE (user_id, merchant_id); <file_sep> pack="QBP-A" entity="user_role" role="migration_up" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/up.sql" -- Your SQL goes here ALTER TABLE user_roles ADD COLUMN IF NOT EXISTS tenant_id VARCHAR(64) NOT NULL DEFAULT 'public'; <file_sep> pack="QBP-A" entity="user_role" role="migration_down" path="/Users/sachin/PycharmProjects/hs_code_llm/tools/pack/codefiles/hyperswitch/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/down.sql" -- This file should undo anything in `up.sql` ALTER TABLE user_roles DROP COLUMN IF EXISTS tenant_id; <file_sep> pack="QBP-A" entity="user_role" role="schema" path="tools/pack/outputs/query_boundary/indices/schema_entity_user_role.rs" // schema snippet for entity=user_role repo=hyperswitch // table: user_roles columns: [] entities: [user_role] sources: [migration, model_or_query]
query_boundary
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/utils.rs<|crate|> router anchor=missing_field_err kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="56" end="65"> pub fn missing_field_err( message: &'static str, ) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> { Box::new(move || { errors::ConnectorError::MissingRequiredField { field_name: message, } .into() }) } <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="55" end="55"> use std::{ collections::{HashMap, HashSet}, str::FromStr, }; use common_utils::{ date_time, errors::{ParsingError, ReportSwitchExt}, ext_traits::StringExt, id_type, pii::{self, Email, IpAddress}, types::{AmountConvertor, MinorUnit}, }; use error_stack::{report, ResultExt}; use crate::{ consts, core::{ errors::{self, ApiErrorResponse, CustomResult}, payments::{types::AuthenticationData, PaymentData}, }, pii::PeekInterface, types::{ self, api, domain, storage::enums as storage_enums, transformers::{ForeignFrom, ForeignTryFrom}, ApplePayPredecryptData, BrowserInformation, PaymentsCancelData, ResponseId, }, utils::{OptionExt, ValueExt}, }; type Error = error_stack::Report<errors::ConnectorError>; <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="162" end="191"> fn get_attempt_status_for_db_update<F>( &self, payment_data: &PaymentData<F>, ) -> enums::AttemptStatus where F: Clone, { match self.status { enums::AttemptStatus::Voided => { if payment_data.payment_intent.amount_captured > Some(MinorUnit::new(0)) { enums::AttemptStatus::PartialCharged } else { self.status } } enums::AttemptStatus::Charged => { let captured_amount = types::Capturable::get_captured_amount(&self.request, payment_data); let total_capturable_amount = payment_data.payment_attempt.get_total_amount(); if Some(total_capturable_amount) == captured_amount.map(MinorUnit::new) { enums::AttemptStatus::Charged } else if captured_amount.is_some() { enums::AttemptStatus::PartialCharged } else { self.status } } _ => self.status, } } <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="74" end="79"> fn get_request_id(&self) -> Result<Secret<String>, Error> { self.request .id .clone() .ok_or_else(missing_field_err("request.id")) } <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="217" end="224"> fn get_billing_phone( &self, ) -> Result<&hyperswitch_domain_models::address::PhoneDetails, Error> { self.address .get_payment_method_billing() .and_then(|a| a.phone.as_ref()) .ok_or_else(missing_field_err("billing.phone")) } <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="856" end="860"> fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1506" end="1508"> pub fn new(headers: &'a HeaderMap) -> Self { HeaderMapStruct { headers } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1505" end="1505"> use actix_web::http::header::HeaderMap; use crate::{ core::{ api_keys, errors::{self, utils::StorageErrorExt, RouterResult}, }, headers, routes::app::SessionStateInfo, services::api, types::{domain, storage}, utils::OptionExt, }; pub type AuthenticationDataWithUserId = (AuthenticationData, String); <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1532" end="1550"> pub fn get_id_type_from_header< T: TryFrom< std::borrow::Cow<'static, str>, Error = error_stack::Report<errors::ValidationError>, >, >( &self, key: &str, ) -> RouterResult<T> { self.get_mandatory_header_value_by_key(key) .map(|val| val.to_owned()) .and_then(|header_value| { T::try_from(std::borrow::Cow::Owned(header_value)).change_context( errors::ApiErrorResponse::InvalidRequestData { message: format!("`{}` header is invalid", key), }, ) }) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1510" end="1528"> fn get_mandatory_header_value_by_key( &self, key: &str, ) -> Result<&str, error_stack::Report<errors::ApiErrorResponse>> { self.headers .get(key) .ok_or(errors::ApiErrorResponse::InvalidRequestData { message: format!("Missing header key: `{}`", key), }) .attach_printable(format!("Failed to find header key: {}", key))? .to_str() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "`{key}` in headers", }) .attach_printable(format!( "Failed to convert header value to string for header key: {}", key )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1414" end="1497"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let merchant_id_from_route: id_type::MerchantId = self.0.clone(); let request_api_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; let conf = state.conf(); let admin_api_key: &masking::Secret<String> = &conf.secrets.get_inner().admin_api_key; if request_api_key == admin_api_key.peek() { let (key_store, merchant) = Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: None, }; return Ok(( auth, AuthenticationType::AdminApiAuthWithMerchantId { merchant_id: merchant_id_from_route.clone(), }, )); } let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else { return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( "Api Key Authentication Failure: fallback merchant set not configured", ); }; let api_key = api_keys::PlaintextApiKey::from(request_api_key); let hash_key = conf.api_keys.get_inner().get_hash_key()?; let hashed_api_key = api_key.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("Merchant not authenticated")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } if fallback_merchant_ids .merchant_ids .contains(&stored_api_key.merchant_id) { let (_, api_key_merchant) = Self::fetch_merchant_key_store_and_account(&stored_api_key.merchant_id, state) .await?; let (route_key_store, route_merchant) = Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; if api_key_merchant.get_org_id() == route_merchant.get_org_id() { let auth = AuthenticationData { merchant_account: route_merchant, platform_merchant_account: None, key_store: route_key_store, profile_id: None, }; return Ok(( auth.clone(), AuthenticationType::MerchantId { merchant_id: auth.merchant_account.get_id().clone(), }, )); } } Err(report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Authentication Failure")) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1382" end="1404"> async fn fetch_merchant_key_store_and_account<A: SessionStateInfo + Sync>( merchant_id: &id_type::MerchantId, state: &A, ) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> { let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; Ok((key_store, merchant)) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3364" end="3430"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let profile_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &payload.merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let merchant_id = merchant.get_id().clone(); let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth, AuthenticationType::MerchantJwt { merchant_id, user_id: Some(payload.user_id), }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="2669" end="2741"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; // Check if token has access to MerchantId that has been requested through headers if payload.merchant_id != merchant_id_from_header { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &payload.merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1501" end="1503"> pub(crate) struct HeaderMapStruct<'a> { headers: &'a HeaderMap, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/square.rs<|crate|> router<|connector|> square anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="39" end="52"> fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="58" end="71"> fn token_details() -> Option<types::PaymentMethodTokenizationData> { Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("100".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="54" end="56"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="32" end="34"> fn get_name(&self) -> String { "square".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="23" end="30"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( ConnectorAuthentication::new() .square .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="204" end="230"> async fn should_partially_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="522" end="546"> async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment( txn_id.clone().unwrap(), None, get_default_payment_info(None), ) .await .unwrap(); let connector_transaction_id = txn_id.unwrap(); assert_eq!( void_response.response.unwrap_err().reason.unwrap_or("".to_string()), format!("Payment {connector_transaction_id} is in inflight state COMPLETED, which is invalid for the requested operation") ); } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="61" end="72"> pub struct PaymentInfo { pub address: Option<PaymentAddress>, pub auth_type: Option<enums::AuthenticationType>, pub access_token: Option<AccessToken>, pub connector_meta_data: Option<serde_json::Value>, pub connector_customer: Option<String>, pub payment_method_token: Option<String>, #[cfg(feature = "payouts")] pub payout_method_data: Option<types::api::PayoutMethodData>, #[cfg(feature = "payouts")] pub currency: Option<enums::Currency>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/square.rs<|crate|> router<|connector|> square anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="39" end="52"> fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="58" end="71"> fn token_details() -> Option<types::PaymentMethodTokenizationData> { Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("100".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="54" end="56"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="32" end="34"> fn get_name(&self) -> String { "square".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="23" end="30"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( ConnectorAuthentication::new() .square .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="204" end="230"> async fn should_partially_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="522" end="546"> async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment( txn_id.clone().unwrap(), None, get_default_payment_info(None), ) .await .unwrap(); let connector_transaction_id = txn_id.unwrap(); assert_eq!( void_response.response.unwrap_err().reason.unwrap_or("".to_string()), format!("Payment {connector_transaction_id} is in inflight state COMPLETED, which is invalid for the requested operation") ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stax.rs<|crate|> router<|connector|> stax anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="39" end="55"> fn get_default_payment_info( connector_customer: Option<String>, payment_method_token: Option<String>, ) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="63" end="76"> fn token_details() -> Option<types::PaymentMethodTokenizationData> { Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="57" end="61"> fn customer_details() -> Option<types::ConnectorCustomerData> { Some(types::ConnectorCustomerData { ..utils::CustomerType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="32" end="34"> fn get_name(&self) -> String { "stax".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="23" end="30"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .stax .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="361" end="374"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="598" end="611"> async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment( "123456789".to_string(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().reason, Some(r#"{"id":["The selected id is invalid."]}"#.to_string()), ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="37" end="41"> pub const fn new() -> &'static Self { &Self { amount_converter: &FloatMajorUnitForConnector, } } <file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="36" end="36"> use common_utils::{ crypto, ext_traits::ByteSliceExt, request::RequestContent, types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; <file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="74" end="76"> fn id(&self) -> &'static str { "nmi" } <file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="61" end="70"> fn build_headers( &self, _req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { Ok(vec![( "Content-Type".to_string(), "application/x-www-form-urlencoded".to_string().into(), )]) } <file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="433" end="446"> fn get_request_body( &self, req: &types::PaymentsCompleteAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = nmi::NmiRouterData::from((amount, req)); let connector_req = nmi::NmiCompleteRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } <file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="523" end="538"> fn build_request( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .set_body(types::PaymentsSyncType::get_request_body( self, req, connectors, )?) .build(), )) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/paypal.rs<|crate|> router<|connector|> paypal anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="51" end="56"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { access_token: get_access_token(), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="71" end="77"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="58" end="66"> fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4000020000000000").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="40" end="50"> fn get_access_token() -> Option<AccessToken> { let connector = PaypalTest {}; match connector.get_auth_token() { ConnectorAuthType::BodyKey { api_key, key1: _ } => Some(AccessToken { token: api_key, expires: 18600, }), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="34" end="36"> fn get_name(&self) -> String { "paypal".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="128" end="157"> async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = "".to_string(); let connector_meta = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { mandate_id: None, connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, sync_type: types::SyncRequestType::SinglePaymentSync, connector_meta, payment_method_type: None, currency: enums::Currency::USD, payment_experience: None, integrity_object: None, amount: MinorUnit::new(100), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="364" end="373"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(get_payment_data(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/fiserv.rs<|crate|> router<|connector|> fiserv anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="63" end="68"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { connector_meta_data: Some(json!({"terminalId": "10000001"})), ..utils::PaymentInfo::with_default_billing_name() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="62" end="62"> use serde_json::json; <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="87" end="93"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="76" end="82"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="43" end="61"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4005550000000019").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="38" end="40"> fn get_connector_meta(&self) -> Option<serde_json::Value> { Some(json!({"terminalId": "10000001"})) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="416" end="434"> async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Unable to assign card to brand: Invalid.".to_string(), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="469" end="478"> async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Referenced transaction is invalid or not found") ); } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="61" end="72"> pub struct PaymentInfo { pub address: Option<PaymentAddress>, pub auth_type: Option<enums::AuthenticationType>, pub access_token: Option<AccessToken>, pub connector_meta_data: Option<serde_json::Value>, pub connector_customer: Option<String>, pub payment_method_token: Option<String>, #[cfg(feature = "payouts")] pub payout_method_data: Option<types::api::PayoutMethodData>, #[cfg(feature = "payouts")] pub currency: Option<enums::Currency>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/fiserv.rs<|crate|> router<|connector|> fiserv anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="63" end="68"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { connector_meta_data: Some(json!({"terminalId": "10000001"})), ..utils::PaymentInfo::with_default_billing_name() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="62" end="62"> use serde_json::json; <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="87" end="93"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="76" end="82"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="43" end="61"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4005550000000019").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="38" end="40"> fn get_connector_meta(&self) -> Option<serde_json::Value> { Some(json!({"terminalId": "10000001"})) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="416" end="434"> async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Unable to assign card to brand: Invalid.".to_string(), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="469" end="478"> async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Referenced transaction is invalid or not found") ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/dlocal.rs<|crate|> router<|connector|> dlocal anchor=get_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/dlocal.rs" role="context" start="423" end="450"> pub fn get_payment_info() -> PaymentInfo { PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { phone: None, address: Some(AddressDetails { city: None, country: Some(api_models::enums::CountryAlpha2::PA), line1: None, line2: None, line3: None, zip: None, state: None, first_name: None, last_name: None, }), email: None, }), None, None, )), auth_type: None, access_token: None, connector_meta_data: None, ..Default::default() } } <file_sep path="hyperswitch/crates/router/tests/connectors/dlocal.rs" role="context" start="422" end="422"> use hyperswitch_domain_models::address::{Address, AddressDetails}; use router::types::{self, api, domain, storage::enums, PaymentAddress}; <file_sep path="hyperswitch/crates/router/tests/connectors/dlocal.rs" role="context" start="404" end="421"> async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( None, Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), Some(get_payment_info()), ) .await .unwrap(); let x = response.response.unwrap_err(); println!("response from refund amount higher payment"); println!("{}", x.code); assert_eq!(x.code, "5007",); assert_eq!(x.message, "Amount exceeded",); } <file_sep path="hyperswitch/crates/router/tests/connectors/dlocal.rs" role="context" start="393" end="400"> async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456sdf789".to_string(), None, Some(get_payment_info())) .await .unwrap(); let x = capture_response.response.unwrap_err(); assert_eq!(x.code, "3003",); } <file_sep path="hyperswitch/crates/router/tests/connectors/dlocal.rs" role="context" start="140" end="157"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( None, None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), Some(get_payment_info()), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/dlocal.rs" role="context" start="353" end="370"> async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("20001".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), Some(get_payment_info()), ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!(x.message, "Invalid parameter",); assert_eq!(x.reason, Some("card.expiration_year".to_string())); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/payme.rs<|crate|> router<|connector|> payme anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="44" end="76"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { city: None, country: None, line1: None, line2: None, line3: None, zip: None, state: None, first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), }), phone: None, email: None, }), None, None, )), auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token: None, #[cfg(feature = "payouts")] currency: None, #[cfg(feature = "payouts")] payout_method_data: None, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="43" end="43"> use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, domain, storage::enums, PaymentAddress}; <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="113" end="119"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="78" end="108"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, }]), router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), email: Some(Email::from_str("test@gmail.com").unwrap()), payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_cvc: Secret::new("123".to_string()), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), ..utils::CCardType::default().0 }), amount: 1000, ..PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="37" end="39"> fn get_name(&self) -> String { "payme".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="28" end="35"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .payme .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="533" end="549"> async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 1500, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "internal_server_error", ); } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="315" end="330"> async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stax.rs<|crate|> router<|connector|> stax anchor=create_customer_and_get_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="84" end="107"> async fn create_customer_and_get_token() -> Option<String> { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( token_details(), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="83" end="83"> use router::types::{self, domain, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="125" end="135"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="112" end="121"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="78" end="82"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="63" end="76"> fn token_details() -> Option<types::PaymentMethodTokenizationData> { Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="201" end="233"> async fn should_refund_manually_captured_payment() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="331" end="357"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="57" end="61"> fn customer_details() -> Option<types::ConnectorCustomerData> { Some(types::ConnectorCustomerData { ..utils::CustomerType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="39" end="55"> fn get_default_payment_info( connector_customer: Option<String>, payment_method_token: Option<String>, ) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/multisafepay.rs<|crate|> router<|connector|> multisafepay anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="40" end="65"> fn get_default_payment_info() -> Option<PaymentInfo> { let address = Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), line1: Some(Secret::new("Kraanspoor".to_string())), line2: Some(Secret::new("line2".to_string())), line3: Some(Secret::new("line3".to_string())), city: Some("Amsterdam".to_string()), zip: Some(Secret::new("1033SC".to_string())), country: Some(api_models::enums::CountryAlpha2::NL), state: Some(Secret::new("Amsterdam".to_string())), }), phone: None, email: None, }), None, None, )); Some(PaymentInfo { address, ..PaymentInfo::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="39" end="39"> use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, domain, storage::enums, PaymentAddress}; <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="82" end="88"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(None, None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="71" end="77"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(None, get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="33" end="35"> fn get_name(&self) -> String { "multisafepay".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="24" end="31"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .multisafepay .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="256" end="265"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(None, None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="229" end="251"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(None, get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/macros.rs" role="context" start="17" end="21"> struct Address { line1: String, zip: String, city: String, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund -----------------------
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/multisafepay.rs<|crate|> router<|connector|> multisafepay anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="40" end="65"> fn get_default_payment_info() -> Option<PaymentInfo> { let address = Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), line1: Some(Secret::new("Kraanspoor".to_string())), line2: Some(Secret::new("line2".to_string())), line3: Some(Secret::new("line3".to_string())), city: Some("Amsterdam".to_string()), zip: Some(Secret::new("1033SC".to_string())), country: Some(api_models::enums::CountryAlpha2::NL), state: Some(Secret::new("Amsterdam".to_string())), }), phone: None, email: None, }), None, None, )); Some(PaymentInfo { address, ..PaymentInfo::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="39" end="39"> use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, domain, storage::enums, PaymentAddress}; <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="82" end="88"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(None, None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="71" end="77"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(None, get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="33" end="35"> fn get_name(&self) -> String { "multisafepay".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="24" end="31"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .multisafepay .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="256" end="265"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(None, None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/multisafepay.rs" role="context" start="229" end="251"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(None, get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/square.rs<|crate|> router<|connector|> square anchor=create_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="73" end="82"> async fn create_token() -> Option<String> { let token_response = CONNECTOR .create_connector_pm_token(token_details(), get_default_payment_info(None)) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="72" end="72"> use router::types::{self, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="100" end="110"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), None, get_default_payment_info(create_token().await), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="87" end="96"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="58" end="71"> fn token_details() -> Option<types::PaymentMethodTokenizationData> { Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("100".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="54" end="56"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="274" end="300"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(None), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="204" end="230"> async fn should_partially_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="39" end="52"> fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/bluesnap.rs<|crate|> router<|connector|> bluesnap anchor=get_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="47" end="65"> fn get_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("joseph".to_string())), last_name: Some(Secret::new("Doe".to_string())), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="46" end="46"> use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, domain, storage::enums, ConnectorAuthType, PaymentAddress}; <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="84" end="90"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="72" end="78"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="41" end="46"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("test@gmail.com").unwrap()), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="37" end="39"> fn get_name(&self) -> String { "bluesnap".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="336" end="370"> async fn should_refund_succeeded_payment_multiple_times() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let transaction_id = utils::get_connector_transaction_id(authorize_response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(std::time::Duration::from_secs(5)).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); let rsync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( rsync_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="253" end="275"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/admin.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4451" end="4453"> pub fn new(profile: domain::Profile) -> Self { Self { profile } } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4450" end="4450"> use crate::{ consts, core::{ encryption::transfer_encryption_key, errors::{self, RouterResponse, RouterResult, StorageErrorExt}, payment_methods::{cards, transformers}, payments::helpers, pm_auth::helpers::PaymentAuthConnectorDataExt, routing, utils as core_utils, }, db::{AccountsStorageInterface, StorageInterface}, routes::{metrics, SessionState}, services::{ self, api::{self as service_api, client}, authentication, pm_auth as payment_initiation_service, }, types::{ self, api::{self, admin}, domain::{ self, types::{self as domain_types, AsyncLift}, }, storage::{self, enums::MerchantStorageScheme}, transformers::{ForeignInto, ForeignTryFrom, ForeignTryInto}, }, utils, }; <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4469" end="4510"> pub async fn update_profile_and_invalidate_routing_config_for_active_algorithm_id_update( self, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, algorithm_id: id_type::RoutingId, transaction_type: &storage::enums::TransactionType, ) -> RouterResult<()> { let routing_cache_key = self.clone().get_routing_config_cache_key(); let (routing_algorithm_id, payout_routing_algorithm_id) = match transaction_type { storage::enums::TransactionType::Payment => (Some(algorithm_id), None), #[cfg(feature = "payouts")] storage::enums::TransactionType::Payout => (None, Some(algorithm_id)), }; let profile_update = domain::ProfileUpdate::RoutingAlgorithmUpdate { routing_algorithm_id, payout_routing_algorithm_id, }; let profile = self.profile; db.update_profile_by_profile_id( key_manager_state, merchant_key_store, profile, profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref in business profile")?; storage_impl::redis::cache::redact_from_redis_and_publish( db.get_cache_store().as_ref(), [routing_cache_key], ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to invalidate routing cache")?; Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4454" end="4467"> fn get_routing_config_cache_key(self) -> storage_impl::redis::cache::CacheKind<'static> { let merchant_id = self.profile.merchant_id.clone(); let profile_id = self.profile.get_id().to_owned(); storage_impl::redis::cache::CacheKind::Routing( format!( "routing_config_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr() ) .into(), ) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4404" end="4441"> pub async fn update_profile( state: SessionState, profile_id: &id_type::ProfileId, key_store: domain::MerchantKeyStore, request: api::ProfileUpdate, ) -> RouterResponse<api::ProfileResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let profile_update = request .get_update_profile_object(&state, &key_store, &business_profile) .await?; let updated_business_profile = db .update_profile_by_profile_id( key_manager_state, &key_store, business_profile, profile_update, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(service_api::ApplicationResponse::Json( api_models::admin::ProfileResponse::foreign_try_from(updated_business_profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?, )) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4272" end="4400"> async fn get_update_profile_object( self, state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, ) -> RouterResult<domain::ProfileUpdate> { if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let payment_link_config = self .payment_link_config .map(|payment_link_conf| match payment_link_conf.validate() { Ok(_) => Ok(payment_link_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let extended_card_info_config = self .extended_card_info_config .as_ref() .map(|config| { config.encode_to_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "extended_card_info_config", }, ) }) .transpose()? .map(Secret::new); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data(&key_manager_state, key_store, headers) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = match business_profile.card_testing_secret_key { Some(_) => None, None => { let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")? } }; Ok(domain::ProfileUpdate::Update(Box::new( domain::ProfileGeneralUpdate { profile_name: self.profile_name, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, webhook_details, metadata: self.metadata, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self.session_expiry.map(i64::from), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, extended_card_info_config, use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector_if_required, collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector_if_required, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, order_fulfillment_time: self .order_fulfillment_time .map(|order_fulfillment_time| order_fulfillment_time.into_inner()), order_fulfillment_time_origin: self.order_fulfillment_time_origin, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, three_ds_decision_manager_config: None, card_testing_guard_config: self .card_testing_guard_config .map(ForeignInto::foreign_into), card_testing_secret_key, is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: self.merchant_business_country, }, ))) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4783" end="4862"> fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult<()> { match data { types::MerchantAccountData::Iban { iban, .. } => { // IBAN check algorithm if iban.peek().len() > IBAN_MAX_LENGTH { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "IBAN length must be up to 34 characters".to_string(), } .into()); } let pattern = Regex::new(r"^[A-Z0-9]*$") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to create regex pattern")?; let mut iban = iban.peek().to_string(); if !pattern.is_match(iban.as_str()) { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "IBAN data must be alphanumeric".to_string(), } .into()); } // MOD check let first_4 = iban.chars().take(4).collect::<String>(); iban.push_str(first_4.as_str()); let len = iban.len(); let rearranged_iban = iban .chars() .rev() .take(len - 4) .collect::<String>() .chars() .rev() .collect::<String>(); let mut result = String::new(); rearranged_iban.chars().for_each(|c| { if c.is_ascii_uppercase() { let digit = (u32::from(c) - u32::from('A')) + 10; result.push_str(&format!("{:02}", digit)); } else { result.push(c); } }); let num = result .parse::<u128>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to validate IBAN")?; if num % 97 != 1 { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid IBAN".to_string(), } .into()); } Ok(()) } types::MerchantAccountData::Bacs { account_number, sort_code, .. } => { if account_number.peek().len() > BACS_MAX_ACCOUNT_NUMBER_LENGTH || sort_code.peek().len() != BACS_SORT_CODE_LENGTH { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid BACS numbers".to_string(), } .into()); } Ok(()) } } } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4522" end="4538"> pub fn get_default_fallback_list_of_connector_under_profile( &self, ) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> { let fallback_connectors = if let Some(default_fallback_routing) = self.profile.default_fallback_routing.clone() { default_fallback_routing .expose() .parse_value::<Vec<routing_types::RoutableConnectorChoice>>( "Vec<RoutableConnectorChoice>", ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Business Profile default config has invalid structure")? } else { Vec::new() }; Ok(fallback_connectors) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=get_headers kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2675" end="2681"> fn get_headers( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2674" end="2674"> use common_utils::{ request::RequestContent, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use self::transformers as stripe; use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData}; use crate::{ configs::settings, consts, core::{ errors::{self, CustomResult}, payments, }, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, domain, }, utils::{crypto, ByteSliceExt, BytesExt, OptionExt}, }; type Verify = dyn services::ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >; <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2692" end="2712"> fn build_request( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutRecipientAccountType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PayoutRecipientAccountType::get_headers( self, req, connectors, )?) .set_body(types::PayoutRecipientAccountType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2683" end="2690"> fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::StripeConnectRecipientAccountCreateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673"> fn get_url( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_customer_id = req.get_connector_customer_id()?; Ok(format!( "{}v1/accounts/{}/external_accounts", connectors.stripe.base_url, connector_customer_id )) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2659" end="2661"> fn get_content_type(&self) -> &'static str { self.common_get_content_type() } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2523" end="2541"> fn build_request( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutFulfillType::get_headers( self, req, connectors, )?) .set_body(types::PayoutFulfillType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1338" end="1355"> fn build_request( &self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } <file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="226" end="226"> pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/utils.rs<|crate|> router<|connector|> utils anchor=default kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1103" end="1111"> fn default() -> Self { let data = types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0), browser_info: None, amount: Some(100), currency: enums::Currency::USD, }; Self(data) } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1102" end="1102"> use router::{ configs::settings::Settings, core::{errors::ConnectorError, payments}, db::StorageImpl, routes, services::{ self, connector_integration_interface::{BoxedConnectorIntegrationInterface, ConnectorEnum}, }, types::{self, storage::enums, AccessToken, MinorUnit, PaymentAddress, RouterData}, }; <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1136" end="1152"> pub fn get_connector_metadata( response: Result<types::PaymentsResponseData, types::ErrorResponse>, ) -> Option<serde_json::Value> { match response { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: _, redirection_data: _, mandate_reference: _, connector_metadata, network_txn_id: _, connector_response_reference_id: _, incremental_authorization_allowed: _, charges: _, }) => connector_metadata, _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1114" end="1134"> pub fn get_connector_transaction_id( response: Result<types::PaymentsResponseData, types::ErrorResponse>, ) -> Option<String> { match response { Ok(types::PaymentsResponseData::TransactionResponse { resource_id, .. }) => { resource_id.get_connector_transaction_id().ok() } Ok(types::PaymentsResponseData::SessionResponse { .. }) => None, Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, Ok(types::PaymentsResponseData::PreProcessingResponse { .. }) => None, Ok(types::PaymentsResponseData::ConnectorCustomerResponse { .. }) => None, Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None, Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None, Ok(types::PaymentsResponseData::SessionUpdateResponse { .. }) => None, Err(_) => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1089" end="1099"> fn default() -> Self { let data = types::ConnectorCustomerData { payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0), description: None, email: Email::from_str("test@juspay.in").ok(), phone: None, name: None, preprocessing_id: None, }; Self(data) } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1062" end="1085"> fn default() -> Self { let data = types::RefundsData { payment_amount: 100, minor_payment_amount: MinorUnit::new(100), currency: enums::Currency::USD, refund_id: uuid::Uuid::new_v4().to_string(), connector_transaction_id: String::new(), refund_amount: 100, minor_refund_amount: MinorUnit::new(100), webhook_url: None, connector_metadata: None, refund_connector_metadata: None, reason: Some("Customer returned product".to_string()), connector_refund_id: None, browser_info: None, split_refunds: None, integrity_object: None, refund_status: enums::RefundStatus::Pending, merchant_account_id: None, merchant_config_currency: None, capture_method: None, }; Self(data) } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="166" end="177"> async fn sync_payment( &self, payment_data: Option<types::PaymentsSyncData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsSyncRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( payment_data.unwrap_or_else(|| PaymentSyncType::default().0), payment_info, ); Box::pin(call_connector(request, integration)).await } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="924" end="924"> pub struct CCardType(pub types::domain::Card); <file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207"> pub struct PaymentMethodData { pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539"> pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/utils.rs<|crate|> router<|connector|> utils anchor=default kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1103" end="1111"> fn default() -> Self { let data = types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0), browser_info: None, amount: Some(100), currency: enums::Currency::USD, }; Self(data) } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1102" end="1102"> use router::{ configs::settings::Settings, core::{errors::ConnectorError, payments}, db::StorageImpl, routes, services::{ self, connector_integration_interface::{BoxedConnectorIntegrationInterface, ConnectorEnum}, }, types::{self, storage::enums, AccessToken, MinorUnit, PaymentAddress, RouterData}, }; <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1136" end="1152"> pub fn get_connector_metadata( response: Result<types::PaymentsResponseData, types::ErrorResponse>, ) -> Option<serde_json::Value> { match response { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: _, redirection_data: _, mandate_reference: _, connector_metadata, network_txn_id: _, connector_response_reference_id: _, incremental_authorization_allowed: _, charges: _, }) => connector_metadata, _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1114" end="1134"> pub fn get_connector_transaction_id( response: Result<types::PaymentsResponseData, types::ErrorResponse>, ) -> Option<String> { match response { Ok(types::PaymentsResponseData::TransactionResponse { resource_id, .. }) => { resource_id.get_connector_transaction_id().ok() } Ok(types::PaymentsResponseData::SessionResponse { .. }) => None, Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, Ok(types::PaymentsResponseData::PreProcessingResponse { .. }) => None, Ok(types::PaymentsResponseData::ConnectorCustomerResponse { .. }) => None, Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None, Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None, Ok(types::PaymentsResponseData::SessionUpdateResponse { .. }) => None, Err(_) => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1089" end="1099"> fn default() -> Self { let data = types::ConnectorCustomerData { payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0), description: None, email: Email::from_str("test@juspay.in").ok(), phone: None, name: None, preprocessing_id: None, }; Self(data) } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1062" end="1085"> fn default() -> Self { let data = types::RefundsData { payment_amount: 100, minor_payment_amount: MinorUnit::new(100), currency: enums::Currency::USD, refund_id: uuid::Uuid::new_v4().to_string(), connector_transaction_id: String::new(), refund_amount: 100, minor_refund_amount: MinorUnit::new(100), webhook_url: None, connector_metadata: None, refund_connector_metadata: None, reason: Some("Customer returned product".to_string()), connector_refund_id: None, browser_info: None, split_refunds: None, integrity_object: None, refund_status: enums::RefundStatus::Pending, merchant_account_id: None, merchant_config_currency: None, capture_method: None, }; Self(data) } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="166" end="177"> async fn sync_payment( &self, payment_data: Option<types::PaymentsSyncData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsSyncRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( payment_data.unwrap_or_else(|| PaymentSyncType::default().0), payment_info, ); Box::pin(call_connector(request, integration)).await } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="924" end="924"> pub struct CCardType(pub types::domain::Card); <file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207"> pub struct PaymentMethodData { pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/types/domain/user.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1256" end="1265"> pub fn new(name: String) -> UserResult<Self> { let is_empty_or_whitespace = name.trim().is_empty(); let is_too_long = name.graphemes(true).count() > consts::user_role::MAX_ROLE_NAME_LENGTH; if is_empty_or_whitespace || is_too_long || name.contains(' ') { Err(UserErrors::RoleNameParsingError.into()) } else { Ok(Self(name.to_lowercase())) } } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1255" end="1255"> use api_models::{ admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api, }; use diesel_models::{ enums::{TotpStatus, UserRoleVersion, UserStatus}, organization::{self as diesel_org, Organization, OrganizationBridge}, user as storage_user, user_role::{UserRole, UserRoleNew}, }; use crate::{ consts, core::{ admin, errors::{UserErrors, UserResult}, }, db::GlobalStorageInterface, routes::SessionState, services::{self, authentication::UserFromToken}, types::{domain, transformers::ForeignFrom}, utils::user::password, }; pub use decision_manager::*; <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1276" end="1290"> pub fn generate_new() -> Self { let mut rand = rand::thread_rng(); let recovery_codes = (0..consts::user::RECOVERY_CODES_COUNT) .map(|_| { let code_part_1 = Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2); let code_part_2 = Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2); Secret::new(format!("{}-{}", code_part_1, code_part_2)) }) .collect::<Vec<_>>(); Self(recovery_codes) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1267" end="1269"> pub fn get_role_name(self) -> String { self.0 } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1244" end="1249"> fn foreign_from(value: UserStatus) -> Self { match value { UserStatus::Active => Self::Active, UserStatus::InvitationSent => Self::InvitationSent, } } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1211" end="1240"> pub async fn decrypt_and_get_totp_secret( &self, state: &SessionState, ) -> UserResult<Option<Secret<String>>> { if self.0.totp_secret.is_none() { return Ok(None); } let key_manager_state = &state.into(); let user_key_store = state .global_store .get_user_key_store_by_user_id( key_manager_state, self.get_user_id(), &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError)?; Ok(domain_types::crypto_operation::<String, masking::WithType>( key_manager_state, type_name!(storage_user::User), domain_types::CryptoOperation::DecryptOptional(self.0.totp_secret.clone()), Identifier::User(user_key_store.user_id.clone()), user_key_store.key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) .change_context(UserErrors::InternalServerError)? .map(Encryptable::into_inner)) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="318" end="322"> fn from(_value: InviteeUserRequestWithInvitedUserToken) -> Self { let new_organization = api_org::OrganizationNew::new(None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="632" end="644"> fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> { let company_name = Some(UserCompanyName::new(value.company_name.clone())?); let merchant_id = MerchantId::new(value.company_name.clone())?; let new_organization = NewUserOrganization::try_from(value)?; let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE); Ok(Self { company_name, merchant_id: id_type::MerchantId::try_from(merchant_id)?, new_organization, product_type, }) } <file_sep path="hyperswitch/crates/router/src/core/errors/user.rs" role="context" start="10" end="113"> pub enum UserErrors { #[error("User InternalServerError")] InternalServerError, #[error("InvalidCredentials")] InvalidCredentials, #[error("UserNotFound")] UserNotFound, #[error("UserExists")] UserExists, #[error("LinkInvalid")] LinkInvalid, #[error("UnverifiedUser")] UnverifiedUser, #[error("InvalidOldPassword")] InvalidOldPassword, #[error("EmailParsingError")] EmailParsingError, #[error("NameParsingError")] NameParsingError, #[error("PasswordParsingError")] PasswordParsingError, #[error("UserAlreadyVerified")] UserAlreadyVerified, #[error("CompanyNameParsingError")] CompanyNameParsingError, #[error("MerchantAccountCreationError: {0}")] MerchantAccountCreationError(String), #[error("InvalidEmailError")] InvalidEmailError, #[error("DuplicateOrganizationId")] DuplicateOrganizationId, #[error("MerchantIdNotFound")] MerchantIdNotFound, #[error("MetadataAlreadySet")] MetadataAlreadySet, #[error("InvalidRoleId")] InvalidRoleId, #[error("InvalidRoleOperation")] InvalidRoleOperation, #[error("IpAddressParsingFailed")] IpAddressParsingFailed, #[error("InvalidMetadataRequest")] InvalidMetadataRequest, #[error("MerchantIdParsingError")] MerchantIdParsingError, #[error("ChangePasswordError")] ChangePasswordError, #[error("InvalidDeleteOperation")] InvalidDeleteOperation, #[error("MaxInvitationsError")] MaxInvitationsError, #[error("RoleNotFound")] RoleNotFound, #[error("InvalidRoleOperationWithMessage")] InvalidRoleOperationWithMessage(String), #[error("RoleNameParsingError")] RoleNameParsingError, #[error("RoleNameAlreadyExists")] RoleNameAlreadyExists, #[error("TotpNotSetup")] TotpNotSetup, #[error("InvalidTotp")] InvalidTotp, #[error("TotpRequired")] TotpRequired, #[error("InvalidRecoveryCode")] InvalidRecoveryCode, #[error("TwoFactorAuthRequired")] TwoFactorAuthRequired, #[error("TwoFactorAuthNotSetup")] TwoFactorAuthNotSetup, #[error("TOTP secret not found")] TotpSecretNotFound, #[error("User auth method already exists")] UserAuthMethodAlreadyExists, #[error("Invalid user auth method operation")] InvalidUserAuthMethodOperation, #[error("Auth config parsing error")] AuthConfigParsingError, #[error("Invalid SSO request")] SSOFailed, #[error("profile_id missing in JWT")] JwtProfileIdMissing, #[error("Maximum attempts reached for TOTP")] MaxTotpAttemptsReached, #[error("Maximum attempts reached for Recovery Code")] MaxRecoveryCodeAttemptsReached, #[error("Forbidden tenant id")] ForbiddenTenantId, #[error("Error Uploading file to Theme Storage")] ErrorUploadingFile, #[error("Error Retrieving file from Theme Storage")] ErrorRetrievingFile, #[error("Theme not found")] ThemeNotFound, #[error("Theme with lineage already exists")] ThemeAlreadyExists, #[error("Invalid field: {0} in lineage")] InvalidThemeLineage(String), #[error("Missing required field: email_config")] MissingEmailConfig, #[error("Invalid Auth Method Operation: {0}")] InvalidAuthMethodOperationWithMessage(String), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stax.rs<|crate|> router<|connector|> stax anchor=payment_method_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="78" end="82"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="77" end="77"> use router::types::{self, domain, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="112" end="121"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="84" end="107"> async fn create_customer_and_get_token() -> Option<String> { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( token_details(), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="63" end="76"> fn token_details() -> Option<types::PaymentMethodTokenizationData> { Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="57" end="61"> fn customer_details() -> Option<types::ConnectorCustomerData> { Some(types::ConnectorCustomerData { ..utils::CustomerType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="398" end="429"> async fn should_refund_succeeded_payment_multiple_times() { let payment_method_token = create_customer_and_get_token().await; let response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, payment_method_token.clone()), ) .await .unwrap(); //try refund for previous payment let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(Duration::from_secs(60)).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, payment_method_token.clone()), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="318" end="327"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/noon.rs<|crate|> router<|connector|> noon anchor=payment_method_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="45" end="50"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { currency: enums::Currency::AED, ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="44" end="44"> use router::types::{self, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="65" end="71"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="55" end="61"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="41" end="43"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="34" end="36"> fn get_name(&self) -> String { "noon".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="237" end="246"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="116" end="130"> async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/bluesnap.rs<|crate|> router<|connector|> bluesnap anchor=payment_method_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="41" end="46"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("test@gmail.com").unwrap()), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="40" end="40"> use router::types::{self, domain, storage::enums, ConnectorAuthType, PaymentAddress}; <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="72" end="78"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="47" end="65"> fn get_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("joseph".to_string())), last_name: Some(Secret::new("Doe".to_string())), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="37" end="39"> fn get_name(&self) -> String { "bluesnap".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="28" end="35"> fn get_auth_token(&self) -> ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .bluesnap .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="305" end="330"> async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_payment_info(), ) .await .unwrap(); let rsync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( rsync_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/paypal.rs<|crate|> router<|connector|> paypal anchor=get_payment_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="58" end="66"> fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4000020000000000").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="57" end="57"> use common_utils::types::MinorUnit; use router::types::{self, domain, storage::enums, AccessToken, ConnectorAuthType}; <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="81" end="100"> async fn should_capture_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = "".to_string(); let connector_meta = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .capture_payment( txn_id, Some(types::PaymentsCaptureData { connector_meta, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Pending); } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="71" end="77"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="51" end="56"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { access_token: get_access_token(), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="40" end="50"> fn get_access_token() -> Option<AccessToken> { let connector = PaypalTest {}; match connector.get_auth_token() { ConnectorAuthType::BodyKey { api_key, key1: _ } => Some(AccessToken { token: api_key, expires: 18600, }), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="187" end="221"> async fn should_refund_manually_captured_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = "".to_string(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id, Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207"> pub struct PaymentMethodData { pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stripe.rs<|crate|> router<|connector|> stripe anchor=get_payment_authorize_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="38" end="46"> fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4242424242424242").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="37" end="37"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="58" end="64"> async fn should_make_payment() { let response = Stripe {} .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="49" end="55"> async fn should_only_authorize_payment() { let response = Stripe {} .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="33" end="35"> fn get_name(&self) -> String { "stripe".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="24" end="31"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .stripe .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="344" end="356"> async fn should_refund_succeeded_payment_multiple_times() { let connector = Stripe {}; connector .make_payment_and_multiple_refund( get_payment_authorize_data(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await; } <file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207"> pub struct PaymentMethodData { pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stripe.rs<|crate|> router<|connector|> stripe anchor=get_payment_authorize_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="38" end="46"> fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4242424242424242").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="37" end="37"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="58" end="64"> async fn should_make_payment() { let response = Stripe {} .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="49" end="55"> async fn should_only_authorize_payment() { let response = Stripe {} .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="33" end="35"> fn get_name(&self) -> String { "stripe".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="24" end="31"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .stripe .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/stripe.rs" role="context" start="344" end="356"> async fn should_refund_succeeded_payment_multiple_times() { let connector = Stripe {}; connector .make_payment_and_multiple_refund( get_payment_authorize_data(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await; }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/nexinets.rs<|crate|> router<|connector|> nexinets anchor=payment_method_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/nexinets.rs" role="context" start="42" end="52"> fn payment_method_details() -> Option<PaymentsAuthorizeData> { Some(PaymentsAuthorizeData { currency: diesel_models::enums::Currency::EUR, payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("374111111111111").unwrap(), ..utils::CCardType::default().0 }), router_return_url: Some("https://google.com".to_string()), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/nexinets.rs" role="context" start="41" end="41"> use router::types::{self, domain, storage::enums, PaymentsAuthorizeData}; <file_sep path="hyperswitch/crates/router/tests/connectors/nexinets.rs" role="context" start="66" end="84"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = "".to_string(); let connector_meta = utils::get_connector_metadata(response.response); let capture_data = types::PaymentsCaptureData { connector_meta, currency: diesel_models::enums::Currency::EUR, ..utils::PaymentCaptureType::default().0 }; let capture_response = CONNECTOR .capture_payment(connector_payment_id, Some(capture_data), None) .await .unwrap(); assert_eq!(capture_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/nexinets.rs" role="context" start="56" end="62"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), None) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/nexinets.rs" role="context" start="37" end="39"> fn get_name(&self) -> String { "nexinets".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/nexinets.rs" role="context" start="28" end="35"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .nexinets .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/nexinets.rs" role="context" start="337" end="359"> async fn should_sync_auto_captured_payment() { let cap_response = CONNECTOR .make_payment(payment_method_details(), None) .await .unwrap(); assert_eq!(cap_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(cap_response.response.clone()).unwrap(); let connector_meta = utils::get_connector_metadata(cap_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), capture_method: Some(enums::CaptureMethod::Automatic), connector_meta, ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/nexinets.rs" role="context" start="144" end="167"> async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = "".to_string(); let connector_meta = utils::get_connector_metadata(response.response); let response = CONNECTOR .void_payment( connector_payment_id, Some(types::PaymentsCancelData { connector_meta, amount: Some(100), currency: Some(diesel_models::enums::Currency::EUR), ..utils::PaymentCancelType::default().0 }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Voided); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/fiserv.rs<|crate|> router<|connector|> fiserv anchor=payment_method_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="43" end="61"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4005550000000019").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="42" end="42"> use masking::Secret; use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="76" end="82"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="63" end="68"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { connector_meta_data: Some(json!({"terminalId": "10000001"})), ..utils::PaymentInfo::with_default_billing_name() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="38" end="40"> fn get_connector_meta(&self) -> Option<serde_json::Value> { Some(json!({"terminalId": "10000001"})) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="35" end="37"> fn get_name(&self) -> String { "fiserv".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="271" end="280"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="143" end="157"> async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("TIMEOUT".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } <file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207"> pub struct PaymentMethodData { pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539"> pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/fiserv.rs<|crate|> router<|connector|> fiserv anchor=payment_method_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="43" end="61"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4005550000000019").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="42" end="42"> use masking::Secret; use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="76" end="82"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="63" end="68"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { connector_meta_data: Some(json!({"terminalId": "10000001"})), ..utils::PaymentInfo::with_default_billing_name() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="38" end="40"> fn get_connector_meta(&self) -> Option<serde_json::Value> { Some(json!({"terminalId": "10000001"})) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="35" end="37"> fn get_name(&self) -> String { "fiserv".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="271" end="280"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="143" end="157"> async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("TIMEOUT".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/cybersource.rs<|crate|> router<|connector|> cybersource anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="37" end="63"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="36" end="36"> use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="72" end="81"> async fn should_only_authorize_payment() { let response = Cybersource {} .authorize_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="64" end="70"> fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { currency: enums::Currency::USD, email: Some(Email::from_str("abc@gmail.com").unwrap()), ..PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="32" end="34"> fn get_name(&self) -> String { "cybersource".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="24" end="31"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .cybersource .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="158" end="181"> async fn should_fail_payment_for_invalid_exp_month() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("13".to_string()), ..utils::CCardType::default().0 }), ..get_default_payment_authorize_data().unwrap() }), get_default_payment_info(), ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!( x.message, "Declined - One or more fields in the request contains invalid data", ); assert_eq!( x.reason, Some("paymentInformation.card.expirationMonth : INVALID_DATA".to_string()) ); } <file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="83" end="92"> async fn should_make_payment() { let response = Cybersource {} .make_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Pending); } <file_sep path="hyperswitch/crates/router/tests/macros.rs" role="context" start="17" end="21"> struct Address { line1: String, zip: String, city: String, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund -----------------------
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/payme.rs<|crate|> router<|connector|> payme anchor=payment_method_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="78" end="108"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, }]), router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), email: Some(Email::from_str("test@gmail.com").unwrap()), payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_cvc: Secret::new("123".to_string()), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), ..utils::CCardType::default().0 }), amount: 1000, ..PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="77" end="77"> use common_utils::{pii::Email, types::MinorUnit}; use diesel_models::types::OrderDetailsWithAmount; use masking::Secret; use router::types::{self, domain, storage::enums, PaymentAddress}; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentAuthorizeType}, }; <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="123" end="129"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="113" end="119"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="44" end="76"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { city: None, country: None, line1: None, line2: None, line3: None, zip: None, state: None, first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), }), phone: None, email: None, }), None, None, )), auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token: None, #[cfg(feature = "payouts")] currency: None, #[cfg(feature = "payouts")] payout_method_data: None, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="37" end="39"> fn get_name(&self) -> String { "payme".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="237" end="260"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=get_request_body kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2683" end="2690"> fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::StripeConnectRecipientAccountCreateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2682" end="2682"> use common_utils::{ request::RequestContent, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use stripe::auth_headers; use self::transformers as stripe; use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData}; use crate::{ configs::settings, consts, core::{ errors::{self, CustomResult}, payments, }, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, domain, }, utils::{crypto, ByteSliceExt, BytesExt, OptionExt}, }; type Verify = dyn services::ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >; <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2714" end="2731"> fn handle_response( &self, data: &types::PayoutsRouterData<api::PoRecipientAccount>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoRecipientAccount>, errors::ConnectorError> { let response: stripe::StripeConnectRecipientAccountCreateResponse = res .response .parse_struct("StripeConnectRecipientAccountCreateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2692" end="2712"> fn build_request( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutRecipientAccountType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PayoutRecipientAccountType::get_headers( self, req, connectors, )?) .set_body(types::PayoutRecipientAccountType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2675" end="2681"> fn get_headers( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673"> fn get_url( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_customer_id = req.get_connector_customer_id()?; Ok(format!( "{}v1/accounts/{}/external_accounts", connectors.stripe.base_url, connector_customer_id )) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2438" end="2454"> fn build_request( &self, req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutCreateType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutCreateType::get_headers(self, req, connectors)?) .set_body(types::PayoutCreateType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="529" end="547"> fn build_request( &self, req: &types::PaymentsCaptureRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52"> pub const fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } <file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="226" end="226"> pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;
symbol_neighborhood