repo
stringclasses
4 values
file_path
stringlengths
6
193
extension
stringclasses
23 values
content
stringlengths
0
1.73M
token_count
int64
0
724k
__index_level_0__
int64
0
10.8k
hyperswitch
crates/router/src/services/api/generic_link_response.rs
.rs
use common_utils::errors::CustomResult; use error_stack::ResultExt; use hyperswitch_domain_models::api::{ GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData, GenericLinksData, }; use tera::{Context, Tera}; use super::build_secure_payment_link_html; use crate::core::errors; pub mod context; pub fn build_generic_link_html( boxed_generic_link_data: GenericLinksData, locale: String, ) -> CustomResult<String, errors::ApiErrorResponse> { match boxed_generic_link_data { GenericLinksData::ExpiredLink(link_data) => build_generic_expired_link_html(&link_data), GenericLinksData::PaymentMethodCollect(pm_collect_data) => { build_pm_collect_link_html(&pm_collect_data) } GenericLinksData::PaymentMethodCollectStatus(pm_collect_data) => { build_pm_collect_link_status_html(&pm_collect_data) } GenericLinksData::PayoutLink(payout_link_data) => { build_payout_link_html(&payout_link_data, locale.as_str()) } GenericLinksData::PayoutLinkStatus(pm_collect_data) => { build_payout_link_status_html(&pm_collect_data, locale.as_str()) } GenericLinksData::SecurePaymentLink(payment_link_data) => { build_secure_payment_link_html(payment_link_data) } } } pub fn build_generic_expired_link_html( link_data: &GenericExpiredLinkData, ) -> CustomResult<String, errors::ApiErrorResponse> { let mut tera = Tera::default(); let mut context = Context::new(); // Build HTML let html_template = include_str!("../../core/generic_link/expired_link/index.html").to_string(); let _ = tera.add_raw_template("generic_expired_link", &html_template); context.insert("title", &link_data.title); context.insert("message", &link_data.message); context.insert("theme", &link_data.theme); tera.render("generic_expired_link", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render expired link HTML template") } fn build_html_template( link_data: &GenericLinkFormData, document: &'static str, styles: &'static str, ) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> { let mut tera: Tera = Tera::default(); let mut context = Context::new(); // Insert dynamic context in CSS let css_dynamic_context = "{{ color_scheme }}"; let css_template = styles.to_string(); let final_css = format!("{}\n{}", css_dynamic_context, css_template); let _ = tera.add_raw_template("document_styles", &final_css); context.insert("color_scheme", &link_data.css_data); let css_style_tag = tera .render("document_styles", &context) .map(|css| format!("<style>{}</style>", css)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render CSS template")?; // Insert HTML context let html_template = document.to_string(); let _ = tera.add_raw_template("html_template", &html_template); context.insert("css_style_tag", &css_style_tag); Ok((tera, context)) } pub fn build_payout_link_html( link_data: &GenericLinkFormData, locale: &str, ) -> CustomResult<String, errors::ApiErrorResponse> { let document = include_str!("../../core/generic_link/payout_link/initiate/index.html"); let styles = include_str!("../../core/generic_link/payout_link/initiate/styles.css"); let (mut tera, mut context) = build_html_template(link_data, document, styles) .attach_printable("Failed to build context for payout link's HTML template")?; // Insert dynamic context in JS let script = include_str!("../../core/generic_link/payout_link/initiate/script.js"); let js_template = script.to_string(); let js_dynamic_context = "{{ script_data }}"; let final_js = format!("{}\n{}", js_dynamic_context, js_template); let _ = tera.add_raw_template("document_scripts", &final_js); context.insert("script_data", &link_data.js_data); context::insert_locales_in_context_for_payout_link(&mut context, locale); let js_script_tag = tera .render("document_scripts", &context) .map(|js| format!("<script>{}</script>", js)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render JS template")?; context.insert("js_script_tag", &js_script_tag); context.insert( "hyper_sdk_loader_script_tag", &format!( r#"<script src="{}" onload="initializePayoutSDK()"></script>"#, link_data.sdk_url ), ); // Render HTML template tera.render("html_template", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link's HTML template") } pub fn build_pm_collect_link_html( link_data: &GenericLinkFormData, ) -> CustomResult<String, errors::ApiErrorResponse> { let document = include_str!("../../core/generic_link/payment_method_collect/initiate/index.html"); let styles = include_str!("../../core/generic_link/payment_method_collect/initiate/styles.css"); let (mut tera, mut context) = build_html_template(link_data, document, styles) .attach_printable( "Failed to build context for payment method collect link's HTML template", )?; // Insert dynamic context in JS let script = include_str!("../../core/generic_link/payment_method_collect/initiate/script.js"); let js_template = script.to_string(); let js_dynamic_context = "{{ script_data }}"; let final_js = format!("{}\n{}", js_dynamic_context, js_template); let _ = tera.add_raw_template("document_scripts", &final_js); context.insert("script_data", &link_data.js_data); let js_script_tag = tera .render("document_scripts", &context) .map(|js| format!("<script>{}</script>", js)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render JS template")?; context.insert("js_script_tag", &js_script_tag); context.insert( "hyper_sdk_loader_script_tag", &format!( r#"<script src="{}" onload="initializeCollectSDK()"></script>"#, link_data.sdk_url ), ); // Render HTML template tera.render("html_template", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link's HTML template") } pub fn build_payout_link_status_html( link_data: &GenericLinkStatusData, locale: &str, ) -> CustomResult<String, errors::ApiErrorResponse> { let mut tera = Tera::default(); let mut context = Context::new(); // Insert dynamic context in CSS let css_dynamic_context = "{{ color_scheme }}"; let css_template = include_str!("../../core/generic_link/payout_link/status/styles.css").to_string(); let final_css = format!("{}\n{}", css_dynamic_context, css_template); let _ = tera.add_raw_template("payout_link_status_styles", &final_css); context.insert("color_scheme", &link_data.css_data); let css_style_tag = tera .render("payout_link_status_styles", &context) .map(|css| format!("<style>{}</style>", css)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link status CSS template")?; // Insert dynamic context in JS let js_dynamic_context = "{{ script_data }}"; let js_template = include_str!("../../core/generic_link/payout_link/status/script.js").to_string(); let final_js = format!("{}\n{}", js_dynamic_context, js_template); let _ = tera.add_raw_template("payout_link_status_script", &final_js); context.insert("script_data", &link_data.js_data); context::insert_locales_in_context_for_payout_link_status(&mut context, locale); let js_script_tag = tera .render("payout_link_status_script", &context) .map(|js| format!("<script>{}</script>", js)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link status JS template")?; // Build HTML let html_template = include_str!("../../core/generic_link/payout_link/status/index.html").to_string(); let _ = tera.add_raw_template("payout_status_link", &html_template); context.insert("css_style_tag", &css_style_tag); context.insert("js_script_tag", &js_script_tag); tera.render("payout_status_link", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link status HTML template") } pub fn build_pm_collect_link_status_html( link_data: &GenericLinkStatusData, ) -> CustomResult<String, errors::ApiErrorResponse> { let mut tera = Tera::default(); let mut context = Context::new(); // Insert dynamic context in CSS let css_dynamic_context = "{{ color_scheme }}"; let css_template = include_str!("../../core/generic_link/payment_method_collect/status/styles.css") .to_string(); let final_css = format!("{}\n{}", css_dynamic_context, css_template); let _ = tera.add_raw_template("pm_collect_link_status_styles", &final_css); context.insert("color_scheme", &link_data.css_data); let css_style_tag = tera .render("pm_collect_link_status_styles", &context) .map(|css| format!("<style>{}</style>", css)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link status CSS template")?; // Insert dynamic context in JS let js_dynamic_context = "{{ collect_link_status_context }}"; let js_template = include_str!("../../core/generic_link/payment_method_collect/status/script.js").to_string(); let final_js = format!("{}\n{}", js_dynamic_context, js_template); let _ = tera.add_raw_template("pm_collect_link_status_script", &final_js); context.insert("collect_link_status_context", &link_data.js_data); let js_script_tag = tera .render("pm_collect_link_status_script", &context) .map(|js| format!("<script>{}</script>", js)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link status JS template")?; // Build HTML let html_template = include_str!("../../core/generic_link/payment_method_collect/status/index.html") .to_string(); let _ = tera.add_raw_template("payment_method_collect_status_link", &html_template); context.insert("css_style_tag", &css_style_tag); context.insert("js_script_tag", &js_script_tag); tera.render("payment_method_collect_status_link", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link status HTML template") }
2,472
1,305
hyperswitch
crates/router/src/services/api/generic_link_response/context.rs
.rs
use rust_i18n::t; use tera::Context; pub fn insert_locales_in_context_for_payout_link(context: &mut Context, locale: &str) { let i18n_payout_link_title = t!("payout_link.initiate.title", locale = locale); let i18n_january = t!("months.january", locale = locale); let i18n_february = t!("months.february", locale = locale); let i18n_march = t!("months.march", locale = locale); let i18n_april = t!("months.april", locale = locale); let i18n_may = t!("months.may", locale = locale); let i18n_june = t!("months.june", locale = locale); let i18n_july = t!("months.july", locale = locale); let i18n_august = t!("months.august", locale = locale); let i18n_september = t!("months.september", locale = locale); let i18n_october = t!("months.october", locale = locale); let i18n_november = t!("months.november", locale = locale); let i18n_december = t!("months.december", locale = locale); let i18n_not_allowed = t!("payout_link.initiate.not_allowed", locale = locale); let i18n_am = t!("time.am", locale = locale); let i18n_pm = t!("time.pm", locale = locale); context.insert("i18n_payout_link_title", &i18n_payout_link_title); context.insert("i18n_january", &i18n_january); context.insert("i18n_february", &i18n_february); context.insert("i18n_march", &i18n_march); context.insert("i18n_april", &i18n_april); context.insert("i18n_may", &i18n_may); context.insert("i18n_june", &i18n_june); context.insert("i18n_july", &i18n_july); context.insert("i18n_august", &i18n_august); context.insert("i18n_september", &i18n_september); context.insert("i18n_october", &i18n_october); context.insert("i18n_november", &i18n_november); context.insert("i18n_december", &i18n_december); context.insert("i18n_not_allowed", &i18n_not_allowed); context.insert("i18n_am", &i18n_am); context.insert("i18n_pm", &i18n_pm); } pub fn insert_locales_in_context_for_payout_link_status(context: &mut Context, locale: &str) { let i18n_payout_link_status_title = t!("payout_link.status.title", locale = locale); let i18n_success_text = t!("payout_link.status.text.success", locale = locale); let i18n_success_message = t!("payout_link.status.message.success", locale = locale); let i18n_pending_text = t!("payout_link.status.text.processing", locale = locale); let i18n_pending_message = t!("payout_link.status.message.processing", locale = locale); let i18n_failed_text = t!("payout_link.status.text.failed", locale = locale); let i18n_failed_message = t!("payout_link.status.message.failed", locale = locale); let i18n_ref_id_text = t!("payout_link.status.info.ref_id", locale = locale); let i18n_error_code_text = t!("payout_link.status.info.error_code", locale = locale); let i18n_error_message = t!("payout_link.status.info.error_message", locale = locale); let i18n_redirecting_text = t!( "payout_link.status.redirection_text.redirecting", locale = locale ); let i18n_redirecting_in_text = t!( "payout_link.status.redirection_text.redirecting_in", locale = locale ); let i18n_seconds_text = t!( "payout_link.status.redirection_text.seconds", locale = locale ); context.insert( "i18n_payout_link_status_title", &i18n_payout_link_status_title, ); context.insert("i18n_success_text", &i18n_success_text); context.insert("i18n_success_message", &i18n_success_message); context.insert("i18n_pending_text", &i18n_pending_text); context.insert("i18n_pending_message", &i18n_pending_message); context.insert("i18n_failed_text", &i18n_failed_text); context.insert("i18n_failed_message", &i18n_failed_message); context.insert("i18n_ref_id_text", &i18n_ref_id_text); context.insert("i18n_error_code_text", &i18n_error_code_text); context.insert("i18n_error_message", &i18n_error_message); context.insert("i18n_redirecting_text", &i18n_redirecting_text); context.insert("i18n_redirecting_in_text", &i18n_redirecting_in_text); context.insert("i18n_seconds_text", &i18n_seconds_text); }
1,281
1,306
hyperswitch
crates/router/src/services/email/types.rs
.rs
use api_models::user::dashboard_metadata::ProdIntent; use common_enums::{EntityType, MerchantProductType}; use common_utils::{errors::CustomResult, pii, types::theme::EmailThemeConfig}; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; use masking::{ExposeInterface, Secret}; use crate::{configs, consts, routes::SessionState}; #[cfg(feature = "olap")] use crate::{ core::errors::{UserErrors, UserResult}, services::jwt, types::domain, }; pub enum EmailBody { Verify { link: String, entity_name: String, entity_logo_url: String, primary_color: String, background_color: String, foreground_color: String, }, Reset { link: String, user_name: String, entity_name: String, entity_logo_url: String, primary_color: String, background_color: String, foreground_color: String, }, MagicLink { link: String, user_name: String, entity_name: String, entity_logo_url: String, primary_color: String, background_color: String, foreground_color: String, }, InviteUser { link: String, user_name: String, entity_name: String, entity_logo_url: String, primary_color: String, background_color: String, foreground_color: String, }, AcceptInviteFromEmail { link: String, user_name: String, entity_name: String, entity_logo_url: String, primary_color: String, background_color: String, foreground_color: String, }, BizEmailProd { user_name: String, poc_email: String, legal_business_name: String, business_location: String, business_website: String, product_type: MerchantProductType, }, ReconActivation { user_name: String, }, ProFeatureRequest { feature_name: String, merchant_id: common_utils::id_type::MerchantId, user_name: String, user_email: String, }, ApiKeyExpiryReminder { expires_in: u8, api_key_name: String, prefix: String, }, WelcomeToCommunity, } pub mod html { use crate::services::email::types::EmailBody; pub fn get_html_body(email_body: EmailBody) -> String { match email_body { EmailBody::Verify { link, entity_name, entity_logo_url, primary_color, background_color, foreground_color, } => { format!( include_str!("assets/verify.html"), link = link, entity_name = entity_name, entity_logo_url = entity_logo_url, primary_color = primary_color, background_color = background_color, foreground_color = foreground_color ) } EmailBody::Reset { link, user_name, entity_name, entity_logo_url, primary_color, background_color, foreground_color, } => { format!( include_str!("assets/reset.html"), link = link, username = user_name, entity_name = entity_name, entity_logo_url = entity_logo_url, primary_color = primary_color, background_color = background_color, foreground_color = foreground_color ) } EmailBody::MagicLink { link, user_name, entity_name, entity_logo_url, primary_color, background_color, foreground_color, } => { format!( include_str!("assets/magic_link.html"), username = user_name, link = link, entity_name = entity_name, entity_logo_url = entity_logo_url, primary_color = primary_color, background_color = background_color, foreground_color = foreground_color ) } EmailBody::InviteUser { link, user_name, entity_name, entity_logo_url, primary_color, background_color, foreground_color, } => { format!( include_str!("assets/invite.html"), username = user_name, link = link, entity_name = entity_name, entity_logo_url = entity_logo_url, primary_color = primary_color, background_color = background_color, foreground_color = foreground_color ) } // TODO: Change the linked html for accept invite from email EmailBody::AcceptInviteFromEmail { link, user_name, entity_name, entity_logo_url, primary_color, background_color, foreground_color, } => { format!( include_str!("assets/invite.html"), username = user_name, link = link, entity_name = entity_name, entity_logo_url = entity_logo_url, primary_color = primary_color, background_color = background_color, foreground_color = foreground_color ) } EmailBody::ReconActivation { user_name } => { format!( include_str!("assets/recon_activation.html"), username = user_name, ) } EmailBody::BizEmailProd { user_name, poc_email, legal_business_name, business_location, business_website, product_type, } => { format!( include_str!("assets/bizemailprod.html"), poc_email = poc_email, legal_business_name = legal_business_name, business_location = business_location, business_website = business_website, username = user_name, product_type = product_type ) } EmailBody::ProFeatureRequest { feature_name, merchant_id, user_name, user_email, } => format!( "Dear Hyperswitch Support Team, Dashboard Pro Feature Request, Feature name : {feature_name} Merchant ID : {} Merchant Name : {user_name} Email : {user_email} (note: This is an auto generated email. Use merchant email for any further communications)", merchant_id.get_string_repr() ), EmailBody::ApiKeyExpiryReminder { expires_in, api_key_name, prefix, } => format!( include_str!("assets/api_key_expiry_reminder.html"), api_key_name = api_key_name, prefix = prefix, expires_in = expires_in, ), EmailBody::WelcomeToCommunity => { include_str!("assets/welcome_to_community.html").to_string() } } } } #[derive(serde::Serialize, serde::Deserialize)] pub struct EmailToken { email: String, flow: domain::Origin, exp: u64, entity: Option<Entity>, } #[derive(serde::Serialize, serde::Deserialize, Clone)] pub struct Entity { pub entity_id: String, pub entity_type: EntityType, } impl Entity { pub fn get_entity_type(&self) -> EntityType { self.entity_type } pub fn get_entity_id(&self) -> &str { &self.entity_id } } impl EmailToken { pub async fn new_token( email: domain::UserEmail, entity: Option<Entity>, flow: domain::Origin, settings: &configs::Settings, ) -> UserResult<String> { let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(expiration_duration)?.as_secs(); let token_payload = Self { email: email.get_secret().expose(), flow, exp, entity, }; jwt::generate_jwt(&token_payload, settings).await } pub fn get_email(&self) -> UserResult<domain::UserEmail> { pii::Email::try_from(self.email.clone()) .change_context(UserErrors::InternalServerError) .and_then(domain::UserEmail::from_pii_email) } pub fn get_entity(&self) -> Option<&Entity> { self.entity.as_ref() } pub fn get_flow(&self) -> domain::Origin { self.flow.clone() } } pub fn get_link_with_token( base_url: impl std::fmt::Display, token: impl std::fmt::Display, action: impl std::fmt::Display, auth_id: &Option<impl std::fmt::Display>, theme_id: &Option<impl std::fmt::Display>, ) -> String { let mut email_url = format!("{base_url}/user/{action}?token={token}"); if let Some(auth_id) = auth_id { email_url = format!("{email_url}&auth_id={auth_id}"); } if let Some(theme_id) = theme_id { email_url = format!("{email_url}&theme_id={theme_id}"); } email_url } pub fn get_base_url(state: &SessionState) -> &str { if !state.conf.multitenancy.enabled { &state.conf.user.base_url } else { &state.tenant.user.control_center_url } } pub struct VerifyEmail { pub recipient_email: domain::UserEmail, pub settings: std::sync::Arc<configs::Settings>, pub auth_id: Option<String>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } /// Currently only HTML is supported #[async_trait::async_trait] impl EmailData for VerifyEmail { async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), None, domain::Origin::VerifyEmail, &self.settings, ) .await .change_context(EmailError::TokenGenerationFailure)?; let verify_email_link = get_link_with_token( base_url, token, "verify_email", &self.auth_id, &self.theme_id, ); let body = html::get_html_body(EmailBody::Verify { link: verify_email_link, entity_name: self.theme_config.entity_name.clone(), entity_logo_url: self.theme_config.entity_logo_url.clone(), primary_color: self.theme_config.primary_color.clone(), background_color: self.theme_config.background_color.clone(), foreground_color: self.theme_config.foreground_color.clone(), }); Ok(EmailContents { subject: format!( "Welcome to the {} community!", self.theme_config.entity_name ), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct ResetPassword { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, pub settings: std::sync::Arc<configs::Settings>, pub auth_id: Option<String>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for ResetPassword { async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), None, domain::Origin::ResetPassword, &self.settings, ) .await .change_context(EmailError::TokenGenerationFailure)?; let reset_password_link = get_link_with_token( base_url, token, "set_password", &self.auth_id, &self.theme_id, ); let body = html::get_html_body(EmailBody::Reset { link: reset_password_link, user_name: self.user_name.clone().get_secret().expose(), entity_name: self.theme_config.entity_name.clone(), entity_logo_url: self.theme_config.entity_logo_url.clone(), primary_color: self.theme_config.primary_color.clone(), background_color: self.theme_config.background_color.clone(), foreground_color: self.theme_config.foreground_color.clone(), }); Ok(EmailContents { subject: format!( "Get back to {} - Reset Your Password Now!", self.theme_config.entity_name ), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct MagicLink { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, pub settings: std::sync::Arc<configs::Settings>, pub auth_id: Option<String>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for MagicLink { async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), None, domain::Origin::MagicLink, &self.settings, ) .await .change_context(EmailError::TokenGenerationFailure)?; let magic_link_login = get_link_with_token( base_url, token, "verify_email", &self.auth_id, &self.theme_id, ); let body = html::get_html_body(EmailBody::MagicLink { link: magic_link_login, user_name: self.user_name.clone().get_secret().expose(), entity_name: self.theme_config.entity_name.clone(), entity_logo_url: self.theme_config.entity_logo_url.clone(), primary_color: self.theme_config.primary_color.clone(), background_color: self.theme_config.background_color.clone(), foreground_color: self.theme_config.foreground_color.clone(), }); Ok(EmailContents { subject: format!( "Unlock {}: Use Your Magic Link to Sign In", self.theme_config.entity_name ), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct InviteUser { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, pub settings: std::sync::Arc<configs::Settings>, pub entity: Entity, pub auth_id: Option<String>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for InviteUser { async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), Some(self.entity.clone()), domain::Origin::AcceptInvitationFromEmail, &self.settings, ) .await .change_context(EmailError::TokenGenerationFailure)?; let invite_user_link = get_link_with_token( base_url, token, "accept_invite_from_email", &self.auth_id, &self.theme_id, ); let body = html::get_html_body(EmailBody::AcceptInviteFromEmail { link: invite_user_link, user_name: self.user_name.clone().get_secret().expose(), entity_name: self.theme_config.entity_name.clone(), entity_logo_url: self.theme_config.entity_logo_url.clone(), primary_color: self.theme_config.primary_color.clone(), background_color: self.theme_config.background_color.clone(), foreground_color: self.theme_config.foreground_color.clone(), }); Ok(EmailContents { subject: format!( "You have been invited to join {} Community!", self.theme_config.entity_name ), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct ReconActivation { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, pub subject: &'static str, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for ReconActivation { async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let body = html::get_html_body(EmailBody::ReconActivation { user_name: self.user_name.clone().get_secret().expose(), }); Ok(EmailContents { subject: self.subject.to_string(), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct BizEmailProd { pub recipient_email: domain::UserEmail, pub user_name: Secret<String>, pub poc_email: Secret<String>, pub legal_business_name: String, pub business_location: String, pub business_website: String, pub settings: std::sync::Arc<configs::Settings>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, pub product_type: MerchantProductType, } impl BizEmailProd { pub fn new( state: &SessionState, data: ProdIntent, theme_id: Option<String>, theme_config: EmailThemeConfig, ) -> UserResult<Self> { Ok(Self { recipient_email: domain::UserEmail::from_pii_email( state.conf.email.prod_intent_recipient_email.clone(), )?, settings: state.conf.clone(), user_name: data.poc_name.unwrap_or_default().into(), poc_email: data.poc_email.unwrap_or_default(), legal_business_name: data.legal_business_name.unwrap_or_default(), business_location: data .business_location .unwrap_or(common_enums::CountryAlpha2::AD) .to_string(), business_website: data.business_website.unwrap_or_default(), theme_id, theme_config, product_type: data.product_type, }) } } #[async_trait::async_trait] impl EmailData for BizEmailProd { async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let body = html::get_html_body(EmailBody::BizEmailProd { user_name: self.user_name.clone().expose(), poc_email: self.poc_email.clone().expose(), legal_business_name: self.legal_business_name.clone(), business_location: self.business_location.clone(), business_website: self.business_website.clone(), product_type: self.product_type, }); Ok(EmailContents { subject: "New Prod Intent".to_string(), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct ProFeatureRequest { pub recipient_email: domain::UserEmail, pub feature_name: String, pub merchant_id: common_utils::id_type::MerchantId, pub user_name: domain::UserName, pub user_email: domain::UserEmail, pub subject: String, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for ProFeatureRequest { async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let recipient = self.recipient_email.clone().into_inner(); let body = html::get_html_body(EmailBody::ProFeatureRequest { user_name: self.user_name.clone().get_secret().expose(), feature_name: self.feature_name.clone(), merchant_id: self.merchant_id.clone(), user_email: self.user_email.clone().get_secret().expose(), }); Ok(EmailContents { subject: self.subject.clone(), body: external_services::email::IntermediateString::new(body), recipient, }) } } pub struct ApiKeyExpiryReminder { pub recipient_email: domain::UserEmail, pub subject: &'static str, pub expires_in: u8, pub api_key_name: String, pub prefix: String, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for ApiKeyExpiryReminder { async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let recipient = self.recipient_email.clone().into_inner(); let body = html::get_html_body(EmailBody::ApiKeyExpiryReminder { expires_in: self.expires_in, api_key_name: self.api_key_name.clone(), prefix: self.prefix.clone(), }); Ok(EmailContents { subject: self.subject.to_string(), body: external_services::email::IntermediateString::new(body), recipient, }) } } pub struct WelcomeToCommunity { pub recipient_email: domain::UserEmail, } #[async_trait::async_trait] impl EmailData for WelcomeToCommunity { async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let body = html::get_html_body(EmailBody::WelcomeToCommunity); Ok(EmailContents { subject: "Thank you for signing up on Hyperswitch Dashboard!".to_string(), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } }
4,508
1,307
hyperswitch
crates/router/src/services/email/assets/reset.html
.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Reset Password</title> </head> <body style=" background-color: #f8f9fb; /*outer wrapper*/ height: 100%; font-family: Arial, Helvetica, sans-serif; "> <div style=" width: 100%; margin: auto; text-align: center; background-color: #f8f9fb; /*outer wrapper*/ "> <table style="text-align: center; width: 100%"> <tr> <td style="height: 6px"></td> </tr> <tr> <td style="text-align: center"> <table style=" background-color: {background_color}; text-align: center; max-width: 55%; margin: auto; "> <tr> <td style="height: 20px"></td> </tr> <tr> <td> <table style="width: 100%"> <tr> <td style="text-align: center"> <img src={entity_logo_url} alt={entity_name} style=" text-align: center; height: auto; width: 4rem; " /> </td> </tr> </table> </td> </tr> <tr> <td style="height: 40px"></td> </tr> <tr> <td style=" font-size: 2.02rem; font-weight: 600; line-height: 2.5rem; color: {foreground_color}; min-width: 550px; "> Reset password! </td> </tr> <tr> <td style="height: 10px"></td> </tr> <tr> <td style=" color: {foreground_color}; opacity:0.8; width: 50%; font-size: 1.02rem; font-weight: 400; line-height: 1.4rem; min-width: 300px; "> <table style=" width: 50%; min-width: 450px; text-align: center; margin: auto; "> <tr> <td> We have received a request to reset your password associated with <span style="font-weight: bold"> username : </span> {username} </td> </tr> </table> </td> </tr> <tr> <td style="height: 10px"></td> </tr> <tr> <td style=" color: {foreground_color}; opacity:0.8; width: 50%; font-size: 1.02rem; font-weight: 400; line-height: 1.4rem; min-width: 300px; "> <table style=" width: 50%; min-width: 370px; text-align: center; margin: auto; "> <tr> <td>Click on the below button to reset your password.</td> </tr> </table> </td> </tr> <tr> <td style="height: 30px"></td> </tr> <tr> <td> <a href="{link}" style=" text-decoration: none; border: none; border-radius: 64px; font-size: 1.03rem; color: #ffffff; font-weight: 500; line-height: 1.5rem; width: 50%; padding: 0.9rem 4rem; background: {primary_color}; min-width: 18rem; max-width: 25rem; cursor: pointer; "> Reset Password </a> </td> </tr> <tr> <td style="height: 70px"></td> </tr> </table> </td> </tr> <tr> <td style="height: 6px"></td> </tr> </table> </div> </body> </html>
1,028
1,308
hyperswitch
crates/router/src/services/email/assets/magic_link.html
.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Login to {entity_name}</title> </head> <body style=" background-color: #f8f9fb; /*outer wrapper*/ height: 100%; font-family: Arial, Helvetica, sans-serif; "> <div style=" width: 100%; margin: auto; text-align: center; background-color: #f8f9fb; /*outer wrapper*/ "> <table style="text-align: center; width: 100%"> <tr> <td style="height: 6px"></td> </tr> <tr> <td style="text-align: center"> <table style=" background-color: {background_color}; text-align: center; max-width: 55%; margin: auto; "> <tr> <td style="height: 20px"></td> </tr> <tr> <td> <table style="width: 100%"> <tr> <td style="text-align: center"> <img src={entity_logo_url} alt={entity_name} style=" text-align: center; height: auto; width: 4rem; " /> </td> </tr> </table> </td> </tr> <tr> <td style="height: 40px"></td> </tr> <tr> <td style=" font-size: 2.02rem; font-weight: 600; line-height: 2.5rem; color: {foreground_color}; min-width: 550px; "> Welcome to {entity_name}! </td> </tr> <tr> <td style="height: 10px"></td> </tr> <tr> <td style=" color: {foreground_color}; opacity:0.8; width: 50%; font-size: 1.02rem; font-weight: 400; line-height: 1.4rem; min-width: 300px; "> <table style=" width: 50%; min-width: 350px; text-align: center; margin: auto; "> <tr> <td> Dear {username}, we are thrilled to welcome you into our community! </td> </tr> </table> </td> </tr> <tr> <td style="height: 30px"></td> </tr> <tr> <td> <a href="{link}" style=" text-decoration: none; border: none; border-radius: 64px; font-size: 1.02rem; color: #ffffff; font-weight: 500; line-height: 1.5rem; width: 50%; padding: 0.9rem 3.5rem; background: {primary_color}; min-width: 18rem; max-width: 25rem; cursor: pointer; "> Unlock {entity_name} </a> </td> </tr> <tr> <td style="height: 30px"></td> </tr> <tr> <td style=" color: {foreground_color}; opacity:0.8; width: 50%; font-size: 1.02rem; font-weight: 400; line-height: 1.4rem; min-width: 300px; "> <table style=" width: 50%; min-width: 500px; text-align: center; margin: auto; "> <tr> <td> This link provides instant access to {entity_name} account. It will expire in 24 hours and can only be used once. </td> </tr> </table> </td> </tr> <tr> <td style="height: 70px"></td> </tr> </table> </td> </tr> <tr> <td style="height: 6px"></td> </tr> </table> </div> </body> </html>
1,044
1,309
hyperswitch
crates/router/src/services/email/assets/invite.html
.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Invite User</title> </head> <body style=" background-color: #f8f9fb; /*outer wrapper*/ height: 100%; font-family: Arial, Helvetica, sans-serif; "> <div style=" width: 100%; margin: auto; text-align: center; background-color: #f8f9fb; /*outer wrapper*/ "> <table style="text-align: center; width: 100%"> <tr> <td style="height: 6px"></td> </tr> <tr> <td style="text-align: center"> <table style=" background-color: {background_color}; text-align: center; max-width: 55%; margin: auto; "> <tr> <td style="height: 20px"></td> </tr> <tr> <td> <table style="width: 100%"> <tr> <td style="text-align: center"> <img src={entity_logo_url} alt={entity_name} style=" text-align: center; height: auto; width: 4rem; " /> </td> </tr> </table> </td> </tr> <tr> <td style="height: 40px"></td> </tr> <tr> <td style=" font-size: 2.02rem; font-weight: 600; line-height: 2.5rem; color: {foreground_color}; min-width: 550px; "> Welcome to {entity_name}! </td> </tr> <tr> <td style="height: 10px"></td> </tr> <tr> <td style=" color: {foreground_color}; opacity:0.8; width: 50%; font-size: 1.02rem; font-weight: 400; line-height: 1.4rem; min-width: 300px; "> <table style=" width: 50%; min-width: 440px; text-align: center; margin: auto; "> <tr> <td> Hi {username}, you have received this email because your administrator has invited you as a new user on {entity_name}. </td> </tr> </table> </td> </tr> <tr> <td style="height: 30px"></td> </tr> <tr> <td> <a href="{link}" style=" text-decoration: none; border: none; border-radius: 64px; font-size: 1.02rem; color: #ffffff; font-weight: 500; line-height: 1.5rem; width: 50%; padding: 0.9rem 4rem; background: {primary_color}; min-width: 18rem; max-width: 25rem; cursor: pointer; "> Click here to join </a> </td> </tr> <tr> <td style="height: 30px"></td> </tr> <tr> <td style=" color: {foreground_color}; opacity:0.8; width: 50%; font-size: 1.02rem; font-weight: 400; line-height: 1.4rem; min-width: 300px; "> <table style=" width: 50%; min-width: 500px; text-align: center; margin: auto; "> <tr> <td> If the link has already expired, you can request a new link from your administrator or reach out to your internal support for more assistance. </td> </tr> </table> </td> </tr> <tr> <td style="height: 70px"></td> </tr> </table> </td> </tr> <tr> <td style="height: 6px"></td> </tr> </table> </div> </body> </html>
1,053
1,310
hyperswitch
crates/router/src/services/email/assets/bizemailprod.html
.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Welcome to Hyperswitch!</title> </head> <body style=" background-color: #f8f9fb; height: 100%; font-family: Arial, Helvetica, sans-serif; " > <div style=" width: 100%; margin: auto; text-align: center; background-color: #f8f9fb; " > <table style="text-align: center; width: 100%"> <tr> <td style="height: 6px"></td> </tr> <tr> <td style="text-align: center"> <table style=" background-color: #ffffff; text-align: center; max-width: 60%; margin: auto; " > <tr> <td style="height: 15px"></td> </tr> <tr> <td> <table style="width: 100%"> <tr> <td style="text-align: center"> <img src="https://app.hyperswitch.io/email-assets/HyperswitchLogo.png" alt="Hyperswitch" style=" text-align: center; height: 1.3rem; width: auto; " /> </td> </tr> </table> </td> </tr> <tr> <td style="height: 20px"></td> </tr> <tr> <td style=" color: #666666; font-size: 1rem; font-weight: 400; line-height: 1.5rem; min-width: 450px; " > <table style=" width: 90%; min-width: 350px; text-align: start; margin: auto; padding: 0 10px; " > <tr> <td style="text-align: start"> <p>Hi Team,</p> <p> A Production Account Intent has been initiated by {username} - please find more details below: </p> <ol> <li><strong>Name:</strong> {username}</li> <li> <strong>Point of Contact Email (POC):</strong> {poc_email} </li> <li> <strong>Legal Business Name:</strong> {legal_business_name} </li> <li> <strong>Business Location:</strong> {business_location} </li> <li> <strong>Business Website:</strong> {business_website} </li> <li> <strong>Product Type:</strong> {product_type} </li> </ol> </td> </tr> <tr> <td style="height: 15px"></td> </tr> <tr> <td style="text-align: start"> Regards,<br /> Hyperswitch Dashboard Team </td> </tr> </table> </td> </tr> <tr> <td style="height: 50px"></td> </tr> <tr> <td style=" font-size: 12px; line-height: 1rem; font-weight: 400; color: #111326b2; " > Follow us on </td> </tr> <tr> <td style="font-size: 0"> <a href="https://github.com/juspay/hyperswitch" target="_blank" > <img src="https://app.hyperswitch.io/email-assets/Github.png" alt="Github" height="15" /> </a> <a href="https://x.com/hyperswitchio?s=21" target="_blank" style="margin: 0 6px 0" > <img src="https://app.hyperswitch.io/email-assets/Twitter.png" alt="Twitter" height="15" /> </a> <a href="https://www.linkedin.com/company/hyperswitch/" target="_blank" > <img src="https://app.hyperswitch.io/email-assets/Linkedin-Dark.png" alt="LinkedIn" height="15" /> </a> </td> </tr> <tr> <td style="height: 20px"></td> </tr> </table> </td> </tr> <tr> <td style="height: 6px"></td> </tr> </table> </div> </body> </html>
1,175
1,311
hyperswitch
crates/router/src/services/email/assets/welcome_to_community.html
.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Email Template</title> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet"> <style> @media only screen and (max-width: 600px) { .card-container { display: block !important; width: 100% !important; padding: 0 !important; } .card { width: 100% !important; max-width: 100% !important; margin-bottom: 15px !important; display: block !important; box-sizing: border-box; } .repocard, .communitycard, .devdocs-card { width: 100% !important; padding: 0 !important; margin-bottom: 10px !important; } .card-content { width: 100% !important; max-width: 100% !important; height: auto !important; min-height: 100px !important; padding: 20px 0 0 20px !important; box-sizing: border-box; } .docscard-content { width: 100% !important; max-width: 100% !important; height: auto !important; min-height: 100px !important; padding: 0 20px 0 20px !important; box-sizing: border-box; } .divider { width: 100% !important; padding: 0 !important; } .footer-section { text-align: center !important; margin: 0 auto; width: 100%; } td.card-container, td.card { width: 100% !important; padding: 0 !important; display: block !important; } .logo-section { text-align: center !important; width: 100% !important; } .logo-section img { display: block; margin: 0 auto; } } a.card-link { text-decoration: none !important; color: inherit !important; } .card-content td { color: #151A1F !important; } .card-content td img { display: block !important; } </style> </head> <body style="margin: 0; padding: 0; background-color: #f6f6f8; font-family: 'Inter', Arial, sans-serif;"> <center> <table width="100%" cellspacing="0" cellpadding="0" style="border-spacing: 0; margin: 0; padding: 0; background-color: #f6f6f8;"> <tr> <td align="center"> <table role="presentation" width="600" cellspacing="0" cellpadding="0" class="container" style="max-width: 600px; background-color: #ffffff; border-radius: 10px; border-collapse: collapse;"> <!-- Header Section --> <tr> <td align="center" bgcolor="#283652" style="padding: 40px 30px; color: white; border-top-left-radius: 20px; border-top-right-radius: 20px;"> <table width="100%" role="presentation" cellspacing="0" cellpadding="0"> <tr> <td align="left"> <img src="https://app.hyperswitch.io/assets/welcome-email/logotext.png" alt="Hyperswitch Logo" width="150" style="display: block; margin-bottom: 20px;"> </td> </tr> <tr> <td align="left" style="font-size: 36px; line-height: 40px; font-weight: 500; color: white;"> Welcome to <span style="font-weight: 700;">Hyperswitch</span> <img src="https://app.hyperswitch.io/assets/welcome-email/star.png" alt="Star Icon" width="30" style="display: inline-block; vertical-align: middle; position: relative; top: -3px; margin-left: -2px;"> </td> </tr> </table> </td> </tr> <!-- Body Section --> <tr> <td align="left" style="padding: 30px; background-color: #FFFFFF; color: #151A1F; font-size: 16px; font-family: 'Inter', Arial, sans-serif; font-weight: 400; line-height: 23.68px; text-align: left;"> <p style="margin-bottom: 20px; font-weight: 500;">Hello,</p> <p style="margin-bottom: 20px;">I wanted to reach out and introduce our community to you.</p> <p style="margin-bottom: 20px;">I’m Neeraj. I work in Community Growth here at Hyperswitch. We are a bunch of passionate people solving for payment diversity, complexity, and innovation. Juspay, our parent organization, processes 125 Mn transactions every day and has been providing payment platform solutions to large digital enterprises for the past 12 years. We wish to empower global businesses to expand their reach and enhance customer experiences through diverse payment solutions.</p> <p style="margin-bottom: 20px;">Our mission is to provide a Fast, Reliable, Affordable & Transparent payments platform, allowing businesses the flexibility to choose between open-source and SaaS solution.</p> </td> </tr> <!-- CTA Cards Section (GitHub & Slack) --> <tr> <td align="center" style="padding: 0 30px;"> <table width="100%" cellspacing="0" cellpadding="0"> <tr> <!-- GitHub Repo Card --> <td width="50%" class="card" valign="top" style="padding-right: 10px;"> <a href="https://github.com/juspay/hyperswitch" target="_blank" class="card-link"> <table class="card-content" width="100%" cellspacing="0" cellpadding="0" style="background-color: #F6F6F6; border-radius: 16px; padding: 20px 0 0 20px;"> <tr> <td align="left" style="vertical-align: top; font-size: 22px; font-weight: 600; padding-right: 20px;"> Star <br /> our repo </td> <td align="right" style="vertical-align: top; padding: 0 20px 0 0;"> <img src="https://app.hyperswitch.io/assets/welcome-email/repoArrow.png" alt="Arrow Icon" width="24" height="24" style="border-radius: 50%; padding: 7px; background-color: #fff;"> </td> </tr> <tr> <td colspan="2" align="right"> <img src="https://app.hyperswitch.io/assets/welcome-email/github-logo1.png" alt="GitHub Icon" width="98" height="98" style="display: block;"> </td> </tr> </table> </a> </td> <!-- Slack Community Card --> <td width="50%" class="card" valign="top" style="padding-left: 10px;"> <a href="https://hyperswitch-io.slack.com/join/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw#/shared-invite/email" target="_blank" class="card-link"> <table class="card-content" width="100%" cellspacing="0" cellpadding="0" style="background-color: #F6F6F6; border-radius: 16px; padding: 20px 0 0 20px;"> <tr> <td align="left" style="vertical-align: top; font-size: 22px; font-weight: 600; padding-right: 20px;"> Join our <br /> Community </td> <td align="right" style="vertical-align: top; padding: 0 20px 0 0;"> <img src="https://app.hyperswitch.io/assets/welcome-email/communityArrow.png" alt="Arrow Icon" width="24" height="24" style="border-radius: 50%; padding: 7px; background-color: #fff;"> </td> </tr> <tr> <td colspan="2" align="right"> <img src="https://app.hyperswitch.io/assets/welcome-email/slack.png" alt="Slack Icon" width="98" height="98" style="display: block;"> </td> </tr> </table> </a> </td> </tr> </table> </td> </tr> <!-- Read Dev Docs Section --> <tr> <td style="padding: 10px 30px 0 30px ;"> <a href="https://api-reference.hyperswitch.io/introduction" target="_blank" class="card-link"> <table class="docscard-content" width="100%" cellspacing="0" cellpadding="0" style="background-color: #FFEFEF; border-radius: 16px; padding: 20px;"> <tr> <td style="vertical-align: middle;"> <table> <tr> <td style="vertical-align: middle;"> <img src="https://app.hyperswitch.io/assets/welcome-email/docs.png" alt="docs icon" width="24" height="29" style="margin-right: 10px;"> </td> <td style="vertical-align: middle;"> <span style="font-size: 22px; font-weight: 600;">Read dev docs</span> </td> </tr> </table> </td> <td align="right" style="vertical-align: middle;"> <img src="https://app.hyperswitch.io/assets/welcome-email/docsArrow.png" alt="Arrow Icon" width="24" height="24" style="border-radius: 50%; padding: 7px; background-color: #fff;"> </td> </tr> </table> </a> </td> </tr> <!-- Divider and Footer Section --> <tr> <td style="padding: 40px 0 0 0;"> <!-- Divider (Top Border) --> <table width="100%" class="divider" cellpadding="0" cellspacing="0" style="border-top: 1px solid #F2F2F2;"> <tr> <td align="center"> <table cellspacing="0" cellpadding="0" style="margin: 0 auto; padding: 30px 0; max-width: 378px; width: 100%;"> <tr> <td align="center" style="padding: 0;" class="logo-section"> <img src="https://app.hyperswitch.io/assets/welcome-email/logo.png" alt="Icon" width="82" height="40" style="display: block;"> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </td> </tr> <!-- Footer Section with max-width 600px --> <tr> <td align="center" style="padding: 16px 4px 0 4px; background-color: #f6f6f8;"> <table width="100%" cellspacing="0" cellpadding="0" style="max-width: 601px;"> <tr> <!-- Follow us on and Social Media Icons --> <td align="left" style="font-family: 'Inter', Arial, sans-serif; font-size: 12px; font-weight: 500; line-height: 16px; color: #63605F;"> Follow us on <a href="https://x.com/hyperswitchio" style="margin-right: 10px; text-decoration: none;"> <img src="https://app.hyperswitch.io/assets/welcome-email/twitter.png" alt="Twitter" width="14" height="14" style="vertical-align: -3px;"> </a> <a href="https://www.linkedin.com/company/hyperswitch/" style="text-decoration: none;"> <img src="https://app.hyperswitch.io/assets/welcome-email/linkedin.png" alt="LinkedIn" width="13.33" height="13.33" style="vertical-align: -3px;"> </a> </td> </tr> </table> </td> </tr> </table> </center> </body> </html>
3,084
1,312
hyperswitch
crates/router/src/services/email/assets/recon_activation.html
.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Access Granted to Hyperswitch Recon Dashboard!</title> </head> <body style=" background-color: #f8f9fb; height: 100%; font-family: Arial, Helvetica, sans-serif; " > <div style=" width: 100%; margin: auto; text-align: center; background-color: #f8f9fb; " > <table style="text-align: center; width: 100%"> <tr> <td style="height: 6px"></td> </tr> <tr> <td style="text-align: center"> <table style=" background-color: #ffffff; text-align: center; max-width: 55%; margin: auto; " > <tr> <td style="height: 15px"></td> </tr> <tr> <td> <table style="width: 100%"> <tr> <td style="text-align: center"> <img src="https://app.hyperswitch.io/email-assets/HyperswitchLogo.png" alt="Hyperswitch" style=" text-align: center; height: 1.3rem; width: auto; " /> </td> </tr> </table> </td> </tr> <tr> <td style="height: 40px"></td> </tr> <tr> <td style=" color: #666666; font-size: 1rem; font-weight: 400; line-height: 1.5rem; min-width: 450px; " > <table style=" width: 90%; min-width: 350px; text-align: start; margin: auto; padding: 0 10px; " > <tr> <td style=" font-size: 2rem; font-weight: 600; line-height: 2.5rem; color: #111326; min-width: 500px; text-align: center; " > Access Granted to Hyperswitch Recon Dashboard! </td> </tr> <tr> <td style="text-align: start; font-size: 0.95rem; padding: 0 10px"> <p>Dear {username}</p> <p> We are pleased to inform you that your Reconciliation access request has been approved. You now have authorized access to the Recon dashboard, allowing you to test its functionality and experience its benefits firsthand. </p> <p> To access the Recon dashboard, please follow these steps: </p> <ol type="1"> <li> Visit our website at <a href="https://app.hyperswitch.io/">Hyperswitch Dashboard</a>. </li> <li>Click on the "Login" button.</li> <li>Enter your login credentials.</li> <li> Once logged in, you will have full access to the Recon dashboard, where you can explore its comprehensive features. </li> </ol> <p> For any inquiries or assistance, please reach out to our team on <a href="https://hyperswitch-io.slack.com/ssb/redirect">Slack </a>. </p> </td> </tr> <tr> <td style="height: 15px"></td> </tr> <tr> <td style="text-align: start"> Thanks,</br> Team Hyperswitch </td> </tr> </table> </td> </tr> <tr> <td style="height: 50px"></td> </tr> <tr> <td style=" font-size: 12px; line-height: 1rem; font-weight: 400; color: #111326b2; " > Follow us on </td> </tr> <tr> <td style="font-size: 0"> <a href="https://github.com/juspay/hyperswitch" target="_blank" > <img src="https://app.hyperswitch.io/email-assets/Github.png" alt="Github" height="15" /> </a> <a href="https://x.com/hyperswitchio?s=21" target="_blank" style="margin: 0 6px 0"> <img src="https://app.hyperswitch.io/email-assets/Twitter.png" alt="Twitter" height="15" /> </a> <a href="https://www.linkedin.com/company/hyperswitch/" target="_blank" > <img src="https://app.hyperswitch.io/email-assets/Linkedin-Dark.png" alt="LinkedIn" height="15" /> </a> </td> </tr> <tr> <td style="height: 20px"></td> </tr> </table> </td> </tr> <tr> <td style="height: 6px"></td> </tr> </table> </div> </body> </html>
1,334
1,313
hyperswitch
crates/router/src/services/email/assets/api_key_expiry_reminder.html
.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>API Key Expiry Notice</title> </head> <body style=" background-color: #f8f9fb; height: 100%; font-family: Arial, Helvetica, sans-serif; " > <div style=" width: 100%; margin: auto; text-align: center; background-color: #f8f9fb; " > <table style="text-align: center; width: 100%"> <tr> <td style="height: 6px"></td> </tr> <tr> <td style="text-align: center"> <table style=" background-color: #ffffff; text-align: center; max-width: 50%; margin: auto; " > <tr> <td style="height: 20px"></td> </tr> <tr> <td> <table style="width: 100%"> <tr> <td style="text-align: center"> <img src="https://app.hyperswitch.io/email-assets/HyperswitchLogo.png" alt="Hyperswitch" style=" text-align: center; height: 1.3rem; width: auto; " /> </td> </tr> </table> </td> </tr> <tr> <td style="height: 40px"></td> </tr> <tr> <td style=" color: #666666; font-size: 1rem; font-weight: 400; line-height: 1.5rem; min-width: 450px; " > <table style=" width: 90%; min-width: 350px; text-align: start; margin: auto; padding: 0 10px; " > <tr> <td style="text-align: start;"> <p>Dear Merchant,</p> </td> </tr> <tr> <td style="text-align: start;"> <p> It has come to our attention that your API key, <b>{api_key_name}</b> (<code>{prefix}*****</code>) </code> will expire in {expires_in} days. </p> <p> To ensure uninterrupted access to our platform and continued smooth operation of your services, we request you to take the necessary actions as soon as possible. </p> </td> </tr> <tr> <td style="height: 30px"></td> </tr> <tr> <td style="text-align: start;"> Thanks,<br /> Team Hyperswitch </td> </tr> </table> </td> </tr> <tr> <td style="height: 50px"></td> </tr> <tr> <td style=" font-size: 12px; line-height: 1rem; font-weight: 400; color: #111326b2; " > Follow us on </td> </tr> <tr> <td style="font-size: 0"> <a href="https://github.com/juspay/hyperswitch" target="_blank" > <img src="https://app.hyperswitch.io/email-assets/Github.png" alt="Github" height="15" /> </a> <a href="https://x.com/hyperswitchio?s=21" target="_blank" style="margin: 0 6px 0"> <img src="https://app.hyperswitch.io/email-assets/Twitter.png" alt="Twitter" height="15" /> </a> <a href="https://www.linkedin.com/company/hyperswitch/" target="_blank" > <img src="https://app.hyperswitch.io/email-assets/Linkedin-Dark.png" alt="LinkedIn" height="15" /> </a> </td> </tr> <tr> <td style="height: 20px"></td> </tr> </table> </td> </tr> <tr> <td style="height: 6px"></td> </tr> </table> </div> </body> </html>
1,114
1,314
hyperswitch
crates/router/src/services/email/assets/verify.html
.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Verify Email</title> </head> <body style=" background-color: #f8f9fb; /*outer wrapper*/ height: 100%; font-family: Arial, Helvetica, sans-serif; "> <div style=" width: 100%; margin: auto; text-align: center; background-color: #f8f9fb; /*outer wrapper*/ "> <table style="text-align: center; width: 100%"> <tr> <td style="height: 6px"></td> </tr> <tr> <td style="text-align: center"> <table style=" background-color: {background_color}; text-align: center; min-width: 55%; margin: auto; padding: 0 13px; "> <tr> <td style="height: 20px"></td> </tr> <tr> <td> <table style="width: 100%"> <tr> <td style="text-align: center"> <img src={entity_logo_url} alt={entity_name} style=" text-align: center; height: auto; width: 4rem; " /> </td> </tr> </table> </td> </tr> <tr> <td style="height: 40px"></td> </tr> <tr> <td style=" font-size: 2.01rem; font-weight: 600; line-height: 2.5rem; color: {foreground_color}; min-width: 500px; "> Thanks for signing up with {entity_name}! </td> </tr> <tr> <td style="height: 10px"></td> </tr> <tr> <td style=" color: {foreground_color}; opacity:0.8; font-size: 1.02rem; font-weight: 400; line-height: 1.4rem; min-width: 450px; "> <table style=" width: 50%; min-width: 350px; text-align: center; margin: auto; "> <tr> <td> Confirm your email address to complete your registration by clicking the button below. </td> </tr> </table> </td> </tr> <tr> <td style="height: 30px"></td> </tr> <tr> <td> <a href="{link}" style=" text-decoration: none; border: none; border-radius: 64px; font-size: 1.03rem; color: #ffffff; font-weight: 500; line-height: 1.5rem; width: 55%; padding: 1rem 3rem; background: {primary_color}; min-width: 18rem; "> Confirm your email address </a> </td> </tr> <tr> <td style="height: 70px"></td> </tr> </table> </td> </tr> <tr> <td style="height: 6px"></td> </tr> </table> </div> </body> </html>
842
1,315
hyperswitch
crates/router/src/services/kafka/payment_intent.rs
.rs
use common_utils::{crypto::Encryptable, hashing::HashedString, id_type, pii, types::MinorUnit}; use diesel_models::enums as storage_enums; use hyperswitch_domain_models::payments::PaymentIntent; use masking::{PeekInterface, Secret}; use serde_json::Value; use time::OffsetDateTime; #[cfg(feature = "v1")] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntent<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a 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<&'a id_type::CustomerId>, pub description: Option<&'a String>, pub return_url: Option<&'a String>, pub metadata: Option<String>, pub connector_id: Option<&'a String>, pub statement_descriptor_name: Option<&'a String>, pub statement_descriptor_suffix: Option<&'a String>, #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<&'a String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<&'a String>, pub attempt_count: i16, pub profile_id: Option<&'a id_type::ProfileId>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub billing_details: Option<Encryptable<Secret<Value>>>, pub shipping_details: Option<Encryptable<Secret<Value>>>, pub customer_email: Option<HashedString<pii::EmailStrategy>>, pub feature_metadata: Option<&'a Value>, pub merchant_order_reference_id: Option<&'a String>, pub organization_id: &'a id_type::OrganizationId, } #[cfg(feature = "v2")] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntent<'a> { pub id: &'a id_type::PaymentId, pub merchant_id: &'a 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<&'a id_type::CustomerId>, pub description: Option<&'a String>, pub return_url: Option<&'a String>, pub metadata: Option<String>, pub statement_descriptor: Option<&'a String>, #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<&'a String>, pub active_attempt_id: String, pub attempt_count: i16, pub profile_id: &'a id_type::ProfileId, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub billing_details: Option<Encryptable<Secret<Value>>>, pub shipping_details: Option<Encryptable<Secret<Value>>>, pub customer_email: Option<HashedString<pii::EmailStrategy>>, pub feature_metadata: Option<&'a Value>, pub merchant_order_reference_id: Option<&'a String>, pub organization_id: &'a id_type::OrganizationId, } #[cfg(feature = "v1")] impl<'a> KafkaPaymentIntent<'a> { pub fn from_storage(intent: &'a PaymentIntent) -> Self { Self { payment_id: &intent.payment_id, merchant_id: &intent.merchant_id, status: intent.status, amount: intent.amount, currency: intent.currency, amount_captured: intent.amount_captured, customer_id: intent.customer_id.as_ref(), description: intent.description.as_ref(), return_url: intent.return_url.as_ref(), metadata: intent.metadata.as_ref().map(|x| x.to_string()), connector_id: intent.connector_id.as_ref(), statement_descriptor_name: intent.statement_descriptor_name.as_ref(), statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(), created_at: intent.created_at.assume_utc(), modified_at: intent.modified_at.assume_utc(), last_synced: intent.last_synced.map(|i| i.assume_utc()), setup_future_usage: intent.setup_future_usage, off_session: intent.off_session, client_secret: intent.client_secret.as_ref(), active_attempt_id: intent.active_attempt.get_id(), business_country: intent.business_country, business_label: intent.business_label.as_ref(), attempt_count: intent.attempt_count, profile_id: intent.profile_id.as_ref(), payment_confirm_source: intent.payment_confirm_source, // TODO: use typed information here to avoid PII logging billing_details: None, shipping_details: None, customer_email: intent .customer_details .as_ref() .and_then(|value| value.get_inner().peek().as_object()) .and_then(|obj| obj.get("email")) .and_then(|email| email.as_str()) .map(|email| HashedString::from(Secret::new(email.to_string()))), feature_metadata: intent.feature_metadata.as_ref(), merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(), organization_id: &intent.organization_id, } } } #[cfg(feature = "v2")] impl<'a> KafkaPaymentIntent<'a> { pub fn from_storage(intent: &'a PaymentIntent) -> Self { // Self { // id: &intent.id, // merchant_id: &intent.merchant_id, // status: intent.status, // amount: intent.amount, // currency: intent.currency, // amount_captured: intent.amount_captured, // customer_id: intent.customer_id.as_ref(), // description: intent.description.as_ref(), // return_url: intent.return_url.as_ref(), // metadata: intent.metadata.as_ref().map(|x| x.to_string()), // statement_descriptor: intent.statement_descriptor.as_ref(), // created_at: intent.created_at.assume_utc(), // modified_at: intent.modified_at.assume_utc(), // last_synced: intent.last_synced.map(|i| i.assume_utc()), // setup_future_usage: intent.setup_future_usage, // off_session: intent.off_session, // client_secret: intent.client_secret.as_ref(), // active_attempt_id: intent.active_attempt.get_id(), // attempt_count: intent.attempt_count, // profile_id: &intent.profile_id, // payment_confirm_source: intent.payment_confirm_source, // // TODO: use typed information here to avoid PII logging // billing_details: None, // shipping_details: None, // customer_email: intent // .customer_details // .as_ref() // .and_then(|value| value.get_inner().peek().as_object()) // .and_then(|obj| obj.get("email")) // .and_then(|email| email.as_str()) // .map(|email| HashedString::from(Secret::new(email.to_string()))), // feature_metadata: intent.feature_metadata.as_ref(), // merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(), // organization_id: &intent.organization_id, // } todo!() } } impl KafkaPaymentIntent<'_> { #[cfg(feature = "v1")] fn get_id(&self) -> &id_type::PaymentId { self.payment_id } #[cfg(feature = "v2")] fn get_id(&self) -> &id_type::PaymentId { self.id } } impl super::KafkaMessage for KafkaPaymentIntent<'_> { fn key(&self) -> String { format!( "{}_{}", self.merchant_id.get_string_repr(), self.get_id().get_string_repr(), ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentIntent } }
1,900
1,316
hyperswitch
crates/router/src/services/kafka/refund.rs
.rs
use common_utils::{ id_type, types::{ConnectorTransactionIdTrait, MinorUnit}, }; use diesel_models::{enums as storage_enums, refund::Refund}; use time::OffsetDateTime; use crate::events; #[cfg(feature = "v1")] #[derive(serde::Serialize, Debug)] pub struct KafkaRefund<'a> { pub internal_reference_id: &'a String, pub refund_id: &'a String, //merchant_reference id pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub connector_transaction_id: &'a String, pub connector: &'a String, pub connector_refund_id: Option<&'a String>, pub external_reference_id: Option<&'a String>, pub refund_type: &'a storage_enums::RefundType, pub total_amount: &'a MinorUnit, pub currency: &'a storage_enums::Currency, pub refund_amount: &'a MinorUnit, pub refund_status: &'a storage_enums::RefundStatus, pub sent_to_gateway: &'a bool, pub refund_error_message: Option<&'a String>, pub refund_arn: Option<&'a String>, #[serde(default, with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, pub description: Option<&'a String>, pub attempt_id: &'a String, pub refund_reason: Option<&'a String>, pub refund_error_code: Option<&'a String>, pub profile_id: Option<&'a id_type::ProfileId>, pub organization_id: &'a id_type::OrganizationId, } #[cfg(feature = "v1")] impl<'a> KafkaRefund<'a> { pub fn from_storage(refund: &'a Refund) -> Self { Self { internal_reference_id: &refund.internal_reference_id, refund_id: &refund.refund_id, payment_id: &refund.payment_id, merchant_id: &refund.merchant_id, connector_transaction_id: refund.get_connector_transaction_id(), connector: &refund.connector, connector_refund_id: refund.get_optional_connector_refund_id(), external_reference_id: refund.external_reference_id.as_ref(), refund_type: &refund.refund_type, total_amount: &refund.total_amount, currency: &refund.currency, refund_amount: &refund.refund_amount, refund_status: &refund.refund_status, sent_to_gateway: &refund.sent_to_gateway, refund_error_message: refund.refund_error_message.as_ref(), refund_arn: refund.refund_arn.as_ref(), created_at: refund.created_at.assume_utc(), modified_at: refund.modified_at.assume_utc(), description: refund.description.as_ref(), attempt_id: &refund.attempt_id, refund_reason: refund.refund_reason.as_ref(), refund_error_code: refund.refund_error_code.as_ref(), profile_id: refund.profile_id.as_ref(), organization_id: &refund.organization_id, } } } #[cfg(feature = "v2")] #[derive(serde::Serialize, Debug)] pub struct KafkaRefund<'a> { pub id: &'a id_type::GlobalRefundId, pub merchant_reference_id: &'a id_type::RefundReferenceId, pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub connector_transaction_id: &'a String, pub connector: &'a String, pub connector_refund_id: Option<&'a String>, pub external_reference_id: Option<&'a String>, pub refund_type: &'a storage_enums::RefundType, pub total_amount: &'a MinorUnit, pub currency: &'a storage_enums::Currency, pub refund_amount: &'a MinorUnit, pub refund_status: &'a storage_enums::RefundStatus, pub sent_to_gateway: &'a bool, pub refund_error_message: Option<&'a String>, pub refund_arn: Option<&'a String>, #[serde(default, with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, pub description: Option<&'a String>, pub attempt_id: &'a id_type::GlobalAttemptId, pub refund_reason: Option<&'a String>, pub refund_error_code: Option<&'a String>, pub profile_id: Option<&'a id_type::ProfileId>, pub organization_id: &'a id_type::OrganizationId, } #[cfg(feature = "v2")] impl<'a> KafkaRefund<'a> { pub fn from_storage(refund: &'a Refund) -> Self { Self { id: &refund.id, merchant_reference_id: &refund.merchant_reference_id, payment_id: &refund.payment_id, merchant_id: &refund.merchant_id, connector_transaction_id: refund.get_connector_transaction_id(), connector: &refund.connector, connector_refund_id: refund.get_optional_connector_refund_id(), external_reference_id: refund.external_reference_id.as_ref(), refund_type: &refund.refund_type, total_amount: &refund.total_amount, currency: &refund.currency, refund_amount: &refund.refund_amount, refund_status: &refund.refund_status, sent_to_gateway: &refund.sent_to_gateway, refund_error_message: refund.refund_error_message.as_ref(), refund_arn: refund.refund_arn.as_ref(), created_at: refund.created_at.assume_utc(), modified_at: refund.modified_at.assume_utc(), description: refund.description.as_ref(), attempt_id: &refund.attempt_id, refund_reason: refund.refund_reason.as_ref(), refund_error_code: refund.refund_error_code.as_ref(), profile_id: refund.profile_id.as_ref(), organization_id: &refund.organization_id, } } } #[cfg(feature = "v1")] impl super::KafkaMessage for KafkaRefund<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id, self.refund_id ) } fn event_type(&self) -> events::EventType { events::EventType::Refund } } #[cfg(feature = "v2")] impl super::KafkaMessage for KafkaRefund<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id.get_string_repr(), self.merchant_reference_id.get_string_repr() ) } fn event_type(&self) -> events::EventType { events::EventType::Refund } }
1,501
1,317
hyperswitch
crates/router/src/services/kafka/refund_event.rs
.rs
use common_utils::{ id_type, types::{ConnectorTransactionIdTrait, MinorUnit}, }; use diesel_models::{enums as storage_enums, refund::Refund}; use time::OffsetDateTime; use crate::events; #[cfg(feature = "v1")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaRefundEvent<'a> { pub internal_reference_id: &'a String, pub refund_id: &'a String, //merchant_reference id pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub connector_transaction_id: &'a String, pub connector: &'a String, pub connector_refund_id: Option<&'a String>, pub external_reference_id: Option<&'a String>, pub refund_type: &'a storage_enums::RefundType, pub total_amount: &'a MinorUnit, pub currency: &'a storage_enums::Currency, pub refund_amount: &'a MinorUnit, pub refund_status: &'a storage_enums::RefundStatus, pub sent_to_gateway: &'a bool, pub refund_error_message: Option<&'a String>, pub refund_arn: Option<&'a String>, #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub description: Option<&'a String>, pub attempt_id: &'a String, pub refund_reason: Option<&'a String>, pub refund_error_code: Option<&'a String>, pub profile_id: Option<&'a id_type::ProfileId>, pub organization_id: &'a id_type::OrganizationId, } #[cfg(feature = "v1")] impl<'a> KafkaRefundEvent<'a> { pub fn from_storage(refund: &'a Refund) -> Self { Self { internal_reference_id: &refund.internal_reference_id, refund_id: &refund.refund_id, payment_id: &refund.payment_id, merchant_id: &refund.merchant_id, connector_transaction_id: refund.get_connector_transaction_id(), connector: &refund.connector, connector_refund_id: refund.get_optional_connector_refund_id(), external_reference_id: refund.external_reference_id.as_ref(), refund_type: &refund.refund_type, total_amount: &refund.total_amount, currency: &refund.currency, refund_amount: &refund.refund_amount, refund_status: &refund.refund_status, sent_to_gateway: &refund.sent_to_gateway, refund_error_message: refund.refund_error_message.as_ref(), refund_arn: refund.refund_arn.as_ref(), created_at: refund.created_at.assume_utc(), modified_at: refund.modified_at.assume_utc(), description: refund.description.as_ref(), attempt_id: &refund.attempt_id, refund_reason: refund.refund_reason.as_ref(), refund_error_code: refund.refund_error_code.as_ref(), profile_id: refund.profile_id.as_ref(), organization_id: &refund.organization_id, } } } #[cfg(feature = "v2")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaRefundEvent<'a> { pub id: &'a id_type::GlobalRefundId, pub merchant_reference_id: &'a id_type::RefundReferenceId, pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub connector_transaction_id: &'a String, pub connector: &'a String, pub connector_refund_id: Option<&'a String>, pub external_reference_id: Option<&'a String>, pub refund_type: &'a storage_enums::RefundType, pub total_amount: &'a MinorUnit, pub currency: &'a storage_enums::Currency, pub refund_amount: &'a MinorUnit, pub refund_status: &'a storage_enums::RefundStatus, pub sent_to_gateway: &'a bool, pub refund_error_message: Option<&'a String>, pub refund_arn: Option<&'a String>, #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub description: Option<&'a String>, pub attempt_id: &'a id_type::GlobalAttemptId, pub refund_reason: Option<&'a String>, pub refund_error_code: Option<&'a String>, pub profile_id: Option<&'a id_type::ProfileId>, pub organization_id: &'a id_type::OrganizationId, } #[cfg(feature = "v2")] impl<'a> KafkaRefundEvent<'a> { pub fn from_storage(refund: &'a Refund) -> Self { Self { id: &refund.id, merchant_reference_id: &refund.merchant_reference_id, payment_id: &refund.payment_id, merchant_id: &refund.merchant_id, connector_transaction_id: refund.get_connector_transaction_id(), connector: &refund.connector, connector_refund_id: refund.get_optional_connector_refund_id(), external_reference_id: refund.external_reference_id.as_ref(), refund_type: &refund.refund_type, total_amount: &refund.total_amount, currency: &refund.currency, refund_amount: &refund.refund_amount, refund_status: &refund.refund_status, sent_to_gateway: &refund.sent_to_gateway, refund_error_message: refund.refund_error_message.as_ref(), refund_arn: refund.refund_arn.as_ref(), created_at: refund.created_at.assume_utc(), modified_at: refund.modified_at.assume_utc(), description: refund.description.as_ref(), attempt_id: &refund.attempt_id, refund_reason: refund.refund_reason.as_ref(), refund_error_code: refund.refund_error_code.as_ref(), profile_id: refund.profile_id.as_ref(), organization_id: &refund.organization_id, } } } #[cfg(feature = "v1")] impl super::KafkaMessage for KafkaRefundEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id, self.refund_id ) } fn event_type(&self) -> events::EventType { events::EventType::Refund } } #[cfg(feature = "v2")] impl super::KafkaMessage for KafkaRefundEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id.get_string_repr(), self.merchant_reference_id.get_string_repr() ) } fn event_type(&self) -> events::EventType { events::EventType::Refund } }
1,537
1,318
hyperswitch
crates/router/src/services/kafka/authentication.rs
.rs
use diesel_models::{authentication::Authentication, enums as storage_enums}; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaAuthentication<'a> { pub authentication_id: &'a String, pub merchant_id: &'a common_utils::id_type::MerchantId, pub authentication_connector: &'a String, pub connector_authentication_id: Option<&'a String>, pub authentication_data: Option<serde_json::Value>, pub payment_method_id: &'a String, pub authentication_type: Option<storage_enums::DecoupledAuthenticationType>, pub authentication_status: storage_enums::AuthenticationStatus, pub authentication_lifecycle_status: storage_enums::AuthenticationLifecycleStatus, #[serde(default, with = "time::serde::timestamp::milliseconds")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::milliseconds")] pub modified_at: OffsetDateTime, pub error_message: Option<&'a String>, pub error_code: Option<&'a String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<&'a String>, pub cavv: Option<&'a String>, pub authentication_flow_type: Option<&'a String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<&'a String>, pub trans_status: Option<storage_enums::TransactionStatus>, pub acquirer_bin: Option<&'a String>, pub acquirer_merchant_id: Option<&'a String>, pub three_ds_method_data: Option<&'a String>, pub three_ds_method_url: Option<&'a String>, pub acs_url: Option<&'a String>, pub challenge_request: Option<&'a String>, pub acs_reference_number: Option<&'a String>, pub acs_trans_id: Option<&'a String>, pub acs_signed_content: Option<&'a String>, pub profile_id: &'a common_utils::id_type::ProfileId, pub payment_id: Option<&'a common_utils::id_type::PaymentId>, pub merchant_connector_id: &'a common_utils::id_type::MerchantConnectorAccountId, pub ds_trans_id: Option<&'a String>, pub directory_server_id: Option<&'a String>, pub acquirer_country_code: Option<&'a String>, pub organization_id: &'a common_utils::id_type::OrganizationId, } impl<'a> KafkaAuthentication<'a> { pub fn from_storage(authentication: &'a Authentication) -> Self { Self { created_at: authentication.created_at.assume_utc(), modified_at: authentication.modified_at.assume_utc(), 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.as_ref(), authentication_data: authentication.authentication_data.clone(), payment_method_id: &authentication.payment_method_id, authentication_type: authentication.authentication_type, authentication_lifecycle_status: authentication.authentication_lifecycle_status, error_code: authentication.error_code.as_ref(), error_message: authentication.error_message.as_ref(), connector_metadata: authentication.connector_metadata.clone(), maximum_supported_version: authentication.maximum_supported_version.clone(), threeds_server_transaction_id: authentication.threeds_server_transaction_id.as_ref(), cavv: authentication.cavv.as_ref(), authentication_flow_type: authentication.authentication_flow_type.as_ref(), message_version: authentication.message_version.clone(), eci: authentication.eci.as_ref(), trans_status: authentication.trans_status.clone(), acquirer_bin: authentication.acquirer_bin.as_ref(), acquirer_merchant_id: authentication.acquirer_merchant_id.as_ref(), three_ds_method_data: authentication.three_ds_method_data.as_ref(), three_ds_method_url: authentication.three_ds_method_url.as_ref(), acs_url: authentication.acs_url.as_ref(), challenge_request: authentication.challenge_request.as_ref(), acs_reference_number: authentication.acs_reference_number.as_ref(), acs_trans_id: authentication.acs_trans_id.as_ref(), acs_signed_content: authentication.acs_signed_content.as_ref(), profile_id: &authentication.profile_id, payment_id: authentication.payment_id.as_ref(), merchant_connector_id: &authentication.merchant_connector_id, ds_trans_id: authentication.ds_trans_id.as_ref(), directory_server_id: authentication.directory_server_id.as_ref(), acquirer_country_code: authentication.acquirer_country_code.as_ref(), organization_id: &authentication.organization_id, } } } impl super::KafkaMessage for KafkaAuthentication<'_> { fn key(&self) -> String { format!( "{}_{}", self.merchant_id.get_string_repr(), self.authentication_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Authentication } }
1,071
1,319
hyperswitch
crates/router/src/services/kafka/authentication_event.rs
.rs
use diesel_models::{authentication::Authentication, enums as storage_enums}; use time::OffsetDateTime; #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaAuthenticationEvent<'a> { pub authentication_id: &'a String, pub merchant_id: &'a common_utils::id_type::MerchantId, pub authentication_connector: &'a String, pub connector_authentication_id: Option<&'a String>, pub authentication_data: Option<serde_json::Value>, pub payment_method_id: &'a String, pub authentication_type: Option<storage_enums::DecoupledAuthenticationType>, pub authentication_status: storage_enums::AuthenticationStatus, pub authentication_lifecycle_status: storage_enums::AuthenticationLifecycleStatus, #[serde(default, with = "time::serde::timestamp::milliseconds")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::milliseconds")] pub modified_at: OffsetDateTime, pub error_message: Option<&'a String>, pub error_code: Option<&'a String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<&'a String>, pub cavv: Option<&'a String>, pub authentication_flow_type: Option<&'a String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<&'a String>, pub trans_status: Option<storage_enums::TransactionStatus>, pub acquirer_bin: Option<&'a String>, pub acquirer_merchant_id: Option<&'a String>, pub three_ds_method_data: Option<&'a String>, pub three_ds_method_url: Option<&'a String>, pub acs_url: Option<&'a String>, pub challenge_request: Option<&'a String>, pub acs_reference_number: Option<&'a String>, pub acs_trans_id: Option<&'a String>, pub acs_signed_content: Option<&'a String>, pub profile_id: &'a common_utils::id_type::ProfileId, pub payment_id: Option<&'a common_utils::id_type::PaymentId>, pub merchant_connector_id: &'a common_utils::id_type::MerchantConnectorAccountId, pub ds_trans_id: Option<&'a String>, pub directory_server_id: Option<&'a String>, pub acquirer_country_code: Option<&'a String>, pub organization_id: &'a common_utils::id_type::OrganizationId, } impl<'a> KafkaAuthenticationEvent<'a> { pub fn from_storage(authentication: &'a Authentication) -> Self { Self { created_at: authentication.created_at.assume_utc(), modified_at: authentication.modified_at.assume_utc(), 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.as_ref(), authentication_data: authentication.authentication_data.clone(), payment_method_id: &authentication.payment_method_id, authentication_type: authentication.authentication_type, authentication_lifecycle_status: authentication.authentication_lifecycle_status, error_code: authentication.error_code.as_ref(), error_message: authentication.error_message.as_ref(), connector_metadata: authentication.connector_metadata.clone(), maximum_supported_version: authentication.maximum_supported_version.clone(), threeds_server_transaction_id: authentication.threeds_server_transaction_id.as_ref(), cavv: authentication.cavv.as_ref(), authentication_flow_type: authentication.authentication_flow_type.as_ref(), message_version: authentication.message_version.clone(), eci: authentication.eci.as_ref(), trans_status: authentication.trans_status.clone(), acquirer_bin: authentication.acquirer_bin.as_ref(), acquirer_merchant_id: authentication.acquirer_merchant_id.as_ref(), three_ds_method_data: authentication.three_ds_method_data.as_ref(), three_ds_method_url: authentication.three_ds_method_url.as_ref(), acs_url: authentication.acs_url.as_ref(), challenge_request: authentication.challenge_request.as_ref(), acs_reference_number: authentication.acs_reference_number.as_ref(), acs_trans_id: authentication.acs_trans_id.as_ref(), acs_signed_content: authentication.acs_signed_content.as_ref(), profile_id: &authentication.profile_id, payment_id: authentication.payment_id.as_ref(), merchant_connector_id: &authentication.merchant_connector_id, ds_trans_id: authentication.ds_trans_id.as_ref(), directory_server_id: authentication.directory_server_id.as_ref(), acquirer_country_code: authentication.acquirer_country_code.as_ref(), organization_id: &authentication.organization_id, } } } impl super::KafkaMessage for KafkaAuthenticationEvent<'_> { fn key(&self) -> String { format!( "{}_{}", self.merchant_id.get_string_repr(), self.authentication_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Authentication } }
1,083
1,320
hyperswitch
crates/router/src/services/kafka/dispute.rs
.rs
use common_utils::{ext_traits::StringExt, id_type}; use diesel_models::enums as storage_enums; use masking::Secret; use time::OffsetDateTime; use crate::types::storage::dispute::Dispute; #[derive(serde::Serialize, Debug)] pub struct KafkaDispute<'a> { pub dispute_id: &'a String, pub dispute_amount: i64, pub currency: storage_enums::Currency, pub dispute_stage: &'a storage_enums::DisputeStage, pub dispute_status: &'a storage_enums::DisputeStatus, pub payment_id: &'a id_type::PaymentId, pub attempt_id: &'a String, pub merchant_id: &'a id_type::MerchantId, pub connector_status: &'a String, pub connector_dispute_id: &'a String, pub connector_reason: Option<&'a String>, pub connector_reason_code: Option<&'a String>, #[serde(default, with = "time::serde::timestamp::option")] pub challenge_required_by: Option<OffsetDateTime>, #[serde(default, with = "time::serde::timestamp::option")] pub connector_created_at: Option<OffsetDateTime>, #[serde(default, with = "time::serde::timestamp::option")] pub connector_updated_at: Option<OffsetDateTime>, #[serde(default, with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, pub connector: &'a String, pub evidence: &'a Secret<serde_json::Value>, pub profile_id: Option<&'a id_type::ProfileId>, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, pub organization_id: &'a id_type::OrganizationId, } impl<'a> KafkaDispute<'a> { pub fn from_storage(dispute: &'a Dispute) -> Self { Self { dispute_id: &dispute.dispute_id, dispute_amount: dispute.amount.parse::<i64>().unwrap_or_default(), currency: dispute.dispute_currency.unwrap_or( dispute .currency .to_uppercase() .parse_enum("Currency") .unwrap_or_default(), ), 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.as_ref(), connector_reason_code: dispute.connector_reason_code.as_ref(), challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()), connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()), connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()), created_at: dispute.created_at.assume_utc(), modified_at: dispute.modified_at.assume_utc(), connector: &dispute.connector, evidence: &dispute.evidence, profile_id: dispute.profile_id.as_ref(), merchant_connector_id: dispute.merchant_connector_id.as_ref(), organization_id: &dispute.organization_id, } } } impl super::KafkaMessage for KafkaDispute<'_> { fn key(&self) -> String { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.dispute_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Dispute } }
805
1,321
hyperswitch
crates/router/src/services/kafka/dispute_event.rs
.rs
use common_utils::ext_traits::StringExt; use diesel_models::enums as storage_enums; use masking::Secret; use time::OffsetDateTime; use crate::types::storage::dispute::Dispute; #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaDisputeEvent<'a> { pub dispute_id: &'a String, pub dispute_amount: i64, pub currency: storage_enums::Currency, pub dispute_stage: &'a storage_enums::DisputeStage, pub dispute_status: &'a storage_enums::DisputeStatus, pub payment_id: &'a common_utils::id_type::PaymentId, pub attempt_id: &'a String, pub merchant_id: &'a common_utils::id_type::MerchantId, pub connector_status: &'a String, pub connector_dispute_id: &'a String, pub connector_reason: Option<&'a String>, pub connector_reason_code: Option<&'a String>, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub challenge_required_by: Option<OffsetDateTime>, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub connector_created_at: Option<OffsetDateTime>, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub connector_updated_at: Option<OffsetDateTime>, #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub connector: &'a String, pub evidence: &'a Secret<serde_json::Value>, pub profile_id: Option<&'a common_utils::id_type::ProfileId>, pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>, pub organization_id: &'a common_utils::id_type::OrganizationId, } impl<'a> KafkaDisputeEvent<'a> { pub fn from_storage(dispute: &'a Dispute) -> Self { Self { dispute_id: &dispute.dispute_id, dispute_amount: dispute.amount.parse::<i64>().unwrap_or_default(), currency: dispute.dispute_currency.unwrap_or( dispute .currency .to_uppercase() .parse_enum("Currency") .unwrap_or_default(), ), 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.as_ref(), connector_reason_code: dispute.connector_reason_code.as_ref(), challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()), connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()), connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()), created_at: dispute.created_at.assume_utc(), modified_at: dispute.modified_at.assume_utc(), connector: &dispute.connector, evidence: &dispute.evidence, profile_id: dispute.profile_id.as_ref(), merchant_connector_id: dispute.merchant_connector_id.as_ref(), organization_id: &dispute.organization_id, } } } impl super::KafkaMessage for KafkaDisputeEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.dispute_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Dispute } }
844
1,322
hyperswitch
crates/router/src/services/kafka/fraud_check.rs
.rs
// use diesel_models::enums as storage_enums; use diesel_models::{ enums as storage_enums, enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, fraud_check::FraudCheck, }; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaFraudCheck<'a> { pub frm_id: &'a String, pub payment_id: &'a common_utils::id_type::PaymentId, pub merchant_id: &'a common_utils::id_type::MerchantId, pub attempt_id: &'a String, #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, pub frm_name: &'a String, pub frm_transaction_id: Option<&'a 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<&'a String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, #[serde(with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, 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. } impl<'a> KafkaFraudCheck<'a> { pub fn from_storage(check: &'a FraudCheck) -> Self { Self { frm_id: &check.frm_id, payment_id: &check.payment_id, merchant_id: &check.merchant_id, attempt_id: &check.attempt_id, created_at: check.created_at.assume_utc(), frm_name: &check.frm_name, frm_transaction_id: check.frm_transaction_id.as_ref(), frm_transaction_type: check.frm_transaction_type, frm_status: check.frm_status, frm_score: check.frm_score, frm_reason: check.frm_reason.clone(), frm_error: check.frm_error.as_ref(), payment_details: check.payment_details.clone(), metadata: check.metadata.clone(), modified_at: check.modified_at.assume_utc(), last_step: check.last_step, payment_capture_method: check.payment_capture_method, } } } impl super::KafkaMessage for KafkaFraudCheck<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id, self.frm_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::FraudCheck } }
629
1,323
hyperswitch
crates/router/src/services/kafka/payment_attempt_event.rs
.rs
// use diesel_models::enums::MandateDetails; use common_utils::{id_type, types::MinorUnit}; use diesel_models::enums as storage_enums; use hyperswitch_domain_models::{ mandates::MandateDetails, payments::payment_attempt::PaymentAttempt, }; use time::OffsetDateTime; #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentAttemptEvent<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub attempt_id: &'a String, pub status: storage_enums::AttemptStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub save_to_locker: Option<bool>, pub connector: Option<&'a String>, pub error_message: Option<&'a String>, pub offer_amount: Option<MinorUnit>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<&'a String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<&'a String>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub capture_on: Option<OffsetDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub cancellation_reason: Option<&'a String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<&'a String>, pub browser_info: Option<String>, pub error_code: Option<&'a String>, pub connector_metadata: Option<String>, // TODO: These types should implement copy ideally pub payment_experience: Option<&'a storage_enums::PaymentExperience>, pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>, pub payment_method_data: Option<String>, pub error_reason: Option<&'a String>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, pub net_amount: MinorUnit, pub unified_code: Option<&'a String>, pub unified_message: Option<&'a String>, pub mandate_data: Option<&'a MandateDetails>, pub client_source: Option<&'a String>, pub client_version: Option<&'a String>, pub profile_id: &'a id_type::ProfileId, pub organization_id: &'a id_type::OrganizationId, pub card_network: Option<String>, pub card_discovery: Option<String>, } #[cfg(feature = "v1")] impl<'a> KafkaPaymentAttemptEvent<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { Self { payment_id: &attempt.payment_id, merchant_id: &attempt.merchant_id, attempt_id: &attempt.attempt_id, status: attempt.status, amount: attempt.net_amount.get_order_amount(), currency: attempt.currency, save_to_locker: attempt.save_to_locker, connector: attempt.connector.as_ref(), error_message: attempt.error_message.as_ref(), offer_amount: attempt.offer_amount, surcharge_amount: attempt.net_amount.get_surcharge_amount(), tax_amount: attempt.net_amount.get_tax_on_surcharge(), payment_method_id: attempt.payment_method_id.as_ref(), payment_method: attempt.payment_method, connector_transaction_id: attempt.connector_transaction_id.as_ref(), capture_method: attempt.capture_method, capture_on: attempt.capture_on.map(|i| i.assume_utc()), confirm: attempt.confirm, authentication_type: attempt.authentication_type, created_at: attempt.created_at.assume_utc(), modified_at: attempt.modified_at.assume_utc(), last_synced: attempt.last_synced.map(|i| i.assume_utc()), cancellation_reason: attempt.cancellation_reason.as_ref(), amount_to_capture: attempt.amount_to_capture, mandate_id: attempt.mandate_id.as_ref(), browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), error_code: attempt.error_code.as_ref(), connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), payment_experience: attempt.payment_experience.as_ref(), payment_method_type: attempt.payment_method_type.as_ref(), payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()), error_reason: attempt.error_reason.as_ref(), multiple_capture_count: attempt.multiple_capture_count, amount_capturable: attempt.amount_capturable, merchant_connector_id: attempt.merchant_connector_id.as_ref(), net_amount: attempt.net_amount.get_total_amount(), unified_code: attempt.unified_code.as_ref(), unified_message: attempt.unified_message.as_ref(), mandate_data: attempt.mandate_data.as_ref(), client_source: attempt.client_source.as_ref(), client_version: attempt.client_version.as_ref(), profile_id: &attempt.profile_id, organization_id: &attempt.organization_id, card_network: attempt .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|pm| pm.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), card_discovery: attempt .card_discovery .map(|discovery| discovery.to_string()), } } } #[cfg(feature = "v2")] impl<'a> KafkaPaymentAttemptEvent<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { todo!() // Self { // payment_id: &attempt.payment_id, // merchant_id: &attempt.merchant_id, // attempt_id: &attempt.attempt_id, // status: attempt.status, // amount: attempt.amount, // currency: attempt.currency, // save_to_locker: attempt.save_to_locker, // connector: attempt.connector.as_ref(), // error_message: attempt.error_message.as_ref(), // offer_amount: attempt.offer_amount, // surcharge_amount: attempt.surcharge_amount, // tax_amount: attempt.tax_amount, // payment_method_id: attempt.payment_method_id.as_ref(), // payment_method: attempt.payment_method, // connector_transaction_id: attempt.connector_transaction_id.as_ref(), // capture_method: attempt.capture_method, // capture_on: attempt.capture_on.map(|i| i.assume_utc()), // confirm: attempt.confirm, // authentication_type: attempt.authentication_type, // created_at: attempt.created_at.assume_utc(), // modified_at: attempt.modified_at.assume_utc(), // last_synced: attempt.last_synced.map(|i| i.assume_utc()), // cancellation_reason: attempt.cancellation_reason.as_ref(), // amount_to_capture: attempt.amount_to_capture, // mandate_id: attempt.mandate_id.as_ref(), // browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), // error_code: attempt.error_code.as_ref(), // connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), // payment_experience: attempt.payment_experience.as_ref(), // payment_method_type: attempt.payment_method_type.as_ref(), // payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()), // error_reason: attempt.error_reason.as_ref(), // multiple_capture_count: attempt.multiple_capture_count, // amount_capturable: attempt.amount_capturable, // merchant_connector_id: attempt.merchant_connector_id.as_ref(), // net_amount: attempt.net_amount, // unified_code: attempt.unified_code.as_ref(), // unified_message: attempt.unified_message.as_ref(), // mandate_data: attempt.mandate_data.as_ref(), // client_source: attempt.client_source.as_ref(), // client_version: attempt.client_version.as_ref(), // profile_id: &attempt.profile_id, // organization_id: &attempt.organization_id, // card_network: attempt // .payment_method_data // .as_ref() // .and_then(|data| data.as_object()) // .and_then(|pm| pm.get("card")) // .and_then(|data| data.as_object()) // .and_then(|card| card.get("card_network")) // .and_then(|network| network.as_str()) // .map(|network| network.to_string()), // } } } impl super::KafkaMessage for KafkaPaymentAttemptEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentAttempt } }
2,081
1,324
hyperswitch
crates/router/src/services/kafka/payout.rs
.rs
use common_utils::{id_type, pii, types::MinorUnit}; use diesel_models::enums as storage_enums; use hyperswitch_domain_models::payouts::{payout_attempt::PayoutAttempt, payouts::Payouts}; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaPayout<'a> { pub payout_id: &'a String, pub payout_attempt_id: &'a String, pub merchant_id: &'a id_type::MerchantId, pub customer_id: Option<&'a id_type::CustomerId>, pub address_id: Option<&'a String>, pub profile_id: &'a id_type::ProfileId, pub payout_method_id: Option<&'a String>, pub payout_type: Option<storage_enums::PayoutType>, pub amount: MinorUnit, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub description: Option<&'a String>, pub recurring: bool, pub auto_fulfill: bool, pub return_url: Option<&'a String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp")] pub last_modified_at: OffsetDateTime, pub attempt_count: i16, pub status: storage_enums::PayoutStatus, pub priority: Option<storage_enums::PayoutSendPriority>, pub connector: Option<&'a String>, pub connector_payout_id: Option<&'a String>, pub is_eligible: Option<bool>, pub error_message: Option<&'a String>, pub error_code: Option<&'a String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<&'a String>, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, } impl<'a> KafkaPayout<'a> { pub fn from_storage(payouts: &'a Payouts, payout_attempt: &'a PayoutAttempt) -> Self { Self { payout_id: &payouts.payout_id, payout_attempt_id: &payout_attempt.payout_attempt_id, merchant_id: &payouts.merchant_id, customer_id: payouts.customer_id.as_ref(), address_id: payouts.address_id.as_ref(), profile_id: &payouts.profile_id, payout_method_id: payouts.payout_method_id.as_ref(), payout_type: payouts.payout_type, amount: payouts.amount, destination_currency: payouts.destination_currency, source_currency: payouts.source_currency, description: payouts.description.as_ref(), recurring: payouts.recurring, auto_fulfill: payouts.auto_fulfill, return_url: payouts.return_url.as_ref(), entity_type: payouts.entity_type, metadata: payouts.metadata.clone(), created_at: payouts.created_at.assume_utc(), last_modified_at: payouts.last_modified_at.assume_utc(), attempt_count: payouts.attempt_count, status: payouts.status, priority: payouts.priority, connector: payout_attempt.connector.as_ref(), connector_payout_id: payout_attempt.connector_payout_id.as_ref(), is_eligible: payout_attempt.is_eligible, error_message: payout_attempt.error_message.as_ref(), error_code: payout_attempt.error_code.as_ref(), business_country: payout_attempt.business_country, business_label: payout_attempt.business_label.as_ref(), merchant_connector_id: payout_attempt.merchant_connector_id.as_ref(), } } } impl super::KafkaMessage for KafkaPayout<'_> { fn key(&self) -> String { format!( "{}_{}", self.merchant_id.get_string_repr(), self.payout_attempt_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Payout } }
860
1,325
hyperswitch
crates/router/src/services/kafka/payment_intent_event.rs
.rs
use common_utils::{crypto::Encryptable, hashing::HashedString, id_type, pii, types::MinorUnit}; use diesel_models::enums as storage_enums; use hyperswitch_domain_models::payments::PaymentIntent; use masking::{PeekInterface, Secret}; use serde_json::Value; use time::OffsetDateTime; #[cfg(feature = "v1")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntentEvent<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a 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<&'a id_type::CustomerId>, pub description: Option<&'a String>, pub return_url: Option<&'a String>, pub metadata: Option<String>, pub connector_id: Option<&'a String>, pub statement_descriptor_name: Option<&'a String>, pub statement_descriptor_suffix: Option<&'a String>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<&'a String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<&'a String>, pub attempt_count: i16, pub profile_id: Option<&'a id_type::ProfileId>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub billing_details: Option<Encryptable<Secret<Value>>>, pub shipping_details: Option<Encryptable<Secret<Value>>>, pub customer_email: Option<HashedString<pii::EmailStrategy>>, pub feature_metadata: Option<&'a Value>, pub merchant_order_reference_id: Option<&'a String>, pub organization_id: &'a id_type::OrganizationId, } #[cfg(feature = "v2")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntentEvent<'a> { pub id: &'a id_type::PaymentId, pub merchant_id: &'a 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<&'a id_type::CustomerId>, pub description: Option<&'a String>, pub return_url: Option<&'a String>, pub metadata: Option<String>, pub statement_descriptor: Option<&'a String>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<&'a String>, pub active_attempt_id: String, pub attempt_count: i16, pub profile_id: &'a id_type::ProfileId, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub billing_details: Option<Encryptable<Secret<Value>>>, pub shipping_details: Option<Encryptable<Secret<Value>>>, pub customer_email: Option<HashedString<pii::EmailStrategy>>, pub feature_metadata: Option<&'a Value>, pub merchant_order_reference_id: Option<&'a String>, pub organization_id: &'a id_type::OrganizationId, } impl KafkaPaymentIntentEvent<'_> { #[cfg(feature = "v1")] pub fn get_id(&self) -> &id_type::PaymentId { self.payment_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &id_type::PaymentId { self.id } } #[cfg(feature = "v1")] impl<'a> KafkaPaymentIntentEvent<'a> { pub fn from_storage(intent: &'a PaymentIntent) -> Self { Self { payment_id: &intent.payment_id, merchant_id: &intent.merchant_id, status: intent.status, amount: intent.amount, currency: intent.currency, amount_captured: intent.amount_captured, customer_id: intent.customer_id.as_ref(), description: intent.description.as_ref(), return_url: intent.return_url.as_ref(), metadata: intent.metadata.as_ref().map(|x| x.to_string()), connector_id: intent.connector_id.as_ref(), statement_descriptor_name: intent.statement_descriptor_name.as_ref(), statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(), created_at: intent.created_at.assume_utc(), modified_at: intent.modified_at.assume_utc(), last_synced: intent.last_synced.map(|i| i.assume_utc()), setup_future_usage: intent.setup_future_usage, off_session: intent.off_session, client_secret: intent.client_secret.as_ref(), active_attempt_id: intent.active_attempt.get_id(), business_country: intent.business_country, business_label: intent.business_label.as_ref(), attempt_count: intent.attempt_count, profile_id: intent.profile_id.as_ref(), payment_confirm_source: intent.payment_confirm_source, // TODO: use typed information here to avoid PII logging billing_details: None, shipping_details: None, customer_email: intent .customer_details .as_ref() .and_then(|value| value.get_inner().peek().as_object()) .and_then(|obj| obj.get("email")) .and_then(|email| email.as_str()) .map(|email| HashedString::from(Secret::new(email.to_string()))), feature_metadata: intent.feature_metadata.as_ref(), merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(), organization_id: &intent.organization_id, } } } #[cfg(feature = "v2")] impl<'a> KafkaPaymentIntentEvent<'a> { pub fn from_storage(intent: &'a PaymentIntent) -> Self { // Self { // id: &intent.id, // merchant_id: &intent.merchant_id, // status: intent.status, // amount: intent.amount, // currency: intent.currency, // amount_captured: intent.amount_captured, // customer_id: intent.customer_id.as_ref(), // description: intent.description.as_ref(), // return_url: intent.return_url.as_ref(), // metadata: intent.metadata.as_ref().map(|x| x.to_string()), // statement_descriptor: intent.statement_descriptor.as_ref(), // created_at: intent.created_at.assume_utc(), // modified_at: intent.modified_at.assume_utc(), // last_synced: intent.last_synced.map(|i| i.assume_utc()), // setup_future_usage: intent.setup_future_usage, // off_session: intent.off_session, // client_secret: intent.client_secret.as_ref(), // active_attempt_id: intent.active_attempt.get_id(), // attempt_count: intent.attempt_count, // profile_id: &intent.profile_id, // payment_confirm_source: intent.payment_confirm_source, // // TODO: use typed information here to avoid PII logging // billing_details: None, // shipping_details: None, // customer_email: intent // .customer_details // .as_ref() // .and_then(|value| value.get_inner().peek().as_object()) // .and_then(|obj| obj.get("email")) // .and_then(|email| email.as_str()) // .map(|email| HashedString::from(Secret::new(email.to_string()))), // feature_metadata: intent.feature_metadata.as_ref(), // merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(), // organization_id: &intent.organization_id, // } todo!() } } impl super::KafkaMessage for KafkaPaymentIntentEvent<'_> { fn key(&self) -> String { format!( "{}_{}", self.merchant_id.get_string_repr(), self.get_id().get_string_repr(), ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentIntent } }
1,944
1,326
hyperswitch
crates/router/src/services/kafka/fraud_check_event.rs
.rs
use diesel_models::{ enums as storage_enums, enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, fraud_check::FraudCheck, }; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaFraudCheckEvent<'a> { pub frm_id: &'a String, pub payment_id: &'a common_utils::id_type::PaymentId, pub merchant_id: &'a common_utils::id_type::MerchantId, pub attempt_id: &'a String, #[serde(default, with = "time::serde::timestamp::milliseconds")] pub created_at: OffsetDateTime, pub frm_name: &'a String, pub frm_transaction_id: Option<&'a 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<&'a String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, #[serde(default, with = "time::serde::timestamp::milliseconds")] pub modified_at: OffsetDateTime, 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. } impl<'a> KafkaFraudCheckEvent<'a> { pub fn from_storage(check: &'a FraudCheck) -> Self { Self { frm_id: &check.frm_id, payment_id: &check.payment_id, merchant_id: &check.merchant_id, attempt_id: &check.attempt_id, created_at: check.created_at.assume_utc(), frm_name: &check.frm_name, frm_transaction_id: check.frm_transaction_id.as_ref(), frm_transaction_type: check.frm_transaction_type, frm_status: check.frm_status, frm_score: check.frm_score, frm_reason: check.frm_reason.clone(), frm_error: check.frm_error.as_ref(), payment_details: check.payment_details.clone(), metadata: check.metadata.clone(), modified_at: check.modified_at.assume_utc(), last_step: check.last_step, payment_capture_method: check.payment_capture_method, } } } impl super::KafkaMessage for KafkaFraudCheckEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id, self.frm_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::FraudCheck } }
629
1,327
hyperswitch
crates/router/src/services/kafka/payment_attempt.rs
.rs
// use diesel_models::enums::MandateDetails; use common_utils::{id_type, types::MinorUnit}; use diesel_models::enums as storage_enums; use hyperswitch_domain_models::{ mandates::MandateDetails, payments::payment_attempt::PaymentAttempt, }; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentAttempt<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub attempt_id: &'a String, pub status: storage_enums::AttemptStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub save_to_locker: Option<bool>, pub connector: Option<&'a String>, pub error_message: Option<&'a String>, pub offer_amount: Option<MinorUnit>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<&'a String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<&'a String>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "time::serde::timestamp::option")] pub capture_on: Option<OffsetDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::option")] pub last_synced: Option<OffsetDateTime>, pub cancellation_reason: Option<&'a String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<&'a String>, pub browser_info: Option<String>, pub error_code: Option<&'a String>, pub connector_metadata: Option<String>, // TODO: These types should implement copy ideally pub payment_experience: Option<&'a storage_enums::PaymentExperience>, pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>, pub payment_method_data: Option<String>, pub error_reason: Option<&'a String>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, pub net_amount: MinorUnit, pub unified_code: Option<&'a String>, pub unified_message: Option<&'a String>, pub mandate_data: Option<&'a MandateDetails>, pub client_source: Option<&'a String>, pub client_version: Option<&'a String>, pub profile_id: &'a id_type::ProfileId, pub organization_id: &'a id_type::OrganizationId, pub card_network: Option<String>, pub card_discovery: Option<String>, } #[cfg(feature = "v1")] impl<'a> KafkaPaymentAttempt<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { Self { payment_id: &attempt.payment_id, merchant_id: &attempt.merchant_id, attempt_id: &attempt.attempt_id, status: attempt.status, amount: attempt.net_amount.get_order_amount(), currency: attempt.currency, save_to_locker: attempt.save_to_locker, connector: attempt.connector.as_ref(), error_message: attempt.error_message.as_ref(), offer_amount: attempt.offer_amount, surcharge_amount: attempt.net_amount.get_surcharge_amount(), tax_amount: attempt.net_amount.get_tax_on_surcharge(), payment_method_id: attempt.payment_method_id.as_ref(), payment_method: attempt.payment_method, connector_transaction_id: attempt.connector_transaction_id.as_ref(), capture_method: attempt.capture_method, capture_on: attempt.capture_on.map(|i| i.assume_utc()), confirm: attempt.confirm, authentication_type: attempt.authentication_type, created_at: attempt.created_at.assume_utc(), modified_at: attempt.modified_at.assume_utc(), last_synced: attempt.last_synced.map(|i| i.assume_utc()), cancellation_reason: attempt.cancellation_reason.as_ref(), amount_to_capture: attempt.amount_to_capture, mandate_id: attempt.mandate_id.as_ref(), browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), error_code: attempt.error_code.as_ref(), connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), payment_experience: attempt.payment_experience.as_ref(), payment_method_type: attempt.payment_method_type.as_ref(), payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()), error_reason: attempt.error_reason.as_ref(), multiple_capture_count: attempt.multiple_capture_count, amount_capturable: attempt.amount_capturable, merchant_connector_id: attempt.merchant_connector_id.as_ref(), net_amount: attempt.net_amount.get_total_amount(), unified_code: attempt.unified_code.as_ref(), unified_message: attempt.unified_message.as_ref(), mandate_data: attempt.mandate_data.as_ref(), client_source: attempt.client_source.as_ref(), client_version: attempt.client_version.as_ref(), profile_id: &attempt.profile_id, organization_id: &attempt.organization_id, card_network: attempt .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|pm| pm.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), card_discovery: attempt .card_discovery .map(|discovery| discovery.to_string()), } } } #[cfg(feature = "v2")] impl<'a> KafkaPaymentAttempt<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { todo!() // Self { // payment_id: &attempt.payment_id, // merchant_id: &attempt.merchant_id, // attempt_id: &attempt.attempt_id, // status: attempt.status, // amount: attempt.amount, // currency: attempt.currency, // save_to_locker: attempt.save_to_locker, // connector: attempt.connector.as_ref(), // error_message: attempt.error_message.as_ref(), // offer_amount: attempt.offer_amount, // surcharge_amount: attempt.surcharge_amount, // tax_amount: attempt.tax_amount, // payment_method_id: attempt.payment_method_id.as_ref(), // payment_method: attempt.payment_method, // connector_transaction_id: attempt.connector_transaction_id.as_ref(), // capture_method: attempt.capture_method, // capture_on: attempt.capture_on.map(|i| i.assume_utc()), // confirm: attempt.confirm, // authentication_type: attempt.authentication_type, // created_at: attempt.created_at.assume_utc(), // modified_at: attempt.modified_at.assume_utc(), // last_synced: attempt.last_synced.map(|i| i.assume_utc()), // cancellation_reason: attempt.cancellation_reason.as_ref(), // amount_to_capture: attempt.amount_to_capture, // mandate_id: attempt.mandate_id.as_ref(), // browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), // error_code: attempt.error_code.as_ref(), // connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), // payment_experience: attempt.payment_experience.as_ref(), // payment_method_type: attempt.payment_method_type.as_ref(), // payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()), // error_reason: attempt.error_reason.as_ref(), // multiple_capture_count: attempt.multiple_capture_count, // amount_capturable: attempt.amount_capturable, // merchant_connector_id: attempt.merchant_connector_id.as_ref(), // net_amount: attempt.net_amount, // unified_code: attempt.unified_code.as_ref(), // unified_message: attempt.unified_message.as_ref(), // mandate_data: attempt.mandate_data.as_ref(), // client_source: attempt.client_source.as_ref(), // client_version: attempt.client_version.as_ref(), // profile_id: &attempt.profile_id, // organization_id: &attempt.organization_id, // card_network: attempt // .payment_method_data // .as_ref() // .and_then(|data| data.as_object()) // .and_then(|pm| pm.get("card")) // .and_then(|data| data.as_object()) // .and_then(|card| card.get("card_network")) // .and_then(|network| network.as_str()) // .map(|network| network.to_string()), // } } } impl super::KafkaMessage for KafkaPaymentAttempt<'_> { fn key(&self) -> String { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentAttempt } }
2,056
1,328
hyperswitch
crates/router/src/services/redirection/assets/redirect_error_logs_push.js
.js
function parseRoute(url) { const route = new URL(url).pathname; const regex = /^\/payments\/redirect\/([^/]+)\/([^/]+)\/([^/]+)$|^\/payments\/([^/]+)\/([^/]+)\/redirect\/response\/([^/]+)(?:\/([^/]+)\/?)?$|^\/payments\/([^/]+)\/([^/]+)\/redirect\/complete\/([^/]+)$/; const matches = route.match(regex); const attemptIdExists = !( route.includes("response") || route.includes("complete") ); if (matches) { const [, paymentId, merchantId, attemptId, connector,credsIdentifier] = matches; return { paymentId, merchantId, attemptId: attemptIdExists ? attemptId : "", connector }; } else { return { paymentId: "", merchantId: "", attemptId: "", connector: "", }; } } function getEnvRoute(url) { const route = new URL(url).hostname; return route === "api.hyperswitch.io" ? "https://api.hyperswitch.io/logs/redirection" : "https://sandbox.hyperswitch.io/logs/redirection"; } async function postLog(log, urlToPost) { try { const response = await fetch(urlToPost, { method: "POST", mode: "no-cors", body: JSON.stringify(log), headers: { Accept: "application/json", "Content-Type": "application/json", }, }); } catch (err) { console.error(`Error in logging: ${err}`); } } window.addEventListener("error", (event) => { let url = window.location.href; let { paymentId, merchantId, attemptId, connector } = parseRoute(url); let urlToPost = getEnvRoute(url); let log = { message: event.message, url, paymentId, merchantId, attemptId, connector, }; postLog(log, urlToPost); }); window.addEventListener("message", (event) => { let url = window.location.href; let { paymentId, merchantId, attemptId, connector } = parseRoute(url); let urlToPost = getEnvRoute(url); let log = { message: event.data, url, paymentId, merchantId, attemptId, connector, }; postLog(log, urlToPost); });
543
1,329
hyperswitch
crates/router/src/services/authentication/cookies.rs
.rs
use cookie::Cookie; #[cfg(feature = "olap")] use cookie::{ time::{Duration, OffsetDateTime}, SameSite, }; use error_stack::{report, ResultExt}; #[cfg(feature = "olap")] use masking::Mask; #[cfg(feature = "olap")] use masking::{ExposeInterface, Secret}; use crate::{ consts::JWT_TOKEN_COOKIE_NAME, core::errors::{ApiErrorResponse, RouterResult}, }; #[cfg(feature = "olap")] use crate::{ consts::JWT_TOKEN_TIME_IN_SECS, core::errors::{UserErrors, UserResponse}, services::ApplicationResponse, }; #[cfg(feature = "olap")] pub fn set_cookie_response<R>(response: R, token: Secret<String>) -> UserResponse<R> { let jwt_expiry_in_seconds = JWT_TOKEN_TIME_IN_SECS .try_into() .map_err(|_| UserErrors::InternalServerError)?; let (expiry, max_age) = get_expiry_and_max_age_from_seconds(jwt_expiry_in_seconds); let header_value = create_cookie(token, expiry, max_age) .to_string() .into_masked(); let header_key = get_set_cookie_header(); let header = vec![(header_key, header_value)]; Ok(ApplicationResponse::JsonWithHeaders((response, header))) } #[cfg(feature = "olap")] pub fn remove_cookie_response() -> UserResponse<()> { let (expiry, max_age) = get_expiry_and_max_age_from_seconds(0); let header_key = get_set_cookie_header(); let header_value = create_cookie("".to_string().into(), expiry, max_age) .to_string() .into_masked(); let header = vec![(header_key, header_value)]; Ok(ApplicationResponse::JsonWithHeaders(((), header))) } pub fn get_jwt_from_cookies(cookies: &str) -> RouterResult<String> { Cookie::split_parse(cookies) .find_map(|cookie| { cookie .ok() .filter(|parsed_cookie| parsed_cookie.name() == JWT_TOKEN_COOKIE_NAME) .map(|parsed_cookie| parsed_cookie.value().to_owned()) }) .ok_or(report!(ApiErrorResponse::InvalidJwtToken)) .attach_printable("Unable to find JWT token in cookies") } #[cfg(feature = "olap")] fn create_cookie<'c>( token: Secret<String>, expires: OffsetDateTime, max_age: Duration, ) -> Cookie<'c> { Cookie::build((JWT_TOKEN_COOKIE_NAME, token.expose())) .http_only(true) .secure(true) .same_site(SameSite::Strict) .path("/") .expires(expires) .max_age(max_age) .build() } #[cfg(feature = "olap")] fn get_expiry_and_max_age_from_seconds(seconds: i64) -> (OffsetDateTime, Duration) { let max_age = Duration::seconds(seconds); let expiry = OffsetDateTime::now_utc().saturating_add(max_age); (expiry, max_age) } #[cfg(feature = "olap")] fn get_set_cookie_header() -> String { actix_http::header::SET_COOKIE.to_string() } pub fn get_cookie_header() -> String { actix_http::header::COOKIE.to_string() }
691
1,330
hyperswitch
crates/router/src/services/authentication/decision.rs
.rs
use common_utils::{errors::CustomResult, request::RequestContent}; use masking::{ErasedMaskSerialize, Secret}; use serde::Serialize; use storage_impl::errors::ApiClientError; use crate::{ core::metrics, routes::{app::settings::DecisionConfig, SessionState}, }; // # Consts // const DECISION_ENDPOINT: &str = "/rule"; const RULE_ADD_METHOD: common_utils::request::Method = common_utils::request::Method::Post; const RULE_DELETE_METHOD: common_utils::request::Method = common_utils::request::Method::Delete; pub const REVOKE: &str = "REVOKE"; pub const ADD: &str = "ADD"; // # Types // /// [`RuleRequest`] is a request body used to register a new authentication method in the proxy. #[derive(Debug, Serialize)] pub struct RuleRequest { /// [`tag`] similar to a partition key, which can be used by the decision service to tag rules /// by partitioning identifiers. (e.g. `tenant_id`) pub tag: String, /// [`variant`] is the type of authentication method to be registered. #[serde(flatten)] pub variant: AuthRuleType, /// [`expiry`] is the time **in seconds** after which the rule should be removed pub expiry: Option<u64>, } #[derive(Debug, Serialize)] pub struct RuleDeleteRequest { pub tag: String, #[serde(flatten)] pub variant: AuthType, } #[derive(Debug, Serialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum AuthType { /// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`] ApiKey { api_key: Secret<String> }, } #[derive(Debug, Serialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum AuthRuleType { /// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`] /// and [`PublishableKey`] authentication methods. ApiKey { api_key: Secret<String>, identifiers: Identifiers, }, } #[allow(clippy::enum_variant_names)] #[derive(Debug, Serialize, Clone)] #[serde(tag = "type", rename_all = "snake_case")] pub enum Identifiers { /// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`] ApiKey { merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, }, /// [`PublishableKey`] is an authentication method that uses a publishable key. This is used with [`PublishableKey`] PublishableKey { merchant_id: String }, } // # Decision Service // pub async fn add_api_key( state: &SessionState, api_key: Secret<String>, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, expiry: Option<u64>, ) -> CustomResult<(), ApiClientError> { let decision_config = if let Some(config) = &state.conf.decision { config } else { return Ok(()); }; let rule = RuleRequest { tag: state.tenant.schema.clone(), expiry, variant: AuthRuleType::ApiKey { api_key, identifiers: Identifiers::ApiKey { merchant_id, key_id, }, }, }; call_decision_service(state, decision_config, rule, RULE_ADD_METHOD).await } pub async fn add_publishable_key( state: &SessionState, api_key: Secret<String>, merchant_id: common_utils::id_type::MerchantId, expiry: Option<u64>, ) -> CustomResult<(), ApiClientError> { let decision_config = if let Some(config) = &state.conf.decision { config } else { return Ok(()); }; let rule = RuleRequest { tag: state.tenant.schema.clone(), expiry, variant: AuthRuleType::ApiKey { api_key, identifiers: Identifiers::PublishableKey { merchant_id: merchant_id.get_string_repr().to_owned(), }, }, }; call_decision_service(state, decision_config, rule, RULE_ADD_METHOD).await } async fn call_decision_service<T: ErasedMaskSerialize + Send + 'static>( state: &SessionState, decision_config: &DecisionConfig, rule: T, method: common_utils::request::Method, ) -> CustomResult<(), ApiClientError> { let mut request = common_utils::request::Request::new( method, &(decision_config.base_url.clone() + DECISION_ENDPOINT), ); request.set_body(RequestContent::Json(Box::new(rule))); request.add_default_headers(); let response = state .api_client .send_request(state, request, None, false) .await; match response { Err(error) => { router_env::error!("Failed while calling the decision service: {:?}", error); Err(error) } Ok(response) => { router_env::info!("Decision service response: {:?}", response); Ok(()) } } } pub async fn revoke_api_key( state: &SessionState, api_key: Secret<String>, ) -> CustomResult<(), ApiClientError> { let decision_config = if let Some(config) = &state.conf.decision { config } else { return Ok(()); }; let rule = RuleDeleteRequest { tag: state.tenant.schema.clone(), variant: AuthType::ApiKey { api_key }, }; call_decision_service(state, decision_config, rule, RULE_DELETE_METHOD).await } /// Safety: i64::MAX < u64::MAX #[allow(clippy::as_conversions)] pub fn convert_expiry(expiry: time::PrimitiveDateTime) -> u64 { let now = common_utils::date_time::now(); let duration = expiry - now; let output = duration.whole_seconds(); match output { i64::MIN..=0 => 0, _ => output as u64, } } pub fn spawn_tracked_job<E, F>(future: F, request_type: &'static str) where E: std::fmt::Debug, F: futures::Future<Output = Result<(), E>> + Send + 'static, { metrics::API_KEY_REQUEST_INITIATED .add(1, router_env::metric_attributes!(("type", request_type))); tokio::spawn(async move { match future.await { Ok(_) => { metrics::API_KEY_REQUEST_COMPLETED .add(1, router_env::metric_attributes!(("type", request_type))); } Err(e) => { router_env::error!("Error in tracked job: {:?}", e); } } }); }
1,475
1,331
hyperswitch
crates/router/src/services/authentication/detached.rs
.rs
use std::{borrow::Cow, string::ToString}; use actix_web::http::header::HeaderMap; use common_utils::{ crypto::VerifySignature, id_type::{ApiKeyId, MerchantId}, }; use error_stack::ResultExt; use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; use crate::core::errors::RouterResult; const HEADER_AUTH_TYPE: &str = "x-auth-type"; const HEADER_MERCHANT_ID: &str = "x-merchant-id"; const HEADER_KEY_ID: &str = "x-key-id"; const HEADER_CHECKSUM: &str = "x-checksum"; #[derive(Debug)] pub struct ExtractedPayload { pub payload_type: PayloadType, pub merchant_id: Option<MerchantId>, pub key_id: Option<ApiKeyId>, } #[derive(strum::EnumString, strum::Display, PartialEq, Debug)] #[strum(serialize_all = "snake_case")] pub enum PayloadType { ApiKey, PublishableKey, } pub trait GetAuthType { fn get_auth_type(&self) -> PayloadType; } impl ExtractedPayload { pub fn from_headers(headers: &HeaderMap) -> RouterResult<Self> { let merchant_id = headers .get(HEADER_MERCHANT_ID) .and_then(|value| value.to_str().ok()) .ok_or_else(|| ApiErrorResponse::InvalidRequestData { message: format!("`{}` header is invalid or not present", HEADER_MERCHANT_ID), }) .map_err(error_stack::Report::from) .and_then(|merchant_id| { MerchantId::try_from(Cow::from(merchant_id.to_string())).change_context( ApiErrorResponse::InvalidRequestData { message: format!( "`{}` header is invalid or not present", HEADER_MERCHANT_ID ), }, ) })?; let auth_type: PayloadType = headers .get(HEADER_AUTH_TYPE) .and_then(|inner| inner.to_str().ok()) .ok_or_else(|| ApiErrorResponse::InvalidRequestData { message: format!("`{}` header not present", HEADER_AUTH_TYPE), })? .parse::<PayloadType>() .change_context(ApiErrorResponse::InvalidRequestData { message: format!("`{}` header not present", HEADER_AUTH_TYPE), })?; let key_id = headers .get(HEADER_KEY_ID) .and_then(|value| value.to_str().ok()) .map(|key_id| ApiKeyId::try_from(Cow::from(key_id.to_string()))) .transpose() .change_context(ApiErrorResponse::InvalidRequestData { message: format!("`{}` header is invalid or not present", HEADER_KEY_ID), })?; Ok(Self { payload_type: auth_type, merchant_id: Some(merchant_id), key_id, }) } pub fn verify_checksum( &self, headers: &HeaderMap, algo: impl VerifySignature, secret: &[u8], ) -> bool { let output = || { let checksum = headers.get(HEADER_CHECKSUM)?.to_str().ok()?; let payload = self.generate_payload(); algo.verify_signature(secret, &hex::decode(checksum).ok()?, payload.as_bytes()) .ok() }; output().unwrap_or(false) } // The payload should be `:` separated strings of all the fields fn generate_payload(&self) -> String { append_option( &self.payload_type.to_string(), &self .merchant_id .as_ref() .map(|inner| append_api_key(inner.get_string_repr(), &self.key_id)), ) } } #[inline] fn append_option(prefix: &str, data: &Option<String>) -> String { match data { Some(inner) => format!("{}:{}", prefix, inner), None => prefix.to_string(), } } #[inline] fn append_api_key(prefix: &str, data: &Option<ApiKeyId>) -> String { match data { Some(inner) => format!("{}:{}", prefix, inner.get_string_repr()), None => prefix.to_string(), } }
887
1,332
hyperswitch
crates/router/src/services/authentication/blacklist.rs
.rs
use std::sync::Arc; #[cfg(feature = "olap")] use common_utils::date_time; use error_stack::ResultExt; use redis_interface::RedisConnectionPool; use super::AuthToken; #[cfg(feature = "olap")] use super::{SinglePurposeOrLoginToken, SinglePurposeToken}; #[cfg(feature = "email")] use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS}; use crate::{ consts::{JWT_TOKEN_TIME_IN_SECS, ROLE_BLACKLIST_PREFIX, USER_BLACKLIST_PREFIX}, core::errors::{ApiErrorResponse, RouterResult}, routes::app::SessionStateInfo, }; #[cfg(feature = "olap")] use crate::{ core::errors::{UserErrors, UserResult}, routes::SessionState, services::authorization as authz, }; #[cfg(feature = "olap")] pub async fn insert_user_in_blacklist(state: &SessionState, user_id: &str) -> UserResult<()> { let user_blacklist_key = format!("{}{}", USER_BLACKLIST_PREFIX, user_id); let expiry = expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry( &user_blacklist_key.as_str().into(), date_time::now_unix_timestamp(), expiry, ) .await .change_context(UserErrors::InternalServerError) } #[cfg(feature = "olap")] pub async fn insert_role_in_blacklist(state: &SessionState, role_id: &str) -> UserResult<()> { let role_blacklist_key = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id); let expiry = expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry( &role_blacklist_key.as_str().into(), date_time::now_unix_timestamp(), expiry, ) .await .change_context(UserErrors::InternalServerError)?; invalidate_role_cache(state, role_id) .await .change_context(UserErrors::InternalServerError) } #[cfg(feature = "olap")] async fn invalidate_role_cache(state: &SessionState, role_id: &str) -> RouterResult<()> { let redis_conn = get_redis_connection(state)?; redis_conn .delete_key(&authz::get_cache_key_from_role_id(role_id).as_str().into()) .await .map(|_| ()) .change_context(ApiErrorResponse::InternalServerError) } pub async fn check_user_in_blacklist<A: SessionStateInfo>( state: &A, user_id: &str, token_expiry: u64, ) -> RouterResult<bool> { let token = format!("{}{}", USER_BLACKLIST_PREFIX, user_id); let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; let redis_conn = get_redis_connection(state)?; redis_conn .get_key::<Option<i64>>(&token.as_str().into()) .await .change_context(ApiErrorResponse::InternalServerError) .map(|timestamp| timestamp > Some(token_issued_at)) } pub async fn check_role_in_blacklist<A: SessionStateInfo>( state: &A, role_id: &str, token_expiry: u64, ) -> RouterResult<bool> { let token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id); let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; let redis_conn = get_redis_connection(state)?; redis_conn .get_key::<Option<i64>>(&token.as_str().into()) .await .change_context(ApiErrorResponse::InternalServerError) .map(|timestamp| timestamp > Some(token_issued_at)) } #[cfg(feature = "email")] pub async fn insert_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> { let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX); let expiry = expiry_to_i64(EMAIL_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry(&blacklist_key.as_str().into(), true, expiry) .await .change_context(UserErrors::InternalServerError) } #[cfg(feature = "email")] pub async fn check_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> { let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX); let key_exists = redis_conn .exists::<()>(&blacklist_key.as_str().into()) .await .change_context(UserErrors::InternalServerError)?; if key_exists { return Err(UserErrors::LinkInvalid.into()); } Ok(()) } fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { state .store() .get_redis_conn() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection") } fn expiry_to_i64(expiry: u64) -> RouterResult<i64> { i64::try_from(expiry).change_context(ApiErrorResponse::InternalServerError) } #[async_trait::async_trait] pub trait BlackList { async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool> where A: SessionStateInfo + Sync; } #[async_trait::async_trait] impl BlackList for AuthToken { async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool> where A: SessionStateInfo + Sync, { Ok( check_user_in_blacklist(state, &self.user_id, self.exp).await? || check_role_in_blacklist(state, &self.role_id, self.exp).await?, ) } } #[cfg(feature = "olap")] #[async_trait::async_trait] impl BlackList for SinglePurposeToken { async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool> where A: SessionStateInfo + Sync, { check_user_in_blacklist(state, &self.user_id, self.exp).await } } #[cfg(feature = "olap")] #[async_trait::async_trait] impl BlackList for SinglePurposeOrLoginToken { async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool> where A: SessionStateInfo + Sync, { check_user_in_blacklist(state, &self.user_id, self.exp).await } }
1,491
1,333
hyperswitch
crates/router/src/types/api.rs
.rs
pub mod admin; pub mod api_keys; pub mod authentication; pub mod configs; #[cfg(feature = "olap")] pub mod connector_onboarding; pub mod customers; pub mod disputes; pub mod enums; pub mod ephemeral_key; pub mod files; #[cfg(feature = "frm")] pub mod fraud_check; pub mod mandates; pub mod payment_link; pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod poll; pub mod refunds; pub mod routing; #[cfg(feature = "olap")] pub mod verify_connector; #[cfg(feature = "olap")] pub mod webhook_events; pub mod webhooks; pub mod authentication_v2; pub mod disputes_v2; pub mod files_v2; #[cfg(feature = "frm")] pub mod fraud_check_v2; pub mod payments_v2; #[cfg(feature = "payouts")] pub mod payouts_v2; pub mod refunds_v2; use std::{fmt::Debug, str::FromStr}; use api_models::routing::{self as api_routing, RoutableConnectorChoice}; use common_enums::RoutableConnectors; use error_stack::{report, ResultExt}; pub use hyperswitch_domain_models::router_flow_types::{ access_token_auth::AccessTokenAuth, mandate_revoke::MandateRevoke, webhooks::VerifyWebhookSource, }; pub use hyperswitch_interfaces::{ api::{ authentication::{ ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication, ConnectorPreAuthenticationVersionCall, ExternalAuthentication, }, authentication_v2::{ ConnectorAuthenticationV2, ConnectorPostAuthenticationV2, ConnectorPreAuthenticationV2, ConnectorPreAuthenticationVersionCallV2, ExternalAuthenticationV2, }, fraud_check::FraudCheck, revenue_recovery::{ BillingConnectorPaymentsSyncIntegration, RevenueRecovery, RevenueRecoveryRecordBack, }, revenue_recovery_v2::RevenueRecoveryV2, BoxedConnector, Connector, ConnectorAccessToken, ConnectorAccessTokenV2, ConnectorCommon, ConnectorCommonExt, ConnectorMandateRevoke, ConnectorMandateRevokeV2, ConnectorTransactionId, ConnectorVerifyWebhookSource, ConnectorVerifyWebhookSourceV2, CurrencyUnit, }, connector_integration_v2::{BoxedConnectorV2, ConnectorV2}, }; use rustc_hash::FxHashMap; #[cfg(feature = "frm")] pub use self::fraud_check::*; #[cfg(feature = "payouts")] pub use self::payouts::*; pub use self::{ admin::*, api_keys::*, authentication::*, configs::*, customers::*, disputes::*, files::*, payment_link::*, payment_methods::*, payments::*, poll::*, refunds::*, refunds_v2::*, webhooks::*, }; use super::transformers::ForeignTryFrom; use crate::{ configs::settings::Connectors, connector, consts, core::{ errors::{self, CustomResult}, payments::types as payments_types, }, services::connector_integration_interface::ConnectorEnum, types::{self, api::enums as api_enums}, }; #[derive(Clone)] pub enum ConnectorCallType { PreDetermined(ConnectorData), Retryable(Vec<ConnectorData>), SessionMultiple(SessionConnectorDatas), #[cfg(feature = "v2")] Skip, } // Normal flow will call the connector and follow the flow specific operations (capture, authorize) // SessionTokenFromMetadata will avoid calling the connector instead create the session token ( for sdk ) #[derive(Clone, Eq, PartialEq, Debug)] pub enum GetToken { GpayMetadata, SamsungPayMetadata, ApplePayMetadata, PaypalSdkMetadata, PazeMetadata, Connector, } /// Routing algorithm will output merchant connector identifier instead of connector name /// In order to support backwards compatibility for older routing algorithms and merchant accounts /// the support for connector name is retained #[derive(Clone, Debug)] pub struct ConnectorData { pub connector: ConnectorEnum, pub connector_name: types::Connector, pub get_token: GetToken, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Clone, Debug)] pub struct SessionConnectorData { pub payment_method_sub_type: api_enums::PaymentMethodType, pub payment_method_type: api_enums::PaymentMethod, pub connector: ConnectorData, pub business_sub_label: Option<String>, } impl SessionConnectorData { pub fn new( payment_method_sub_type: api_enums::PaymentMethodType, connector: ConnectorData, business_sub_label: Option<String>, payment_method_type: api_enums::PaymentMethod, ) -> Self { Self { payment_method_sub_type, connector, business_sub_label, payment_method_type, } } } common_utils::create_list_wrapper!( SessionConnectorDatas, SessionConnectorData, impl_functions: { pub fn apply_filter_for_session_routing(&self) -> Self { let routing_enabled_pmts = &consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES; let routing_enabled_pms = &consts::ROUTING_ENABLED_PAYMENT_METHODS; self .iter() .filter(|connector_data| { routing_enabled_pmts.contains(&connector_data.payment_method_sub_type) || routing_enabled_pms.contains(&connector_data.payment_method_type) }) .cloned() .collect() } pub fn filter_and_validate_for_session_flow(self, routing_results: &FxHashMap<api_enums::PaymentMethodType, Vec<routing::SessionRoutingChoice>>) -> Result<Self, errors::ApiErrorResponse> { let mut final_list = Self::new(Vec::new()); let routing_enabled_pmts = &consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES; for connector_data in self { if !routing_enabled_pmts.contains(&connector_data.payment_method_sub_type) { final_list.push(connector_data); } else if let Some(choice) = routing_results.get(&connector_data.payment_method_sub_type) { let routing_choice = choice .first() .ok_or(errors::ApiErrorResponse::InternalServerError)?; if connector_data.connector.connector_name == routing_choice.connector.connector_name && connector_data.connector.merchant_connector_id == routing_choice.connector.merchant_connector_id { final_list.push(connector_data); } } } Ok(final_list) } } ); pub fn convert_connector_data_to_routable_connectors( connectors: &[ConnectorData], ) -> CustomResult<Vec<RoutableConnectorChoice>, common_utils::errors::ValidationError> { connectors .iter() .map(|connector_data| RoutableConnectorChoice::foreign_try_from(connector_data.clone())) .collect() } impl ForeignTryFrom<ConnectorData> for RoutableConnectorChoice { type Error = error_stack::Report<common_utils::errors::ValidationError>; fn foreign_try_from(from: ConnectorData) -> Result<Self, Self::Error> { match RoutableConnectors::foreign_try_from(from.connector_name) { Ok(connector) => Ok(Self { choice_kind: api_routing::RoutableChoiceKind::FullStruct, connector, merchant_connector_id: from.merchant_connector_id, }), Err(e) => Err(common_utils::errors::ValidationError::InvalidValue { message: format!("This is not a routable connector: {:?}", e), })?, } } } /// Session Surcharge type pub enum SessionSurchargeDetails { /// Surcharge is calculated by hyperswitch Calculated(payments_types::SurchargeMetadata), /// Surcharge is sent by merchant PreDetermined(payments_types::SurchargeDetails), } impl SessionSurchargeDetails { pub fn fetch_surcharge_details( &self, payment_method: enums::PaymentMethod, payment_method_type: enums::PaymentMethodType, card_network: Option<&enums::CardNetwork>, ) -> Option<payments_types::SurchargeDetails> { match self { Self::Calculated(surcharge_metadata) => surcharge_metadata .get_surcharge_details(payments_types::SurchargeKey::PaymentMethodData( payment_method, payment_method_type, card_network.cloned(), )) .cloned(), Self::PreDetermined(surcharge_details) => Some(surcharge_details.clone()), } } } pub enum ConnectorChoice { SessionMultiple(SessionConnectorDatas), StraightThrough(serde_json::Value), Decide, } impl ConnectorData { pub fn get_connector_by_name( _connectors: &Connectors, name: &str, connector_type: GetToken, connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<Self, errors::ApiErrorResponse> { let connector = Self::convert_connector(name)?; let connector_name = api_enums::Connector::from_str(name) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("unable to parse connector name {name}"))?; Ok(Self { connector, connector_name, get_token: connector_type, merchant_connector_id: connector_id, }) } #[cfg(feature = "payouts")] pub fn get_payout_connector_by_name( _connectors: &Connectors, name: &str, connector_type: GetToken, connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<Self, errors::ApiErrorResponse> { let connector = Self::convert_connector(name)?; let payout_connector_name = api_enums::PayoutConnectors::from_str(name) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("unable to parse payout connector name {name}"))?; let connector_name = api_enums::Connector::from(payout_connector_name); Ok(Self { connector, connector_name, get_token: connector_type, merchant_connector_id: connector_id, }) } pub fn convert_connector( connector_name: &str, ) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> { match enums::Connector::from_str(connector_name) { Ok(name) => match name { enums::Connector::Aci => Ok(ConnectorEnum::Old(Box::new(connector::Aci::new()))), enums::Connector::Adyen => { Ok(ConnectorEnum::Old(Box::new(connector::Adyen::new()))) } enums::Connector::Adyenplatform => Ok(ConnectorEnum::Old(Box::new( connector::Adyenplatform::new(), ))), enums::Connector::Airwallex => { Ok(ConnectorEnum::Old(Box::new(&connector::Airwallex))) } // enums::Connector::Amazonpay => { // Ok(ConnectorEnum::Old(Box::new(connector::Amazonpay))) // } enums::Connector::Authorizedotnet => { Ok(ConnectorEnum::Old(Box::new(&connector::Authorizedotnet))) } enums::Connector::Bambora => Ok(ConnectorEnum::Old(Box::new(&connector::Bambora))), enums::Connector::Bamboraapac => { Ok(ConnectorEnum::Old(Box::new(connector::Bamboraapac::new()))) } enums::Connector::Bankofamerica => { Ok(ConnectorEnum::Old(Box::new(&connector::Bankofamerica))) } enums::Connector::Billwerk => { Ok(ConnectorEnum::Old(Box::new(connector::Billwerk::new()))) } enums::Connector::Bitpay => { Ok(ConnectorEnum::Old(Box::new(connector::Bitpay::new()))) } enums::Connector::Bluesnap => { Ok(ConnectorEnum::Old(Box::new(connector::Bluesnap::new()))) } enums::Connector::Boku => Ok(ConnectorEnum::Old(Box::new(connector::Boku::new()))), enums::Connector::Braintree => { Ok(ConnectorEnum::Old(Box::new(connector::Braintree::new()))) } enums::Connector::Cashtocode => { Ok(ConnectorEnum::Old(Box::new(connector::Cashtocode::new()))) } enums::Connector::Chargebee => { Ok(ConnectorEnum::Old(Box::new(connector::Chargebee::new()))) } enums::Connector::Checkout => { Ok(ConnectorEnum::Old(Box::new(connector::Checkout::new()))) } enums::Connector::Coinbase => { Ok(ConnectorEnum::Old(Box::new(&connector::Coinbase))) } enums::Connector::Coingate => { Ok(ConnectorEnum::Old(Box::new(connector::Coingate::new()))) } enums::Connector::Cryptopay => { Ok(ConnectorEnum::Old(Box::new(connector::Cryptopay::new()))) } enums::Connector::CtpMastercard => { Ok(ConnectorEnum::Old(Box::new(&connector::CtpMastercard))) } enums::Connector::CtpVisa => Ok(ConnectorEnum::Old(Box::new( connector::UnifiedAuthenticationService::new(), ))), enums::Connector::Cybersource => { Ok(ConnectorEnum::Old(Box::new(connector::Cybersource::new()))) } enums::Connector::Datatrans => { Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new()))) } enums::Connector::Deutschebank => { Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new()))) } enums::Connector::Digitalvirgo => { Ok(ConnectorEnum::Old(Box::new(connector::Digitalvirgo::new()))) } enums::Connector::Dlocal => Ok(ConnectorEnum::Old(Box::new(&connector::Dlocal))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector1 => Ok(ConnectorEnum::Old(Box::new( &connector::DummyConnector::<1>, ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector2 => Ok(ConnectorEnum::Old(Box::new( &connector::DummyConnector::<2>, ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector3 => Ok(ConnectorEnum::Old(Box::new( &connector::DummyConnector::<3>, ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector4 => Ok(ConnectorEnum::Old(Box::new( &connector::DummyConnector::<4>, ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector5 => Ok(ConnectorEnum::Old(Box::new( &connector::DummyConnector::<5>, ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector6 => Ok(ConnectorEnum::Old(Box::new( &connector::DummyConnector::<6>, ))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector7 => Ok(ConnectorEnum::Old(Box::new( &connector::DummyConnector::<7>, ))), enums::Connector::Ebanx => { Ok(ConnectorEnum::Old(Box::new(connector::Ebanx::new()))) } enums::Connector::Elavon => { Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new()))) } // enums::Connector::Facilitapay => { // Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay))) // } enums::Connector::Fiserv => { Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new()))) } enums::Connector::Fiservemea => { Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea::new()))) } enums::Connector::Fiuu => Ok(ConnectorEnum::Old(Box::new(connector::Fiuu::new()))), enums::Connector::Forte => { Ok(ConnectorEnum::Old(Box::new(connector::Forte::new()))) } enums::Connector::Getnet => { Ok(ConnectorEnum::Old(Box::new(connector::Getnet::new()))) } enums::Connector::Globalpay => { Ok(ConnectorEnum::Old(Box::new(connector::Globalpay::new()))) } enums::Connector::Globepay => { Ok(ConnectorEnum::Old(Box::new(connector::Globepay::new()))) } enums::Connector::Gocardless => { Ok(ConnectorEnum::Old(Box::new(&connector::Gocardless))) } enums::Connector::Hipay => { Ok(ConnectorEnum::Old(Box::new(connector::Hipay::new()))) } enums::Connector::Helcim => { Ok(ConnectorEnum::Old(Box::new(connector::Helcim::new()))) } enums::Connector::Iatapay => { Ok(ConnectorEnum::Old(Box::new(connector::Iatapay::new()))) } enums::Connector::Inespay => { Ok(ConnectorEnum::Old(Box::new(connector::Inespay::new()))) } enums::Connector::Itaubank => { Ok(ConnectorEnum::Old(Box::new(connector::Itaubank::new()))) } enums::Connector::Jpmorgan => { Ok(ConnectorEnum::Old(Box::new(connector::Jpmorgan::new()))) } enums::Connector::Juspaythreedsserver => Ok(ConnectorEnum::Old(Box::new( connector::Juspaythreedsserver::new(), ))), enums::Connector::Klarna => { Ok(ConnectorEnum::Old(Box::new(connector::Klarna::new()))) } enums::Connector::Mollie => { // enums::Connector::Moneris => Ok(ConnectorEnum::Old(Box::new(connector::Moneris))), Ok(ConnectorEnum::Old(Box::new(connector::Mollie::new()))) } enums::Connector::Moneris => { Ok(ConnectorEnum::Old(Box::new(connector::Moneris::new()))) } enums::Connector::Nexixpay => { Ok(ConnectorEnum::Old(Box::new(connector::Nexixpay::new()))) } enums::Connector::Nmi => Ok(ConnectorEnum::Old(Box::new(connector::Nmi::new()))), enums::Connector::Nomupay => { Ok(ConnectorEnum::Old(Box::new(connector::Nomupay::new()))) } enums::Connector::Noon => Ok(ConnectorEnum::Old(Box::new(connector::Noon::new()))), enums::Connector::Novalnet => { Ok(ConnectorEnum::Old(Box::new(connector::Novalnet::new()))) } enums::Connector::Nuvei => Ok(ConnectorEnum::Old(Box::new(&connector::Nuvei))), enums::Connector::Opennode => { Ok(ConnectorEnum::Old(Box::new(&connector::Opennode))) } enums::Connector::Paybox => { Ok(ConnectorEnum::Old(Box::new(connector::Paybox::new()))) } // "payeezy" => Ok(ConnectorIntegrationEnum::Old(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage enums::Connector::Payme => { Ok(ConnectorEnum::Old(Box::new(connector::Payme::new()))) } enums::Connector::Payone => { Ok(ConnectorEnum::Old(Box::new(connector::Payone::new()))) } enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))), enums::Connector::Placetopay => { Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new()))) } enums::Connector::Powertranz => { Ok(ConnectorEnum::Old(Box::new(&connector::Powertranz))) } enums::Connector::Prophetpay => { Ok(ConnectorEnum::Old(Box::new(&connector::Prophetpay))) } enums::Connector::Razorpay => { Ok(ConnectorEnum::Old(Box::new(connector::Razorpay::new()))) } enums::Connector::Rapyd => { Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new()))) } enums::Connector::Recurly => { Ok(ConnectorEnum::Old(Box::new(connector::Recurly::new()))) } enums::Connector::Redsys => { Ok(ConnectorEnum::Old(Box::new(connector::Redsys::new()))) } enums::Connector::Shift4 => { Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new()))) } enums::Connector::Square => Ok(ConnectorEnum::Old(Box::new(&connector::Square))), enums::Connector::Stax => Ok(ConnectorEnum::Old(Box::new(&connector::Stax))), enums::Connector::Stripe => { Ok(ConnectorEnum::Old(Box::new(connector::Stripe::new()))) } enums::Connector::Stripebilling => Ok(ConnectorEnum::Old(Box::new( connector::Stripebilling::new(), ))), enums::Connector::Wise => Ok(ConnectorEnum::Old(Box::new(connector::Wise::new()))), enums::Connector::Worldline => { Ok(ConnectorEnum::Old(Box::new(&connector::Worldline))) } enums::Connector::Worldpay => { Ok(ConnectorEnum::Old(Box::new(connector::Worldpay::new()))) } enums::Connector::Xendit => { Ok(ConnectorEnum::Old(Box::new(connector::Xendit::new()))) } enums::Connector::Mifinity => { Ok(ConnectorEnum::Old(Box::new(connector::Mifinity::new()))) } enums::Connector::Multisafepay => { Ok(ConnectorEnum::Old(Box::new(connector::Multisafepay::new()))) } enums::Connector::Netcetera => { Ok(ConnectorEnum::Old(Box::new(&connector::Netcetera))) } enums::Connector::Nexinets => { Ok(ConnectorEnum::Old(Box::new(&connector::Nexinets))) } // enums::Connector::Nexixpay => { // Ok(ConnectorEnum::Old(Box::new(&connector::Nexixpay))) // } enums::Connector::Paypal => { Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new()))) } enums::Connector::Paystack => { Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new()))) } // enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))), enums::Connector::Trustpay => { Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new()))) } enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(connector::Tsys::new()))), // enums::Connector::UnifiedAuthenticationService => Ok(ConnectorEnum::Old(Box::new( // connector::UnifiedAuthenticationService, // ))), enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))), enums::Connector::Wellsfargo => { Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new()))) } // enums::Connector::Wellsfargopayout => { // Ok(Box::new(connector::Wellsfargopayout::new())) // } enums::Connector::Zen => Ok(ConnectorEnum::Old(Box::new(&connector::Zen))), enums::Connector::Zsl => Ok(ConnectorEnum::Old(Box::new(&connector::Zsl))), enums::Connector::Plaid => { Ok(ConnectorEnum::Old(Box::new(connector::Plaid::new()))) } enums::Connector::Signifyd | enums::Connector::Riskified | enums::Connector::Gpayments | enums::Connector::Threedsecureio | enums::Connector::Taxjar => { Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ApiErrorResponse::InternalServerError) } }, Err(_) => Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ApiErrorResponse::InternalServerError), } } } #[cfg(test)] mod test { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_convert_connector_parsing_success() { let result = enums::Connector::from_str("aci"); assert!(result.is_ok()); assert_eq!(result.unwrap(), enums::Connector::Aci); let result = enums::Connector::from_str("shift4"); assert!(result.is_ok()); assert_eq!(result.unwrap(), enums::Connector::Shift4); let result = enums::Connector::from_str("authorizedotnet"); assert!(result.is_ok()); assert_eq!(result.unwrap(), enums::Connector::Authorizedotnet); } #[test] fn test_convert_connector_parsing_fail_for_unknown_type() { let result = enums::Connector::from_str("unknowntype"); assert!(result.is_err()); let result = enums::Connector::from_str("randomstring"); assert!(result.is_err()); } #[test] fn test_convert_connector_parsing_fail_for_camel_case() { let result = enums::Connector::from_str("Paypal"); assert!(result.is_err()); let result = enums::Connector::from_str("Authorizedotnet"); assert!(result.is_err()); let result = enums::Connector::from_str("Opennode"); assert!(result.is_err()); } } #[derive(Clone)] pub struct TaxCalculateConnectorData { pub connector: ConnectorEnum, pub connector_name: enums::TaxConnectors, } impl TaxCalculateConnectorData { pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> { let connector_name = enums::TaxConnectors::from_str(name) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) .attach_printable_lazy(|| format!("unable to parse connector: {name}"))?; let connector = Self::convert_connector(connector_name)?; Ok(Self { connector, connector_name, }) } fn convert_connector( connector_name: enums::TaxConnectors, ) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> { match connector_name { enums::TaxConnectors::Taxjar => { Ok(ConnectorEnum::Old(Box::new(connector::Taxjar::new()))) } } } }
5,905
1,334
hyperswitch
crates/router/src/types/authentication.rs
.rs
pub use hyperswitch_domain_models::{ router_request_types::authentication::{ AcquirerDetails, AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, PreAuthNRequestData, PreAuthenticationData, }, router_response_types::AuthenticationResponseData, }; use super::{api, RouterData}; use crate::services; pub type PreAuthNRouterData = RouterData<api::PreAuthentication, PreAuthNRequestData, AuthenticationResponseData>; pub type PreAuthNVersionCallRouterData = RouterData<api::PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData>; pub type ConnectorAuthenticationRouterData = RouterData<api::Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData>; pub type ConnectorPostAuthenticationRouterData = RouterData< api::PostAuthentication, ConnectorPostAuthenticationRequestData, AuthenticationResponseData, >; pub type ConnectorAuthenticationType = dyn services::ConnectorIntegration< api::Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData, >; pub type ConnectorPostAuthenticationType = dyn services::ConnectorIntegration< api::PostAuthentication, ConnectorPostAuthenticationRequestData, AuthenticationResponseData, >; pub type ConnectorPreAuthenticationType = dyn services::ConnectorIntegration< api::PreAuthentication, PreAuthNRequestData, AuthenticationResponseData, >; pub type ConnectorPreAuthenticationVersionCallType = dyn services::ConnectorIntegration< api::PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData, >;
315
1,335
hyperswitch
crates/router/src/types/pm_auth.rs
.rs
use std::str::FromStr; use error_stack::ResultExt; use pm_auth::{ connector::plaid, types::{ self as pm_auth_types, api::{BoxedPaymentAuthConnector, PaymentAuthConnectorData}, }, }; use crate::core::{ errors::{self, ApiErrorResponse}, pm_auth::helpers::PaymentAuthConnectorDataExt, }; impl PaymentAuthConnectorDataExt for PaymentAuthConnectorData { fn get_connector_by_name(name: &str) -> errors::CustomResult<Self, ApiErrorResponse> { let connector_name = pm_auth_types::PaymentMethodAuthConnectors::from_str(name) .change_context(ApiErrorResponse::IncorrectConnectorNameGiven) .attach_printable_lazy(|| { format!("unable to parse connector: {:?}", name.to_string()) })?; let connector = Self::convert_connector(connector_name.clone())?; Ok(Self { connector, connector_name, }) } fn convert_connector( connector_name: pm_auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<BoxedPaymentAuthConnector, ApiErrorResponse> { match connector_name { pm_auth_types::PaymentMethodAuthConnectors::Plaid => Ok(Box::new(&plaid::Plaid)), } } }
267
1,336
hyperswitch
crates/router/src/types/transformers.rs
.rs
// use actix_web::HttpMessage; use actix_web::http::header::HeaderMap; use api_models::{ cards_info as card_info_types, enums as api_enums, gsm as gsm_api_types, payment_methods, payments, routing::ConnectorSelection, }; use common_utils::{ consts::X_HS_LATENCY, crypto::Encryptable, ext_traits::{Encode, StringExt, ValueExt}, fp_utils::when, pii, types::ConnectorTransactionIdTrait, }; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::payments::payment_intent::CustomerData; use masking::{ExposeInterface, PeekInterface, Secret}; use super::domain; use crate::{ core::errors, headers::{ ACCEPT_LANGUAGE, BROWSER_NAME, X_APP_ID, X_CLIENT_PLATFORM, X_CLIENT_SOURCE, X_CLIENT_VERSION, X_MERCHANT_DOMAIN, X_PAYMENT_CONFIRM_SOURCE, X_REDIRECT_URI, }, services::authentication::get_header_value_by_key, types::{ self as router_types, api::{self as api_types, routing as routing_types}, storage, }, }; pub trait ForeignInto<T> { fn foreign_into(self) -> T; } pub trait ForeignTryInto<T> { type Error; fn foreign_try_into(self) -> Result<T, Self::Error>; } pub trait ForeignFrom<F> { fn foreign_from(from: F) -> Self; } pub trait ForeignTryFrom<F>: Sized { type Error; fn foreign_try_from(from: F) -> Result<Self, Self::Error>; } impl<F, T> ForeignInto<T> for F where T: ForeignFrom<F>, { fn foreign_into(self) -> T { T::foreign_from(self) } } impl<F, T> ForeignTryInto<T> for F where T: ForeignTryFrom<F>, { type Error = <T as ForeignTryFrom<F>>::Error; fn foreign_try_into(self) -> Result<T, Self::Error> { T::foreign_try_from(self) } } impl ForeignFrom<api_models::refunds::RefundType> for storage_enums::RefundType { fn foreign_from(item: api_models::refunds::RefundType) -> Self { match item { api_models::refunds::RefundType::Instant => Self::InstantRefund, api_models::refunds::RefundType::Scheduled => Self::RegularRefund, } } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl ForeignFrom<( Option<payment_methods::CardDetailFromLocker>, domain::PaymentMethod, )> for payment_methods::PaymentMethodResponse { fn foreign_from( (card_details, item): ( Option<payment_methods::CardDetailFromLocker>, domain::PaymentMethod, ), ) -> Self { Self { merchant_id: item.merchant_id.to_owned(), customer_id: Some(item.customer_id.to_owned()), payment_method_id: item.get_id().clone(), payment_method: item.get_payment_method_type(), payment_method_type: item.get_payment_method_subtype(), card: card_details, recurring_enabled: false, installment_payment_enabled: false, payment_experience: None, metadata: item.metadata, created: Some(item.created_at), #[cfg(feature = "payouts")] bank_transfer: None, last_used_at: None, client_secret: item.client_secret, } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl ForeignFrom<( Option<payment_methods::CardDetailFromLocker>, domain::PaymentMethod, )> for payment_methods::PaymentMethodResponse { fn foreign_from( (card_details, item): ( Option<payment_methods::CardDetailFromLocker>, domain::PaymentMethod, ), ) -> Self { todo!() } } // TODO: remove this usage in v1 code impl ForeignFrom<storage_enums::AttemptStatus> for storage_enums::IntentStatus { fn foreign_from(s: storage_enums::AttemptStatus) -> Self { Self::from(s) } } impl ForeignTryFrom<storage_enums::AttemptStatus> for storage_enums::CaptureStatus { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( attempt_status: storage_enums::AttemptStatus, ) -> errors::RouterResult<Self> { match attempt_status { storage_enums::AttemptStatus::Charged | storage_enums::AttemptStatus::PartialCharged => Ok(Self::Charged), storage_enums::AttemptStatus::Pending | storage_enums::AttemptStatus::CaptureInitiated => Ok(Self::Pending), storage_enums::AttemptStatus::Failure | storage_enums::AttemptStatus::CaptureFailed => Ok(Self::Failed), storage_enums::AttemptStatus::Started | storage_enums::AttemptStatus::AuthenticationFailed | storage_enums::AttemptStatus::RouterDeclined | storage_enums::AttemptStatus::AuthenticationPending | storage_enums::AttemptStatus::AuthenticationSuccessful | storage_enums::AttemptStatus::Authorized | storage_enums::AttemptStatus::AuthorizationFailed | storage_enums::AttemptStatus::Authorizing | storage_enums::AttemptStatus::CodInitiated | storage_enums::AttemptStatus::Voided | storage_enums::AttemptStatus::VoidInitiated | storage_enums::AttemptStatus::VoidFailed | storage_enums::AttemptStatus::AutoRefunded | storage_enums::AttemptStatus::Unresolved | storage_enums::AttemptStatus::PaymentMethodAwaited | storage_enums::AttemptStatus::ConfirmationAwaited | storage_enums::AttemptStatus::DeviceDataCollectionPending | storage_enums::AttemptStatus::PartialChargedAndChargeable=> { Err(errors::ApiErrorResponse::PreconditionFailed { message: "AttemptStatus must be one of these for multiple partial captures [Charged, PartialCharged, Pending, CaptureInitiated, Failure, CaptureFailed]".into(), }.into()) } } } } impl ForeignFrom<payments::MandateType> for storage_enums::MandateDataType { fn foreign_from(from: payments::MandateType) -> Self { match from { payments::MandateType::SingleUse(inner) => Self::SingleUse(inner.foreign_into()), payments::MandateType::MultiUse(inner) => { Self::MultiUse(inner.map(ForeignInto::foreign_into)) } } } } impl ForeignFrom<storage_enums::MandateDataType> for payments::MandateType { fn foreign_from(from: storage_enums::MandateDataType) -> Self { match from { storage_enums::MandateDataType::SingleUse(inner) => { Self::SingleUse(inner.foreign_into()) } storage_enums::MandateDataType::MultiUse(inner) => { Self::MultiUse(inner.map(ForeignInto::foreign_into)) } } } } impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { type Error = error_stack::Report<common_utils::errors::ValidationError>; fn foreign_try_from(from: api_enums::Connector) -> Result<Self, Self::Error> { Ok(match from { api_enums::Connector::Aci => Self::Aci, api_enums::Connector::Adyen => Self::Adyen, api_enums::Connector::Adyenplatform => Self::Adyenplatform, api_enums::Connector::Airwallex => Self::Airwallex, // api_enums::Connector::Amazonpay => Self::Amazonpay, api_enums::Connector::Authorizedotnet => Self::Authorizedotnet, api_enums::Connector::Bambora => Self::Bambora, api_enums::Connector::Bamboraapac => Self::Bamboraapac, api_enums::Connector::Bankofamerica => Self::Bankofamerica, api_enums::Connector::Billwerk => Self::Billwerk, api_enums::Connector::Bitpay => Self::Bitpay, api_enums::Connector::Bluesnap => Self::Bluesnap, api_enums::Connector::Boku => Self::Boku, api_enums::Connector::Braintree => Self::Braintree, api_enums::Connector::Cashtocode => Self::Cashtocode, api_enums::Connector::Chargebee => Self::Chargebee, api_enums::Connector::Checkout => Self::Checkout, api_enums::Connector::Coinbase => Self::Coinbase, api_enums::Connector::Coingate => Self::Coingate, api_enums::Connector::Cryptopay => Self::Cryptopay, api_enums::Connector::CtpVisa => { Err(common_utils::errors::ValidationError::InvalidValue { message: "ctp visa is not a routable connector".to_string(), })? } api_enums::Connector::CtpMastercard => { Err(common_utils::errors::ValidationError::InvalidValue { message: "ctp mastercard is not a routable connector".to_string(), })? } api_enums::Connector::Cybersource => Self::Cybersource, api_enums::Connector::Datatrans => Self::Datatrans, api_enums::Connector::Deutschebank => Self::Deutschebank, api_enums::Connector::Digitalvirgo => Self::Digitalvirgo, api_enums::Connector::Dlocal => Self::Dlocal, api_enums::Connector::Ebanx => Self::Ebanx, api_enums::Connector::Elavon => Self::Elavon, // api_enums::Connector::Facilitapay => Self::Facilitapay, api_enums::Connector::Fiserv => Self::Fiserv, api_enums::Connector::Fiservemea => Self::Fiservemea, api_enums::Connector::Fiuu => Self::Fiuu, api_enums::Connector::Forte => Self::Forte, api_enums::Connector::Getnet => Self::Getnet, api_enums::Connector::Globalpay => Self::Globalpay, api_enums::Connector::Globepay => Self::Globepay, api_enums::Connector::Gocardless => Self::Gocardless, api_enums::Connector::Gpayments => { Err(common_utils::errors::ValidationError::InvalidValue { message: "gpayments is not a routable connector".to_string(), })? } api_enums::Connector::Hipay => Self::Hipay, api_enums::Connector::Helcim => Self::Helcim, api_enums::Connector::Iatapay => Self::Iatapay, api_enums::Connector::Inespay => Self::Inespay, api_enums::Connector::Itaubank => Self::Itaubank, api_enums::Connector::Jpmorgan => Self::Jpmorgan, api_enums::Connector::Juspaythreedsserver => { Err(common_utils::errors::ValidationError::InvalidValue { message: "juspaythreedsserver is not a routable connector".to_string(), })? } api_enums::Connector::Klarna => Self::Klarna, api_enums::Connector::Mifinity => Self::Mifinity, api_enums::Connector::Mollie => Self::Mollie, api_enums::Connector::Moneris => Self::Moneris, api_enums::Connector::Multisafepay => Self::Multisafepay, api_enums::Connector::Netcetera => { Err(common_utils::errors::ValidationError::InvalidValue { message: "netcetera is not a routable connector".to_string(), })? } api_enums::Connector::Nexinets => Self::Nexinets, api_enums::Connector::Nexixpay => Self::Nexixpay, api_enums::Connector::Nmi => Self::Nmi, api_enums::Connector::Nomupay => Self::Nomupay, api_enums::Connector::Noon => Self::Noon, api_enums::Connector::Novalnet => Self::Novalnet, api_enums::Connector::Nuvei => Self::Nuvei, api_enums::Connector::Opennode => Self::Opennode, api_enums::Connector::Paybox => Self::Paybox, api_enums::Connector::Payme => Self::Payme, api_enums::Connector::Payone => Self::Payone, api_enums::Connector::Paypal => Self::Paypal, api_enums::Connector::Paystack => Self::Paystack, api_enums::Connector::Payu => Self::Payu, api_models::enums::Connector::Placetopay => Self::Placetopay, api_enums::Connector::Plaid => Self::Plaid, api_enums::Connector::Powertranz => Self::Powertranz, api_enums::Connector::Prophetpay => Self::Prophetpay, api_enums::Connector::Rapyd => Self::Rapyd, api_enums::Connector::Razorpay => Self::Razorpay, api_enums::Connector::Recurly => Self::Recurly, api_enums::Connector::Redsys => Self::Redsys, api_enums::Connector::Shift4 => Self::Shift4, api_enums::Connector::Signifyd => { Err(common_utils::errors::ValidationError::InvalidValue { message: "signifyd is not a routable connector".to_string(), })? } api_enums::Connector::Riskified => { Err(common_utils::errors::ValidationError::InvalidValue { message: "riskified is not a routable connector".to_string(), })? } api_enums::Connector::Square => Self::Square, api_enums::Connector::Stax => Self::Stax, api_enums::Connector::Stripe => Self::Stripe, api_enums::Connector::Stripebilling => Self::Stripebilling, // api_enums::Connector::Taxjar => Self::Taxjar, // api_enums::Connector::Thunes => Self::Thunes, api_enums::Connector::Trustpay => Self::Trustpay, api_enums::Connector::Tsys => Self::Tsys, // api_enums::Connector::UnifiedAuthenticationService => { // Self::UnifiedAuthenticationService // } api_enums::Connector::Volt => Self::Volt, api_enums::Connector::Wellsfargo => Self::Wellsfargo, // api_enums::Connector::Wellsfargopayout => Self::Wellsfargopayout, api_enums::Connector::Wise => Self::Wise, api_enums::Connector::Worldline => Self::Worldline, api_enums::Connector::Worldpay => Self::Worldpay, api_enums::Connector::Xendit => Self::Xendit, api_enums::Connector::Zen => Self::Zen, api_enums::Connector::Zsl => Self::Zsl, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector1 => Self::DummyConnector1, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector2 => Self::DummyConnector2, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector3 => Self::DummyConnector3, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector4 => Self::DummyConnector4, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector5 => Self::DummyConnector5, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector6 => Self::DummyConnector6, #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector7 => Self::DummyConnector7, api_enums::Connector::Threedsecureio => { Err(common_utils::errors::ValidationError::InvalidValue { message: "threedsecureio is not a routable connector".to_string(), })? } api_enums::Connector::Taxjar => { Err(common_utils::errors::ValidationError::InvalidValue { message: "Taxjar is not a routable connector".to_string(), })? } }) } } impl ForeignFrom<storage_enums::MandateAmountData> for payments::MandateAmountData { fn foreign_from(from: storage_enums::MandateAmountData) -> Self { Self { amount: from.amount, currency: from.currency, start_date: from.start_date, end_date: from.end_date, metadata: from.metadata, } } } // TODO: remove foreign from since this conversion won't be needed in the router crate once data models is treated as a single & primary source of truth for structure information impl ForeignFrom<payments::MandateData> for hyperswitch_domain_models::mandates::MandateData { fn foreign_from(d: payments::MandateData) -> Self { Self { customer_acceptance: d.customer_acceptance.map(|d| { hyperswitch_domain_models::mandates::CustomerAcceptance { acceptance_type: match d.acceptance_type { payments::AcceptanceType::Online => { hyperswitch_domain_models::mandates::AcceptanceType::Online } payments::AcceptanceType::Offline => { hyperswitch_domain_models::mandates::AcceptanceType::Offline } }, accepted_at: d.accepted_at, online: d .online .map(|d| hyperswitch_domain_models::mandates::OnlineMandate { ip_address: d.ip_address, user_agent: d.user_agent, }), } }), mandate_type: d.mandate_type.map(|d| match d { payments::MandateType::MultiUse(Some(i)) => { hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some( hyperswitch_domain_models::mandates::MandateAmountData { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, }, )) } payments::MandateType::SingleUse(i) => { hyperswitch_domain_models::mandates::MandateDataType::SingleUse( hyperswitch_domain_models::mandates::MandateAmountData { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, }, ) } payments::MandateType::MultiUse(None) => { hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) } }), update_mandate_id: d.update_mandate_id, } } } impl ForeignFrom<payments::MandateAmountData> for storage_enums::MandateAmountData { fn foreign_from(from: payments::MandateAmountData) -> Self { Self { amount: from.amount, currency: from.currency, start_date: from.start_date, end_date: from.end_date, metadata: from.metadata, } } } impl ForeignFrom<api_enums::IntentStatus> for Option<storage_enums::EventType> { fn foreign_from(value: api_enums::IntentStatus) -> Self { match value { api_enums::IntentStatus::Succeeded => Some(storage_enums::EventType::PaymentSucceeded), api_enums::IntentStatus::Failed => Some(storage_enums::EventType::PaymentFailed), api_enums::IntentStatus::Processing => { Some(storage_enums::EventType::PaymentProcessing) } api_enums::IntentStatus::RequiresMerchantAction | api_enums::IntentStatus::RequiresCustomerAction => { Some(storage_enums::EventType::ActionRequired) } api_enums::IntentStatus::Cancelled => Some(storage_enums::EventType::PaymentCancelled), api_enums::IntentStatus::PartiallyCaptured | api_enums::IntentStatus::PartiallyCapturedAndCapturable => { Some(storage_enums::EventType::PaymentCaptured) } api_enums::IntentStatus::RequiresCapture => { Some(storage_enums::EventType::PaymentAuthorized) } api_enums::IntentStatus::RequiresPaymentMethod | api_enums::IntentStatus::RequiresConfirmation => None, } } } impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { fn foreign_from(payment_method_type: api_enums::PaymentMethodType) -> Self { match payment_method_type { api_enums::PaymentMethodType::AmazonPay | api_enums::PaymentMethodType::ApplePay | api_enums::PaymentMethodType::GooglePay | api_enums::PaymentMethodType::Paypal | api_enums::PaymentMethodType::AliPay | api_enums::PaymentMethodType::AliPayHk | api_enums::PaymentMethodType::Dana | api_enums::PaymentMethodType::MbWay | api_enums::PaymentMethodType::MobilePay | api_enums::PaymentMethodType::Paze | api_enums::PaymentMethodType::SamsungPay | api_enums::PaymentMethodType::Twint | api_enums::PaymentMethodType::Vipps | api_enums::PaymentMethodType::TouchNGo | api_enums::PaymentMethodType::Swish | api_enums::PaymentMethodType::WeChatPay | api_enums::PaymentMethodType::GoPay | api_enums::PaymentMethodType::Gcash | api_enums::PaymentMethodType::Momo | api_enums::PaymentMethodType::Cashapp | api_enums::PaymentMethodType::KakaoPay | api_enums::PaymentMethodType::Venmo | api_enums::PaymentMethodType::Mifinity => Self::Wallet, api_enums::PaymentMethodType::Affirm | api_enums::PaymentMethodType::Alma | api_enums::PaymentMethodType::AfterpayClearpay | api_enums::PaymentMethodType::Klarna | api_enums::PaymentMethodType::PayBright | api_enums::PaymentMethodType::Atome | api_enums::PaymentMethodType::Walley => Self::PayLater, api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Ideal | api_enums::PaymentMethodType::Sofort | api_enums::PaymentMethodType::Eft | api_enums::PaymentMethodType::Eps | api_enums::PaymentMethodType::BancontactCard | api_enums::PaymentMethodType::Blik | api_enums::PaymentMethodType::LocalBankRedirect | api_enums::PaymentMethodType::OnlineBankingThailand | api_enums::PaymentMethodType::OnlineBankingCzechRepublic | api_enums::PaymentMethodType::OnlineBankingFinland | api_enums::PaymentMethodType::OnlineBankingFpx | api_enums::PaymentMethodType::OnlineBankingPoland | api_enums::PaymentMethodType::OnlineBankingSlovakia | api_enums::PaymentMethodType::OpenBankingUk | api_enums::PaymentMethodType::OpenBankingPIS | api_enums::PaymentMethodType::Przelewy24 | api_enums::PaymentMethodType::Trustly | api_enums::PaymentMethodType::Bizum | api_enums::PaymentMethodType::Interac => Self::BankRedirect, api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent => { Self::Upi } api_enums::PaymentMethodType::CryptoCurrency => Self::Crypto, api_enums::PaymentMethodType::Ach | api_enums::PaymentMethodType::Sepa | api_enums::PaymentMethodType::Bacs | api_enums::PaymentMethodType::Becs => Self::BankDebit, api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { Self::Card } #[cfg(feature = "v2")] api_enums::PaymentMethodType::Card => Self::Card, api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward => Self::Reward, api_enums::PaymentMethodType::Boleto | api_enums::PaymentMethodType::Efecty | api_enums::PaymentMethodType::PagoEfectivo | api_enums::PaymentMethodType::RedCompra | api_enums::PaymentMethodType::Alfamart | api_enums::PaymentMethodType::Indomaret | api_enums::PaymentMethodType::Oxxo | api_enums::PaymentMethodType::SevenEleven | api_enums::PaymentMethodType::Lawson | api_enums::PaymentMethodType::MiniStop | api_enums::PaymentMethodType::FamilyMart | api_enums::PaymentMethodType::Seicomart | api_enums::PaymentMethodType::PayEasy | api_enums::PaymentMethodType::RedPagos => Self::Voucher, api_enums::PaymentMethodType::Pse | api_enums::PaymentMethodType::Multibanco | api_enums::PaymentMethodType::PermataBankTransfer | api_enums::PaymentMethodType::BcaBankTransfer | api_enums::PaymentMethodType::BniVa | api_enums::PaymentMethodType::BriVa | api_enums::PaymentMethodType::CimbVa | api_enums::PaymentMethodType::DanamonVa | api_enums::PaymentMethodType::MandiriVa | api_enums::PaymentMethodType::LocalBankTransfer | api_enums::PaymentMethodType::InstantBankTransfer | api_enums::PaymentMethodType::SepaBankTransfer | api_enums::PaymentMethodType::Pix => Self::BankTransfer, api_enums::PaymentMethodType::Givex | api_enums::PaymentMethodType::PaySafeCard => { Self::GiftCard } api_enums::PaymentMethodType::Benefit | api_enums::PaymentMethodType::Knet | api_enums::PaymentMethodType::MomoAtm | api_enums::PaymentMethodType::CardRedirect => Self::CardRedirect, api_enums::PaymentMethodType::Fps | api_enums::PaymentMethodType::DuitNow | api_enums::PaymentMethodType::PromptPay | api_enums::PaymentMethodType::VietQr => Self::RealTimePayment, api_enums::PaymentMethodType::DirectCarrierBilling => Self::MobilePayment, } } } impl ForeignTryFrom<payments::PaymentMethodData> for api_enums::PaymentMethod { type Error = errors::ApiErrorResponse; fn foreign_try_from( payment_method_data: payments::PaymentMethodData, ) -> Result<Self, Self::Error> { match payment_method_data { payments::PaymentMethodData::Card(..) | payments::PaymentMethodData::CardToken(..) => { Ok(Self::Card) } payments::PaymentMethodData::Wallet(..) => Ok(Self::Wallet), payments::PaymentMethodData::PayLater(..) => Ok(Self::PayLater), payments::PaymentMethodData::BankRedirect(..) => Ok(Self::BankRedirect), payments::PaymentMethodData::BankDebit(..) => Ok(Self::BankDebit), payments::PaymentMethodData::BankTransfer(..) => Ok(Self::BankTransfer), payments::PaymentMethodData::Crypto(..) => Ok(Self::Crypto), payments::PaymentMethodData::Reward => Ok(Self::Reward), payments::PaymentMethodData::RealTimePayment(..) => Ok(Self::RealTimePayment), payments::PaymentMethodData::Upi(..) => Ok(Self::Upi), payments::PaymentMethodData::Voucher(..) => Ok(Self::Voucher), payments::PaymentMethodData::GiftCard(..) => Ok(Self::GiftCard), payments::PaymentMethodData::CardRedirect(..) => Ok(Self::CardRedirect), payments::PaymentMethodData::OpenBanking(..) => Ok(Self::OpenBanking), payments::PaymentMethodData::MobilePayment(..) => Ok(Self::MobilePayment), payments::PaymentMethodData::MandatePayment => { Err(errors::ApiErrorResponse::InvalidRequestData { message: ("Mandate payments cannot have payment_method_data field".to_string()), }) } } } } impl ForeignFrom<storage_enums::RefundStatus> for Option<storage_enums::EventType> { fn foreign_from(value: storage_enums::RefundStatus) -> Self { match value { storage_enums::RefundStatus::Success => Some(storage_enums::EventType::RefundSucceeded), storage_enums::RefundStatus::Failure => Some(storage_enums::EventType::RefundFailed), api_enums::RefundStatus::ManualReview | api_enums::RefundStatus::Pending | api_enums::RefundStatus::TransactionFailure => None, } } } impl ForeignFrom<storage_enums::PayoutStatus> for Option<storage_enums::EventType> { fn foreign_from(value: storage_enums::PayoutStatus) -> Self { match value { storage_enums::PayoutStatus::Success => Some(storage_enums::EventType::PayoutSuccess), storage_enums::PayoutStatus::Failed => Some(storage_enums::EventType::PayoutFailed), storage_enums::PayoutStatus::Cancelled => { Some(storage_enums::EventType::PayoutCancelled) } storage_enums::PayoutStatus::Initiated => { Some(storage_enums::EventType::PayoutInitiated) } storage_enums::PayoutStatus::Expired => Some(storage_enums::EventType::PayoutExpired), storage_enums::PayoutStatus::Reversed => Some(storage_enums::EventType::PayoutReversed), storage_enums::PayoutStatus::Ineligible | storage_enums::PayoutStatus::Pending | storage_enums::PayoutStatus::RequiresCreation | storage_enums::PayoutStatus::RequiresFulfillment | storage_enums::PayoutStatus::RequiresPayoutMethodData | storage_enums::PayoutStatus::RequiresVendorAccountCreation | storage_enums::PayoutStatus::RequiresConfirmation => None, } } } impl ForeignFrom<storage_enums::DisputeStatus> for storage_enums::EventType { fn foreign_from(value: storage_enums::DisputeStatus) -> Self { match value { storage_enums::DisputeStatus::DisputeOpened => Self::DisputeOpened, storage_enums::DisputeStatus::DisputeExpired => Self::DisputeExpired, storage_enums::DisputeStatus::DisputeAccepted => Self::DisputeAccepted, storage_enums::DisputeStatus::DisputeCancelled => Self::DisputeCancelled, storage_enums::DisputeStatus::DisputeChallenged => Self::DisputeChallenged, storage_enums::DisputeStatus::DisputeWon => Self::DisputeWon, storage_enums::DisputeStatus::DisputeLost => Self::DisputeLost, } } } impl ForeignFrom<storage_enums::MandateStatus> for Option<storage_enums::EventType> { fn foreign_from(value: storage_enums::MandateStatus) -> Self { match value { storage_enums::MandateStatus::Active => Some(storage_enums::EventType::MandateActive), storage_enums::MandateStatus::Revoked => Some(storage_enums::EventType::MandateRevoked), storage_enums::MandateStatus::Inactive | storage_enums::MandateStatus::Pending => None, } } } impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::RefundStatus { type Error = errors::ValidationError; fn foreign_try_from( value: api_models::webhooks::IncomingWebhookEvent, ) -> Result<Self, Self::Error> { match value { api_models::webhooks::IncomingWebhookEvent::RefundSuccess => Ok(Self::Success), api_models::webhooks::IncomingWebhookEvent::RefundFailure => Ok(Self::Failure), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "incoming_webhook_event_type", }), } } } impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for api_enums::RelayStatus { type Error = errors::ValidationError; fn foreign_try_from( value: api_models::webhooks::IncomingWebhookEvent, ) -> Result<Self, Self::Error> { match value { api_models::webhooks::IncomingWebhookEvent::RefundSuccess => Ok(Self::Success), api_models::webhooks::IncomingWebhookEvent::RefundFailure => Ok(Self::Failure), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "incoming_webhook_event_type", }), } } } #[cfg(feature = "payouts")] impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::PayoutStatus { type Error = errors::ValidationError; fn foreign_try_from( value: api_models::webhooks::IncomingWebhookEvent, ) -> Result<Self, Self::Error> { match value { api_models::webhooks::IncomingWebhookEvent::PayoutSuccess => Ok(Self::Success), api_models::webhooks::IncomingWebhookEvent::PayoutFailure => Ok(Self::Failed), api_models::webhooks::IncomingWebhookEvent::PayoutCancelled => Ok(Self::Cancelled), api_models::webhooks::IncomingWebhookEvent::PayoutProcessing => Ok(Self::Pending), api_models::webhooks::IncomingWebhookEvent::PayoutCreated => Ok(Self::Initiated), api_models::webhooks::IncomingWebhookEvent::PayoutExpired => Ok(Self::Expired), api_models::webhooks::IncomingWebhookEvent::PayoutReversed => Ok(Self::Reversed), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "incoming_webhook_event_type", }), } } } impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::MandateStatus { type Error = errors::ValidationError; fn foreign_try_from( value: api_models::webhooks::IncomingWebhookEvent, ) -> Result<Self, Self::Error> { match value { api_models::webhooks::IncomingWebhookEvent::MandateActive => Ok(Self::Active), api_models::webhooks::IncomingWebhookEvent::MandateRevoked => Ok(Self::Revoked), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "incoming_webhook_event_type", }), } } } impl ForeignFrom<storage::Config> for api_types::Config { fn foreign_from(config: storage::Config) -> Self { Self { key: config.key, value: config.config, } } } impl ForeignFrom<&api_types::ConfigUpdate> for storage::ConfigUpdate { fn foreign_from(config: &api_types::ConfigUpdate) -> Self { Self::Update { config: Some(config.value.clone()), } } } impl From<&domain::Address> for hyperswitch_domain_models::address::Address { fn from(address: &domain::Address) -> Self { // If all the fields of address are none, then pass the address as None let address_details = if address.city.is_none() && address.line1.is_none() && address.line2.is_none() && address.line3.is_none() && address.state.is_none() && address.country.is_none() && address.zip.is_none() && address.first_name.is_none() && address.last_name.is_none() { None } else { Some(hyperswitch_domain_models::address::AddressDetails { city: address.city.clone(), country: address.country, line1: address.line1.clone().map(Encryptable::into_inner), line2: address.line2.clone().map(Encryptable::into_inner), line3: address.line3.clone().map(Encryptable::into_inner), state: address.state.clone().map(Encryptable::into_inner), zip: address.zip.clone().map(Encryptable::into_inner), first_name: address.first_name.clone().map(Encryptable::into_inner), last_name: address.last_name.clone().map(Encryptable::into_inner), }) }; // If all the fields of phone are none, then pass the phone as None let phone_details = if address.phone_number.is_none() && address.country_code.is_none() { None } else { Some(hyperswitch_domain_models::address::PhoneDetails { number: address.phone_number.clone().map(Encryptable::into_inner), country_code: address.country_code.clone(), }) }; Self { address: address_details, phone: phone_details, email: address.email.clone().map(pii::Email::from), } } } impl ForeignFrom<domain::Address> for api_types::Address { fn foreign_from(address: domain::Address) -> Self { // If all the fields of address are none, then pass the address as None let address_details = if address.city.is_none() && address.line1.is_none() && address.line2.is_none() && address.line3.is_none() && address.state.is_none() && address.country.is_none() && address.zip.is_none() && address.first_name.is_none() && address.last_name.is_none() { None } else { Some(api_types::AddressDetails { city: address.city.clone(), country: address.country, line1: address.line1.clone().map(Encryptable::into_inner), line2: address.line2.clone().map(Encryptable::into_inner), line3: address.line3.clone().map(Encryptable::into_inner), state: address.state.clone().map(Encryptable::into_inner), zip: address.zip.clone().map(Encryptable::into_inner), first_name: address.first_name.clone().map(Encryptable::into_inner), last_name: address.last_name.clone().map(Encryptable::into_inner), }) }; // If all the fields of phone are none, then pass the phone as None let phone_details = if address.phone_number.is_none() && address.country_code.is_none() { None } else { Some(api_types::PhoneDetails { number: address.phone_number.clone().map(Encryptable::into_inner), country_code: address.country_code.clone(), }) }; Self { address: address_details, phone: phone_details, email: address.email.clone().map(pii::Email::from), } } } impl ForeignFrom<( diesel_models::api_keys::ApiKey, crate::core::api_keys::PlaintextApiKey, )> for api_models::api_keys::CreateApiKeyResponse { fn foreign_from( item: ( diesel_models::api_keys::ApiKey, crate::core::api_keys::PlaintextApiKey, ), ) -> Self { use masking::StrongSecret; let (api_key, plaintext_api_key) = item; Self { key_id: api_key.key_id, merchant_id: api_key.merchant_id, name: api_key.name, description: api_key.description, api_key: StrongSecret::from(plaintext_api_key.peek().to_owned()), created: api_key.created_at, expiration: api_key.expires_at.into(), } } } impl ForeignFrom<diesel_models::api_keys::ApiKey> for api_models::api_keys::RetrieveApiKeyResponse { fn foreign_from(api_key: diesel_models::api_keys::ApiKey) -> Self { Self { key_id: api_key.key_id, merchant_id: api_key.merchant_id, name: api_key.name, description: api_key.description, prefix: api_key.prefix.into(), created: api_key.created_at, expiration: api_key.expires_at.into(), } } } impl ForeignFrom<api_models::api_keys::UpdateApiKeyRequest> for diesel_models::api_keys::ApiKeyUpdate { fn foreign_from(api_key: api_models::api_keys::UpdateApiKeyRequest) -> Self { Self::Update { name: api_key.name, description: api_key.description, expires_at: api_key.expiration.map(Into::into), last_used: None, } } } impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::DisputeStatus { type Error = errors::ValidationError; fn foreign_try_from( value: api_models::webhooks::IncomingWebhookEvent, ) -> Result<Self, Self::Error> { match value { api_models::webhooks::IncomingWebhookEvent::DisputeOpened => Ok(Self::DisputeOpened), api_models::webhooks::IncomingWebhookEvent::DisputeExpired => Ok(Self::DisputeExpired), api_models::webhooks::IncomingWebhookEvent::DisputeAccepted => { Ok(Self::DisputeAccepted) } api_models::webhooks::IncomingWebhookEvent::DisputeCancelled => { Ok(Self::DisputeCancelled) } api_models::webhooks::IncomingWebhookEvent::DisputeChallenged => { Ok(Self::DisputeChallenged) } api_models::webhooks::IncomingWebhookEvent::DisputeWon => Ok(Self::DisputeWon), api_models::webhooks::IncomingWebhookEvent::DisputeLost => Ok(Self::DisputeLost), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "incoming_webhook_event", }), } } } impl ForeignFrom<storage::Dispute> for api_models::disputes::DisputeResponse { fn foreign_from(dispute: storage::Dispute) -> Self { Self { dispute_id: dispute.dispute_id, payment_id: dispute.payment_id, attempt_id: dispute.attempt_id, amount: dispute.amount, currency: dispute.dispute_currency.unwrap_or( dispute .currency .to_uppercase() .parse_enum("Currency") .unwrap_or_default(), ), dispute_stage: dispute.dispute_stage, dispute_status: dispute.dispute_status, connector: dispute.connector, 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: dispute.created_at, profile_id: dispute.profile_id, merchant_connector_id: dispute.merchant_connector_id, } } } impl ForeignFrom<storage::Authorization> for payments::IncrementalAuthorizationResponse { fn foreign_from(authorization: storage::Authorization) -> Self { Self { authorization_id: authorization.authorization_id, amount: authorization.amount, status: authorization.status, error_code: authorization.error_code, error_message: authorization.error_message, previously_authorized_amount: authorization.previously_authorized_amount, } } } impl ForeignFrom<&storage::Authentication> for payments::ExternalAuthenticationDetailsResponse { fn foreign_from(authn_data: &storage::Authentication) -> Self { let version = authn_data .maximum_supported_version .as_ref() .map(|version| version.to_string()); Self { authentication_flow: authn_data.authentication_type, electronic_commerce_indicator: authn_data.eci.clone(), status: authn_data.authentication_status, ds_transaction_id: authn_data.threeds_server_transaction_id.clone(), version, error_code: authn_data.error_code.clone(), error_message: authn_data.error_message.clone(), } } } impl ForeignFrom<storage::Dispute> for api_models::disputes::DisputeResponsePaymentsRetrieve { fn foreign_from(dispute: storage::Dispute) -> Self { Self { dispute_id: dispute.dispute_id, dispute_stage: dispute.dispute_stage, dispute_status: dispute.dispute_status, 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: dispute.created_at, } } } impl ForeignFrom<storage::FileMetadata> for api_models::files::FileMetadataResponse { fn foreign_from(file_metadata: storage::FileMetadata) -> Self { Self { file_id: file_metadata.file_id, file_name: file_metadata.file_name, file_size: file_metadata.file_size, file_type: file_metadata.file_type, available: file_metadata.available, } } } impl ForeignFrom<diesel_models::cards_info::CardInfo> for api_models::cards_info::CardInfoResponse { fn foreign_from(item: diesel_models::cards_info::CardInfo) -> Self { Self { card_iin: item.card_iin, card_type: item.card_type, card_sub_type: item.card_subtype, card_network: item.card_network.map(|x| x.to_string()), card_issuer: item.card_issuer, card_issuing_country: item.card_issuing_country, } } } impl ForeignTryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantConnectorListResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(item: domain::MerchantConnectorAccount) -> Result<Self, Self::Error> { #[cfg(feature = "v1")] let payment_methods_enabled = match item.payment_methods_enabled { Some(secret_val) => { let val = secret_val .into_iter() .map(|secret| secret.expose()) .collect(); serde_json::Value::Array(val) .parse_value("PaymentMethods") .change_context(errors::ApiErrorResponse::InternalServerError)? } None => None, }; let frm_configs = match item.frm_configs { Some(frm_value) => { let configs_for_frm : Vec<api_models::admin::FrmConfigs> = frm_value .iter() .map(|config| { config .peek() .clone() .parse_value("FrmConfigs") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "frm_configs".to_string(), expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","payment_method_types": [{"payment_method_type": "credit","card_networks": ["Visa"],"flow": "pre","action": "cancel_txn"}]}]}]"#.to_string(), }) }) .collect::<Result<Vec<_>, _>>()?; Some(configs_for_frm) } None => None, }; #[cfg(feature = "v1")] let response = Self { connector_type: item.connector_type, connector_name: item.connector_name, connector_label: item.connector_label, merchant_connector_id: item.merchant_connector_id, test_mode: item.test_mode, disabled: item.disabled, payment_methods_enabled, business_country: item.business_country, business_label: item.business_label, business_sub_label: item.business_sub_label, frm_configs, profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, status: item.status, }; #[cfg(feature = "v2")] let response = Self { id: item.id, connector_type: item.connector_type, connector_name: item.connector_name, connector_label: item.connector_label, disabled: item.disabled, payment_methods_enabled: item.payment_methods_enabled, frm_configs, profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, status: item.status, }; Ok(response) } } #[cfg(feature = "v1")] impl ForeignTryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantConnectorResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(item: domain::MerchantConnectorAccount) -> Result<Self, Self::Error> { let payment_methods_enabled = match item.payment_methods_enabled.clone() { Some(secret_val) => { let val = secret_val .into_iter() .map(|secret| secret.expose()) .collect(); serde_json::Value::Array(val) .parse_value("PaymentMethods") .change_context(errors::ApiErrorResponse::InternalServerError)? } None => None, }; let frm_configs = match item.frm_configs { Some(ref frm_value) => { let configs_for_frm : Vec<api_models::admin::FrmConfigs> = frm_value .iter() .map(|config| { config .peek() .clone() .parse_value("FrmConfigs") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "frm_configs".to_string(), expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","payment_method_types": [{"payment_method_type": "credit","card_networks": ["Visa"],"flow": "pre","action": "cancel_txn"}]}]}]"#.to_string(), }) }) .collect::<Result<Vec<_>, _>>()?; Some(configs_for_frm) } None => None, }; // parse the connector_account_details into ConnectorAuthType let connector_account_details: hyperswitch_domain_models::router_data::ConnectorAuthType = item.connector_account_details .clone() .into_inner() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; // get the masked keys from the ConnectorAuthType and encode it to secret value let masked_connector_account_details = Secret::new( connector_account_details .get_masked_keys() .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode ConnectorAuthType")?, ); #[cfg(feature = "v2")] let response = Self { id: item.get_id(), connector_type: item.connector_type, connector_name: item.connector_name, connector_label: item.connector_label, connector_account_details: masked_connector_account_details, disabled: item.disabled, payment_methods_enabled, metadata: item.metadata, frm_configs, connector_webhook_details: item .connector_webhook_details .map(|webhook_details| { serde_json::Value::parse_value( webhook_details.expose(), "MerchantConnectorWebhookDetails", ) .attach_printable("Unable to deserialize connector_webhook_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, status: item.status, additional_merchant_data: item .additional_merchant_data .map(|data| { let data = data.into_inner(); serde_json::Value::parse_value::<router_types::AdditionalMerchantData>( data.expose(), "AdditionalMerchantData", ) .attach_printable("Unable to deserialize additional_merchant_data") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()? .map(api_models::admin::AdditionalMerchantData::foreign_from), connector_wallets_details: item .connector_wallets_details .map(|data| { data.into_inner() .expose() .parse_value::<api_models::admin::ConnectorWalletDetails>( "ConnectorWalletDetails", ) .attach_printable("Unable to deserialize connector_wallets_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, }; #[cfg(feature = "v1")] let response = Self { connector_type: item.connector_type, connector_name: item.connector_name, connector_label: item.connector_label, merchant_connector_id: item.merchant_connector_id, connector_account_details: masked_connector_account_details, test_mode: item.test_mode, disabled: item.disabled, payment_methods_enabled, metadata: item.metadata, business_country: item.business_country, business_label: item.business_label, business_sub_label: item.business_sub_label, frm_configs, connector_webhook_details: item .connector_webhook_details .map(|webhook_details| { serde_json::Value::parse_value( webhook_details.expose(), "MerchantConnectorWebhookDetails", ) .attach_printable("Unable to deserialize connector_webhook_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, status: item.status, additional_merchant_data: item .additional_merchant_data .map(|data| { let data = data.into_inner(); serde_json::Value::parse_value::<router_types::AdditionalMerchantData>( data.expose(), "AdditionalMerchantData", ) .attach_printable("Unable to deserialize additional_merchant_data") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()? .map(api_models::admin::AdditionalMerchantData::foreign_from), connector_wallets_details: item .connector_wallets_details .map(|data| { data.into_inner() .expose() .parse_value::<api_models::admin::ConnectorWalletDetails>( "ConnectorWalletDetails", ) .attach_printable("Unable to deserialize connector_wallets_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, }; Ok(response) } } #[cfg(feature = "v2")] impl ForeignTryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantConnectorResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(item: domain::MerchantConnectorAccount) -> Result<Self, Self::Error> { let frm_configs = match item.frm_configs { Some(ref frm_value) => { let configs_for_frm : Vec<api_models::admin::FrmConfigs> = frm_value .iter() .map(|config| { config .peek() .clone() .parse_value("FrmConfigs") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "frm_configs".to_string(), expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","payment_method_types": [{"payment_method_type": "credit","card_networks": ["Visa"],"flow": "pre","action": "cancel_txn"}]}]}]"#.to_string(), }) }) .collect::<Result<Vec<_>, _>>()?; Some(configs_for_frm) } None => None, }; // parse the connector_account_details into ConnectorAuthType let connector_account_details: hyperswitch_domain_models::router_data::ConnectorAuthType = item.connector_account_details .clone() .into_inner() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; // get the masked keys from the ConnectorAuthType and encode it to secret value let masked_connector_account_details = Secret::new( connector_account_details .get_masked_keys() .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode ConnectorAuthType")?, ); let feature_metadata = item.feature_metadata.as_ref().map(|metadata| { api_models::admin::MerchantConnectorAccountFeatureMetadata::foreign_from(metadata) }); let response = Self { id: item.get_id(), connector_type: item.connector_type, connector_name: item.connector_name, connector_label: item.connector_label, connector_account_details: masked_connector_account_details, disabled: item.disabled, payment_methods_enabled: item.payment_methods_enabled, metadata: item.metadata, frm_configs, connector_webhook_details: item .connector_webhook_details .map(|webhook_details| { serde_json::Value::parse_value( webhook_details.expose(), "MerchantConnectorWebhookDetails", ) .attach_printable("Unable to deserialize connector_webhook_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, status: item.status, additional_merchant_data: item .additional_merchant_data .map(|data| { let data = data.into_inner(); serde_json::Value::parse_value::<router_types::AdditionalMerchantData>( data.expose(), "AdditionalMerchantData", ) .attach_printable("Unable to deserialize additional_merchant_data") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()? .map(api_models::admin::AdditionalMerchantData::foreign_from), connector_wallets_details: item .connector_wallets_details .map(|data| { data.into_inner() .expose() .parse_value::<api_models::admin::ConnectorWalletDetails>( "ConnectorWalletDetails", ) .attach_printable("Unable to deserialize connector_wallets_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, feature_metadata, }; Ok(response) } } #[cfg(feature = "v1")] impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse { fn foreign_from(payment_attempt: storage::PaymentAttempt) -> Self { let connector_transaction_id = payment_attempt .get_connector_payment_id() .map(ToString::to_string); Self { attempt_id: payment_attempt.attempt_id, status: payment_attempt.status, amount: payment_attempt.net_amount.get_order_amount(), order_tax_amount: payment_attempt.net_amount.get_order_tax_amount(), currency: payment_attempt.currency, connector: payment_attempt.connector, error_message: payment_attempt.error_reason, payment_method: payment_attempt.payment_method, connector_transaction_id, capture_method: payment_attempt.capture_method, authentication_type: payment_attempt.authentication_type, created_at: payment_attempt.created_at, modified_at: payment_attempt.modified_at, cancellation_reason: payment_attempt.cancellation_reason, mandate_id: payment_attempt.mandate_id, error_code: payment_attempt.error_code, payment_token: payment_attempt.payment_token, connector_metadata: payment_attempt.connector_metadata, payment_experience: payment_attempt.payment_experience, payment_method_type: payment_attempt.payment_method_type, reference_id: payment_attempt.connector_response_reference_id, unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, client_source: payment_attempt.client_source, client_version: payment_attempt.client_version, } } } impl ForeignFrom<storage::Capture> for payments::CaptureResponse { fn foreign_from(capture: storage::Capture) -> Self { let connector_capture_id = capture.get_optional_connector_transaction_id().cloned(); Self { capture_id: capture.capture_id, status: capture.status, amount: capture.amount, currency: capture.currency, connector: capture.connector, authorized_attempt_id: capture.authorized_attempt_id, connector_capture_id, capture_sequence: capture.capture_sequence, error_message: capture.error_message, error_code: capture.error_code, error_reason: capture.error_reason, reference_id: capture.connector_response_reference_id, } } } #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_enums::PaymentMethodType { fn foreign_from(value: &api_models::payouts::PayoutMethodData) -> Self { match value { api_models::payouts::PayoutMethodData::Bank(bank) => Self::foreign_from(bank), api_models::payouts::PayoutMethodData::Card(_) => Self::Debit, api_models::payouts::PayoutMethodData::Wallet(wallet) => Self::foreign_from(wallet), } } } #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::Bank> for api_enums::PaymentMethodType { fn foreign_from(value: &api_models::payouts::Bank) -> Self { match value { api_models::payouts::Bank::Ach(_) => Self::Ach, api_models::payouts::Bank::Bacs(_) => Self::Bacs, api_models::payouts::Bank::Sepa(_) => Self::SepaBankTransfer, api_models::payouts::Bank::Pix(_) => Self::Pix, } } } #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::Wallet> for api_enums::PaymentMethodType { fn foreign_from(value: &api_models::payouts::Wallet) -> Self { match value { api_models::payouts::Wallet::Paypal(_) => Self::Paypal, api_models::payouts::Wallet::Venmo(_) => Self::Venmo, } } } #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_enums::PaymentMethod { fn foreign_from(value: &api_models::payouts::PayoutMethodData) -> Self { match value { api_models::payouts::PayoutMethodData::Bank(_) => Self::BankTransfer, api_models::payouts::PayoutMethodData::Card(_) => Self::Card, api_models::payouts::PayoutMethodData::Wallet(_) => Self::Wallet, } } } #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_models::enums::PayoutType { fn foreign_from(value: &api_models::payouts::PayoutMethodData) -> Self { match value { api_models::payouts::PayoutMethodData::Bank(_) => Self::Bank, api_models::payouts::PayoutMethodData::Card(_) => Self::Card, api_models::payouts::PayoutMethodData::Wallet(_) => Self::Wallet, } } } #[cfg(feature = "payouts")] impl ForeignFrom<api_models::enums::PayoutType> for api_enums::PaymentMethod { fn foreign_from(value: api_models::enums::PayoutType) -> Self { match value { api_models::enums::PayoutType::Bank => Self::BankTransfer, api_models::enums::PayoutType::Card => Self::Card, api_models::enums::PayoutType::Wallet => Self::Wallet, } } } #[cfg(feature = "v1")] impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderPayload { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(headers: &HeaderMap) -> Result<Self, Self::Error> { let payment_confirm_source: Option<api_enums::PaymentSource> = get_header_value_by_key(X_PAYMENT_CONFIRM_SOURCE.into(), headers)? .map(|source| { source .to_owned() .parse_enum("PaymentSource") .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid data received in payment_confirm_source header" .into(), }) .attach_printable( "Failed while paring PaymentConfirmSource header value to enum", ) }) .transpose()?; when( payment_confirm_source.is_some_and(|payment_confirm_source| { payment_confirm_source.is_for_internal_use_only() }), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid data received in payment_confirm_source header".into(), })) }, )?; let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers)?.map(|val| val.to_string()); let x_hs_latency = get_header_value_by_key(X_HS_LATENCY.into(), headers) .map(|value| value == Some("true")) .unwrap_or(false); let client_source = get_header_value_by_key(X_CLIENT_SOURCE.into(), headers)?.map(|val| val.to_string()); let client_version = get_header_value_by_key(X_CLIENT_VERSION.into(), headers)?.map(|val| val.to_string()); let browser_name_str = get_header_value_by_key(BROWSER_NAME.into(), headers)?.map(|val| val.to_string()); let browser_name: Option<api_enums::BrowserName> = browser_name_str.map(|browser_name| { browser_name .parse_enum("BrowserName") .unwrap_or(api_enums::BrowserName::Unknown) }); let x_client_platform_str = get_header_value_by_key(X_CLIENT_PLATFORM.into(), headers)?.map(|val| val.to_string()); let x_client_platform: Option<api_enums::ClientPlatform> = x_client_platform_str.map(|x_client_platform| { x_client_platform .parse_enum("ClientPlatform") .unwrap_or(api_enums::ClientPlatform::Unknown) }); let x_merchant_domain = get_header_value_by_key(X_MERCHANT_DOMAIN.into(), headers)?.map(|val| val.to_string()); let x_app_id = get_header_value_by_key(X_APP_ID.into(), headers)?.map(|val| val.to_string()); let x_redirect_uri = get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string()); Ok(Self { payment_confirm_source, client_source, client_version, x_hs_latency: Some(x_hs_latency), browser_name, x_client_platform, x_merchant_domain, locale, x_app_id, x_redirect_uri, }) } } #[cfg(feature = "v2")] impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderPayload { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(headers: &HeaderMap) -> Result<Self, Self::Error> { use std::str::FromStr; use crate::headers::X_CLIENT_SECRET; let payment_confirm_source: Option<api_enums::PaymentSource> = get_header_value_by_key(X_PAYMENT_CONFIRM_SOURCE.into(), headers)? .map(|source| { source .to_owned() .parse_enum("PaymentSource") .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid data received in payment_confirm_source header" .into(), }) .attach_printable( "Failed while paring PaymentConfirmSource header value to enum", ) }) .transpose()?; when( payment_confirm_source.is_some_and(|payment_confirm_source| { payment_confirm_source.is_for_internal_use_only() }), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid data received in payment_confirm_source header".into(), })) }, )?; let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers)?.map(|val| val.to_string()); let x_hs_latency = get_header_value_by_key(X_HS_LATENCY.into(), headers) .map(|value| value == Some("true")) .unwrap_or(false); let client_source = get_header_value_by_key(X_CLIENT_SOURCE.into(), headers)?.map(|val| val.to_string()); let client_version = get_header_value_by_key(X_CLIENT_VERSION.into(), headers)?.map(|val| val.to_string()); let browser_name_str = get_header_value_by_key(BROWSER_NAME.into(), headers)?.map(|val| val.to_string()); let browser_name: Option<api_enums::BrowserName> = browser_name_str.map(|browser_name| { browser_name .parse_enum("BrowserName") .unwrap_or(api_enums::BrowserName::Unknown) }); let x_client_platform_str = get_header_value_by_key(X_CLIENT_PLATFORM.into(), headers)?.map(|val| val.to_string()); let x_client_platform: Option<api_enums::ClientPlatform> = x_client_platform_str.map(|x_client_platform| { x_client_platform .parse_enum("ClientPlatform") .unwrap_or(api_enums::ClientPlatform::Unknown) }); let x_merchant_domain = get_header_value_by_key(X_MERCHANT_DOMAIN.into(), headers)?.map(|val| val.to_string()); let x_app_id = get_header_value_by_key(X_APP_ID.into(), headers)?.map(|val| val.to_string()); let x_redirect_uri = get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string()); // TODO: combine publishable key and client secret when we unify the auth let client_secret = get_header_value_by_key(X_CLIENT_SECRET.into(), headers)? .map(common_utils::types::ClientSecret::from_str) .transpose() .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid data received in client_secret header".into(), })?; Ok(Self { payment_confirm_source, // client_source, // client_version, x_hs_latency: Some(x_hs_latency), browser_name, x_client_platform, x_merchant_domain, locale, x_app_id, x_redirect_uri, client_secret, }) } } #[cfg(feature = "v1")] impl ForeignTryFrom<( Option<&storage::PaymentAttempt>, Option<&storage::PaymentIntent>, Option<&domain::Address>, Option<&domain::Address>, Option<&domain::Customer>, )> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( value: ( Option<&storage::PaymentAttempt>, Option<&storage::PaymentIntent>, Option<&domain::Address>, Option<&domain::Address>, Option<&domain::Customer>, ), ) -> Result<Self, Self::Error> { let (payment_attempt, payment_intent, shipping, billing, customer) = value; // Populating the dynamic fields directly, for the cases where we have customer details stored in // Payment Intent let customer_details_from_pi = payment_intent .and_then(|payment_intent| payment_intent.customer_details.clone()) .map(|customer_details| { customer_details .into_inner() .peek() .clone() .parse_value::<CustomerData>("CustomerData") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "customer_details", }) .attach_printable("Failed to parse customer_details") }) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "customer_details", })?; let mut billing_address = billing .map(hyperswitch_domain_models::address::Address::from) .map(api_types::Address::from); // This change is to fix a merchant integration // If billing.email is not passed by the merchant, and if the customer email is present, then use the `customer.email` as the billing email if let Some(billing_address) = &mut billing_address { billing_address.email = billing_address.email.clone().or_else(|| { customer .and_then(|cust| { cust.email .as_ref() .map(|email| pii::Email::from(email.clone())) }) .or(customer_details_from_pi.clone().and_then(|cd| cd.email)) }); } else { billing_address = Some(payments::Address { email: customer .and_then(|cust| { cust.email .as_ref() .map(|email| pii::Email::from(email.clone())) }) .or(customer_details_from_pi.clone().and_then(|cd| cd.email)), ..Default::default() }); } Ok(Self { currency: payment_attempt.map(|pa| pa.currency.unwrap_or_default()), shipping: shipping .map(hyperswitch_domain_models::address::Address::from) .map(api_types::Address::from), billing: billing_address, amount: payment_attempt .map(|pa| api_types::Amount::from(pa.net_amount.get_order_amount())), email: customer .and_then(|cust| cust.email.as_ref().map(|em| pii::Email::from(em.clone()))) .or(customer_details_from_pi.clone().and_then(|cd| cd.email)), phone: customer .and_then(|cust| cust.phone.as_ref().map(|p| p.clone().into_inner())) .or(customer_details_from_pi.clone().and_then(|cd| cd.phone)), name: customer .and_then(|cust| cust.name.as_ref().map(|n| n.clone().into_inner())) .or(customer_details_from_pi.clone().and_then(|cd| cd.name)), ..Self::default() }) } } impl ForeignFrom<(storage::PaymentLink, payments::PaymentLinkStatus)> for payments::RetrievePaymentLinkResponse { fn foreign_from( (payment_link_config, status): (storage::PaymentLink, payments::PaymentLinkStatus), ) -> Self { Self { payment_link_id: payment_link_config.payment_link_id, merchant_id: payment_link_config.merchant_id, link_to_pay: payment_link_config.link_to_pay, amount: payment_link_config.amount, created_at: payment_link_config.created_at, expiry: payment_link_config.fulfilment_time, description: payment_link_config.description, currency: payment_link_config.currency, status, secure_link: payment_link_config.secure_link, } } } impl From<domain::Address> for payments::AddressDetails { fn from(addr: domain::Address) -> Self { Self { city: addr.city, country: addr.country, line1: addr.line1.map(Encryptable::into_inner), line2: addr.line2.map(Encryptable::into_inner), line3: addr.line3.map(Encryptable::into_inner), zip: addr.zip.map(Encryptable::into_inner), state: addr.state.map(Encryptable::into_inner), first_name: addr.first_name.map(Encryptable::into_inner), last_name: addr.last_name.map(Encryptable::into_inner), } } } impl ForeignFrom<ConnectorSelection> for routing_types::RoutingAlgorithm { fn foreign_from(value: ConnectorSelection) -> Self { match value { ConnectorSelection::Priority(connectors) => Self::Priority(connectors), ConnectorSelection::VolumeSplit(splits) => Self::VolumeSplit(splits), } } } impl ForeignFrom<api_models::organization::OrganizationNew> for diesel_models::organization::OrganizationNew { fn foreign_from(item: api_models::organization::OrganizationNew) -> Self { Self::new(item.org_id, item.org_name) } } impl ForeignFrom<api_models::organization::OrganizationCreateRequest> for diesel_models::organization::OrganizationNew { fn foreign_from(item: api_models::organization::OrganizationCreateRequest) -> Self { let org_new = api_models::organization::OrganizationNew::new(None); let api_models::organization::OrganizationCreateRequest { organization_name, organization_details, metadata, } = item; let mut org_new_db = Self::new(org_new.org_id, Some(organization_name)); org_new_db.organization_details = organization_details; org_new_db.metadata = metadata; org_new_db } } impl ForeignFrom<gsm_api_types::GsmCreateRequest> for storage::GatewayStatusMappingNew { fn foreign_from(value: gsm_api_types::GsmCreateRequest) -> Self { Self { connector: value.connector.to_string(), flow: value.flow, sub_flow: value.sub_flow, code: value.code, message: value.message, decision: value.decision.to_string(), status: value.status, router_error: value.router_error, step_up_possible: value.step_up_possible, unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, clear_pan_possible: value.clear_pan_possible, } } } impl ForeignFrom<storage::GatewayStatusMap> for gsm_api_types::GsmResponse { fn foreign_from(value: storage::GatewayStatusMap) -> Self { Self { connector: value.connector.to_string(), flow: value.flow, sub_flow: value.sub_flow, code: value.code, message: value.message, decision: value.decision.to_string(), status: value.status, router_error: value.router_error, step_up_possible: value.step_up_possible, unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, clear_pan_possible: value.clear_pan_possible, } } } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl ForeignFrom<&domain::Customer> for payments::CustomerDetailsResponse { fn foreign_from(_customer: &domain::Customer) -> Self { todo!() } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl ForeignFrom<&domain::Customer> for payments::CustomerDetailsResponse { fn foreign_from(customer: &domain::Customer) -> Self { Self { id: Some(customer.customer_id.clone()), name: customer .name .as_ref() .map(|name| name.get_inner().to_owned()), email: customer.email.clone().map(Into::into), phone: customer .phone .as_ref() .map(|phone| phone.get_inner().to_owned()), phone_country_code: customer.phone_country_code.clone(), } } } #[cfg(feature = "olap")] impl ForeignTryFrom<api_types::webhook_events::EventListConstraints> for api_types::webhook_events::EventListConstraintsInternal { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( item: api_types::webhook_events::EventListConstraints, ) -> Result<Self, Self::Error> { if item.object_id.is_some() && (item.created_after.is_some() || item.created_before.is_some() || item.limit.is_some() || item.offset.is_some()) { return Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Either only `object_id` must be specified, or one or more of \ `created_after`, `created_before`, `limit` and `offset` must be specified" .to_string() })); } match item.object_id { Some(object_id) => Ok(Self::ObjectIdFilter { object_id }), None => Ok(Self::GenericFilter { created_after: item.created_after, created_before: item.created_before, limit: item.limit.map(i64::from), offset: item.offset.map(i64::from), is_delivered: item.is_delivered, }), } } } #[cfg(feature = "olap")] impl TryFrom<domain::Event> for api_models::webhook_events::EventListItemResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: domain::Event) -> Result<Self, Self::Error> { use crate::utils::OptionExt; // We only allow retrieving events with merchant_id, business_profile_id // and initial_attempt_id populated. // We cannot retrieve events with only some of these fields populated. let merchant_id = item .merchant_id .get_required_value("merchant_id") .change_context(errors::ApiErrorResponse::InternalServerError)?; let profile_id = item .business_profile_id .get_required_value("business_profile_id") .change_context(errors::ApiErrorResponse::InternalServerError)?; let initial_attempt_id = item .initial_attempt_id .get_required_value("initial_attempt_id") .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(Self { event_id: item.event_id, merchant_id, profile_id, object_id: item.primary_object_id, event_type: item.event_type, event_class: item.event_class, is_delivery_successful: item.is_overall_delivery_successful, initial_attempt_id, created: item.created_at, }) } } #[cfg(feature = "olap")] impl TryFrom<domain::Event> for api_models::webhook_events::EventRetrieveResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: domain::Event) -> Result<Self, Self::Error> { use crate::utils::OptionExt; // We only allow retrieving events with all required fields in `EventListItemResponse`, and // `request` and `response` populated. // We cannot retrieve events with only some of these fields populated. let event_information = api_models::webhook_events::EventListItemResponse::try_from(item.clone())?; let request = item .request .get_required_value("request") .change_context(errors::ApiErrorResponse::InternalServerError)? .peek() .parse_struct("OutgoingWebhookRequestContent") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse webhook event request information")?; let response = item .response .get_required_value("response") .change_context(errors::ApiErrorResponse::InternalServerError)? .peek() .parse_struct("OutgoingWebhookResponseContent") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse webhook event response information")?; Ok(Self { event_information, request, response, delivery_attempt: item.delivery_attempt, }) } } impl ForeignFrom<api_models::admin::AuthenticationConnectorDetails> for diesel_models::business_profile::AuthenticationConnectorDetails { fn foreign_from(item: api_models::admin::AuthenticationConnectorDetails) -> Self { Self { authentication_connectors: item.authentication_connectors, three_ds_requestor_url: item.three_ds_requestor_url, three_ds_requestor_app_url: item.three_ds_requestor_app_url, } } } impl ForeignFrom<diesel_models::business_profile::AuthenticationConnectorDetails> for api_models::admin::AuthenticationConnectorDetails { fn foreign_from(item: diesel_models::business_profile::AuthenticationConnectorDetails) -> Self { Self { authentication_connectors: item.authentication_connectors, three_ds_requestor_url: item.three_ds_requestor_url, three_ds_requestor_app_url: item.three_ds_requestor_app_url, } } } impl ForeignFrom<api_models::admin::CardTestingGuardConfig> for diesel_models::business_profile::CardTestingGuardConfig { fn foreign_from(item: api_models::admin::CardTestingGuardConfig) -> Self { Self { is_card_ip_blocking_enabled: match item.card_ip_blocking_status { api_models::admin::CardTestingGuardStatus::Enabled => true, api_models::admin::CardTestingGuardStatus::Disabled => false, }, card_ip_blocking_threshold: item.card_ip_blocking_threshold, is_guest_user_card_blocking_enabled: match item.guest_user_card_blocking_status { api_models::admin::CardTestingGuardStatus::Enabled => true, api_models::admin::CardTestingGuardStatus::Disabled => false, }, guest_user_card_blocking_threshold: item.guest_user_card_blocking_threshold, is_customer_id_blocking_enabled: match item.customer_id_blocking_status { api_models::admin::CardTestingGuardStatus::Enabled => true, api_models::admin::CardTestingGuardStatus::Disabled => false, }, customer_id_blocking_threshold: item.customer_id_blocking_threshold, card_testing_guard_expiry: item.card_testing_guard_expiry, } } } impl ForeignFrom<diesel_models::business_profile::CardTestingGuardConfig> for api_models::admin::CardTestingGuardConfig { fn foreign_from(item: diesel_models::business_profile::CardTestingGuardConfig) -> Self { Self { card_ip_blocking_status: match item.is_card_ip_blocking_enabled { true => api_models::admin::CardTestingGuardStatus::Enabled, false => api_models::admin::CardTestingGuardStatus::Disabled, }, card_ip_blocking_threshold: item.card_ip_blocking_threshold, guest_user_card_blocking_status: match item.is_guest_user_card_blocking_enabled { true => api_models::admin::CardTestingGuardStatus::Enabled, false => api_models::admin::CardTestingGuardStatus::Disabled, }, guest_user_card_blocking_threshold: item.guest_user_card_blocking_threshold, customer_id_blocking_status: match item.is_customer_id_blocking_enabled { true => api_models::admin::CardTestingGuardStatus::Enabled, false => api_models::admin::CardTestingGuardStatus::Disabled, }, customer_id_blocking_threshold: item.customer_id_blocking_threshold, card_testing_guard_expiry: item.card_testing_guard_expiry, } } } impl ForeignFrom<api_models::admin::WebhookDetails> for diesel_models::business_profile::WebhookDetails { fn foreign_from(item: api_models::admin::WebhookDetails) -> Self { Self { webhook_version: item.webhook_version, webhook_username: item.webhook_username, webhook_password: item.webhook_password, webhook_url: item.webhook_url, payment_created_enabled: item.payment_created_enabled, payment_succeeded_enabled: item.payment_succeeded_enabled, payment_failed_enabled: item.payment_failed_enabled, } } } impl ForeignFrom<diesel_models::business_profile::WebhookDetails> for api_models::admin::WebhookDetails { fn foreign_from(item: diesel_models::business_profile::WebhookDetails) -> Self { Self { webhook_version: item.webhook_version, webhook_username: item.webhook_username, webhook_password: item.webhook_password, webhook_url: item.webhook_url, payment_created_enabled: item.payment_created_enabled, payment_succeeded_enabled: item.payment_succeeded_enabled, payment_failed_enabled: item.payment_failed_enabled, } } } impl ForeignFrom<api_models::admin::BusinessPaymentLinkConfig> for diesel_models::business_profile::BusinessPaymentLinkConfig { fn foreign_from(item: api_models::admin::BusinessPaymentLinkConfig) -> Self { Self { domain_name: item.domain_name, default_config: item.default_config.map(ForeignInto::foreign_into), business_specific_configs: item.business_specific_configs.map(|map| { map.into_iter() .map(|(k, v)| (k, v.foreign_into())) .collect() }), allowed_domains: item.allowed_domains, branding_visibility: item.branding_visibility, } } } impl ForeignFrom<diesel_models::business_profile::BusinessPaymentLinkConfig> for api_models::admin::BusinessPaymentLinkConfig { fn foreign_from(item: diesel_models::business_profile::BusinessPaymentLinkConfig) -> Self { Self { domain_name: item.domain_name, default_config: item.default_config.map(ForeignInto::foreign_into), business_specific_configs: item.business_specific_configs.map(|map| { map.into_iter() .map(|(k, v)| (k, v.foreign_into())) .collect() }), allowed_domains: item.allowed_domains, branding_visibility: item.branding_visibility, } } } impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> for diesel_models::business_profile::PaymentLinkConfigRequest { fn foreign_from(item: api_models::admin::PaymentLinkConfigRequest) -> Self { Self { theme: item.theme, logo: item.logo, seller_name: item.seller_name, sdk_layout: item.sdk_layout, display_sdk_only: item.display_sdk_only, enabled_saved_payment_method: item.enabled_saved_payment_method, hide_card_nickname_field: item.hide_card_nickname_field, show_card_form_by_default: item.show_card_form_by_default, details_layout: item.details_layout, background_image: item .background_image .map(|background_image| background_image.foreign_into()), payment_button_text: item.payment_button_text, skip_status_screen: item.skip_status_screen, custom_message_for_card_terms: item.custom_message_for_card_terms, payment_button_colour: item.payment_button_colour, background_colour: item.background_colour, payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, } } } impl ForeignFrom<diesel_models::business_profile::PaymentLinkConfigRequest> for api_models::admin::PaymentLinkConfigRequest { fn foreign_from(item: diesel_models::business_profile::PaymentLinkConfigRequest) -> Self { Self { theme: item.theme, logo: item.logo, seller_name: item.seller_name, sdk_layout: item.sdk_layout, display_sdk_only: item.display_sdk_only, enabled_saved_payment_method: item.enabled_saved_payment_method, hide_card_nickname_field: item.hide_card_nickname_field, show_card_form_by_default: item.show_card_form_by_default, transaction_details: None, details_layout: item.details_layout, background_image: item .background_image .map(|background_image| background_image.foreign_into()), payment_button_text: item.payment_button_text, skip_status_screen: item.skip_status_screen, custom_message_for_card_terms: item.custom_message_for_card_terms, payment_button_colour: item.payment_button_colour, background_colour: item.background_colour, payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, } } } impl ForeignFrom<diesel_models::business_profile::PaymentLinkBackgroundImageConfig> for api_models::admin::PaymentLinkBackgroundImageConfig { fn foreign_from( item: diesel_models::business_profile::PaymentLinkBackgroundImageConfig, ) -> Self { Self { url: item.url, position: item.position, size: item.size, } } } impl ForeignFrom<api_models::admin::PaymentLinkBackgroundImageConfig> for diesel_models::business_profile::PaymentLinkBackgroundImageConfig { fn foreign_from(item: api_models::admin::PaymentLinkBackgroundImageConfig) -> Self { Self { url: item.url, position: item.position, size: item.size, } } } impl ForeignFrom<api_models::admin::BusinessPayoutLinkConfig> for diesel_models::business_profile::BusinessPayoutLinkConfig { fn foreign_from(item: api_models::admin::BusinessPayoutLinkConfig) -> Self { Self { config: item.config.foreign_into(), form_layout: item.form_layout, payout_test_mode: item.payout_test_mode, } } } impl ForeignFrom<diesel_models::business_profile::BusinessPayoutLinkConfig> for api_models::admin::BusinessPayoutLinkConfig { fn foreign_from(item: diesel_models::business_profile::BusinessPayoutLinkConfig) -> Self { Self { config: item.config.foreign_into(), form_layout: item.form_layout, payout_test_mode: item.payout_test_mode, } } } impl ForeignFrom<api_models::admin::BusinessGenericLinkConfig> for diesel_models::business_profile::BusinessGenericLinkConfig { fn foreign_from(item: api_models::admin::BusinessGenericLinkConfig) -> Self { Self { domain_name: item.domain_name, allowed_domains: item.allowed_domains, ui_config: item.ui_config, } } } impl ForeignFrom<diesel_models::business_profile::BusinessGenericLinkConfig> for api_models::admin::BusinessGenericLinkConfig { fn foreign_from(item: diesel_models::business_profile::BusinessGenericLinkConfig) -> Self { Self { domain_name: item.domain_name, allowed_domains: item.allowed_domains, ui_config: item.ui_config, } } } impl ForeignFrom<card_info_types::CardInfoCreateRequest> for storage::CardInfo { fn foreign_from(value: card_info_types::CardInfoCreateRequest) -> Self { Self { card_iin: value.card_iin, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_subtype: value.card_subtype, card_issuing_country: value.card_issuing_country, bank_code_id: value.bank_code_id, bank_code: value.bank_code, country_code: value.country_code, date_created: common_utils::date_time::now(), last_updated: Some(common_utils::date_time::now()), last_updated_provider: value.last_updated_provider, } } } impl ForeignFrom<card_info_types::CardInfoUpdateRequest> for storage::CardInfo { fn foreign_from(value: card_info_types::CardInfoUpdateRequest) -> Self { Self { card_iin: value.card_iin, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_subtype: value.card_subtype, card_issuing_country: value.card_issuing_country, bank_code_id: value.bank_code_id, bank_code: value.bank_code, country_code: value.country_code, date_created: common_utils::date_time::now(), last_updated: Some(common_utils::date_time::now()), last_updated_provider: value.last_updated_provider, } } }
20,848
1,337
hyperswitch
crates/router/src/types/domain.rs
.rs
pub mod behaviour { pub use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion}; } mod merchant_account { pub use hyperswitch_domain_models::merchant_account::*; } mod business_profile { pub use hyperswitch_domain_models::business_profile::{ Profile, ProfileGeneralUpdate, ProfileSetter, ProfileUpdate, }; } mod customers { pub use hyperswitch_domain_models::customer::*; } mod callback_mapper { pub use hyperswitch_domain_models::callback_mapper::CallbackMapper; } mod network_tokenization { pub use hyperswitch_domain_models::network_tokenization::*; } pub use customers::*; pub use merchant_account::*; mod address; mod event; mod merchant_connector_account; mod merchant_key_store { pub use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; } pub use hyperswitch_domain_models::bulk_tokenization::*; pub mod payment_methods { pub use hyperswitch_domain_models::payment_methods::*; } pub mod consts { pub use hyperswitch_domain_models::consts::*; } pub mod payment_method_data { pub use hyperswitch_domain_models::payment_method_data::*; } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub mod vault { pub use hyperswitch_domain_models::vault::*; } pub mod payments; pub mod types; #[cfg(feature = "olap")] pub mod user; pub mod user_key_store; pub use address::*; pub use business_profile::*; pub use callback_mapper::*; pub use consts::*; pub use event::*; pub use merchant_connector_account::*; pub use merchant_key_store::*; pub use network_tokenization::*; pub use payment_method_data::*; pub use payment_methods::*; #[cfg(feature = "olap")] pub use user::*; pub use user_key_store::*; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub use vault::*;
373
1,338
hyperswitch
crates/router/src/types/fraud_check.rs
.rs
pub use hyperswitch_domain_models::{ router_request_types::fraud_check::{ FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, FraudCheckSaleData, FraudCheckTransactionData, RefundMethod, }, router_response_types::fraud_check::FraudCheckResponseData, }; use crate::{ services, types::{api, ErrorResponse, RouterData}, }; pub type FrmSaleRouterData = RouterData<api::Sale, FraudCheckSaleData, FraudCheckResponseData>; pub type FrmSaleType = dyn services::ConnectorIntegration<api::Sale, FraudCheckSaleData, FraudCheckResponseData>; #[derive(Debug, Clone)] pub struct FrmRouterData { pub merchant_id: common_utils::id_type::MerchantId, pub connector: String, // TODO: change this to PaymentId type pub payment_id: String, pub attempt_id: String, pub request: FrmRequest, pub response: FrmResponse, } #[derive(Debug, Clone)] pub enum FrmRequest { Sale(FraudCheckSaleData), Checkout(Box<FraudCheckCheckoutData>), Transaction(FraudCheckTransactionData), Fulfillment(FraudCheckFulfillmentData), RecordReturn(FraudCheckRecordReturnData), } #[derive(Debug, Clone)] pub enum FrmResponse { Sale(Result<FraudCheckResponseData, ErrorResponse>), Checkout(Result<FraudCheckResponseData, ErrorResponse>), Transaction(Result<FraudCheckResponseData, ErrorResponse>), Fulfillment(Result<FraudCheckResponseData, ErrorResponse>), RecordReturn(Result<FraudCheckResponseData, ErrorResponse>), } pub type FrmCheckoutRouterData = RouterData<api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>; pub type FrmCheckoutType = dyn services::ConnectorIntegration< api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData, >; pub type FrmTransactionRouterData = RouterData<api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>; pub type FrmTransactionType = dyn services::ConnectorIntegration< api::Transaction, FraudCheckTransactionData, FraudCheckResponseData, >; pub type FrmFulfillmentRouterData = RouterData<api::Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>; pub type FrmFulfillmentType = dyn services::ConnectorIntegration< api::Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData, >; pub type FrmRecordReturnRouterData = RouterData<api::RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>; pub type FrmRecordReturnType = dyn services::ConnectorIntegration< api::RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData, >;
580
1,339
hyperswitch
crates/router/src/types/payment_methods.rs
.rs
use std::fmt::Debug; use api_models::enums as api_enums; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] use cards::CardNumber; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use cards::{CardNumber, NetworkToken}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use common_types::primitive_wrappers; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use common_utils::generate_id; use common_utils::id_type; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use hyperswitch_domain_models::payment_method_data::NetworkTokenDetails; use masking::Secret; use serde::{Deserialize, Serialize}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use crate::{ consts, types::{api, domain, storage}, }; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub trait VaultingInterface { fn get_vaulting_request_url() -> &'static str; fn get_vaulting_flow_name() -> &'static str; } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultFingerprintRequest { pub data: String, pub key: String, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultFingerprintResponse { pub fingerprint_id: String, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultRequest<D> { pub entity_id: id_type::MerchantId, pub vault_id: domain::VaultId, pub data: D, pub ttl: i64, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultResponse { pub entity_id: id_type::MerchantId, pub vault_id: domain::VaultId, pub fingerprint_id: Option<String>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVault; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetVaultFingerprint; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultRetrieve; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultDelete; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl VaultingInterface for AddVault { fn get_vaulting_request_url() -> &'static str { consts::ADD_VAULT_REQUEST_URL } fn get_vaulting_flow_name() -> &'static str { consts::VAULT_ADD_FLOW_TYPE } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl VaultingInterface for GetVaultFingerprint { fn get_vaulting_request_url() -> &'static str { consts::VAULT_FINGERPRINT_REQUEST_URL } fn get_vaulting_flow_name() -> &'static str { consts::VAULT_GET_FINGERPRINT_FLOW_TYPE } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl VaultingInterface for VaultRetrieve { fn get_vaulting_request_url() -> &'static str { consts::VAULT_RETRIEVE_REQUEST_URL } fn get_vaulting_flow_name() -> &'static str { consts::VAULT_RETRIEVE_FLOW_TYPE } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl VaultingInterface for VaultDelete { fn get_vaulting_request_url() -> &'static str { consts::VAULT_DELETE_REQUEST_URL } fn get_vaulting_flow_name() -> &'static str { consts::VAULT_DELETE_FLOW_TYPE } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub struct SavedPMLPaymentsInfo { pub payment_intent: storage::PaymentIntent, pub profile: domain::Profile, pub collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub off_session_payment_flag: bool, pub is_connector_agnostic_mit_enabled: bool, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultRetrieveRequest { pub entity_id: id_type::MerchantId, pub vault_id: domain::VaultId, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultRetrieveResponse { pub data: domain::PaymentMethodVaultingData, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultDeleteRequest { pub entity_id: id_type::MerchantId, pub vault_id: domain::VaultId, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultDeleteResponse { pub entity_id: id_type::MerchantId, pub vault_id: domain::VaultId, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardData { pub card_number: CardNumber, pub exp_month: Secret<String>, pub exp_year: Secret<String>, pub card_security_code: Option<Secret<String>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardData { pub card_number: CardNumber, pub exp_month: Secret<String>, pub exp_year: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub card_security_code: Option<Secret<String>>, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderData { pub consent_id: String, pub customer_id: id_type::CustomerId, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderData { pub consent_id: String, pub customer_id: id_type::GlobalCustomerId, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApiPayload { pub service: String, pub card_data: Secret<String>, //encrypted card data pub order_data: OrderData, pub key_id: String, pub should_send_token: bool, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct CardNetworkTokenResponse { pub payload: Secret<String>, //encrypted payload } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardNetworkTokenResponsePayload { pub card_brand: api_enums::CardNetwork, pub card_fingerprint: Option<Secret<String>>, pub card_reference: String, pub correlation_id: String, pub customer_id: String, pub par: String, pub token: CardNumber, pub token_expiry_month: Secret<String>, pub token_expiry_year: Secret<String>, pub token_isin: String, pub token_last_four: String, pub token_status: String, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GenerateNetworkTokenResponsePayload { pub card_brand: api_enums::CardNetwork, pub card_fingerprint: Option<Secret<String>>, pub card_reference: String, pub correlation_id: String, pub customer_id: String, pub par: String, pub token: NetworkToken, pub token_expiry_month: Secret<String>, pub token_expiry_year: Secret<String>, pub token_isin: String, pub token_last_four: String, pub token_status: String, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, Serialize)] pub struct GetCardToken { pub card_reference: String, pub customer_id: id_type::CustomerId, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Serialize)] pub struct GetCardToken { pub card_reference: String, pub customer_id: id_type::GlobalCustomerId, } #[derive(Debug, Deserialize)] pub struct AuthenticationDetails { pub cryptogram: Secret<String>, pub token: CardNumber, //network token } #[derive(Debug, Serialize, Deserialize)] pub struct TokenDetails { pub exp_month: Secret<String>, pub exp_year: Secret<String>, } #[derive(Debug, Deserialize)] pub struct TokenResponse { pub authentication_details: AuthenticationDetails, pub network: api_enums::CardNetwork, pub token_details: TokenDetails, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, Serialize, Deserialize)] pub struct DeleteCardToken { pub card_reference: String, //network token requestor ref id pub customer_id: id_type::CustomerId, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Serialize, Deserialize)] pub struct DeleteCardToken { pub card_reference: String, //network token requestor ref id pub customer_id: id_type::GlobalCustomerId, } #[derive(Debug, Deserialize, Eq, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum DeleteNetworkTokenStatus { Success, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct NetworkTokenErrorInfo { pub code: String, pub developer_message: String, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct NetworkTokenErrorResponse { pub error_message: String, pub error_info: NetworkTokenErrorInfo, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct DeleteNetworkTokenResponse { pub status: DeleteNetworkTokenStatus, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, Serialize, Deserialize)] pub struct CheckTokenStatus { pub card_reference: String, pub customer_id: id_type::CustomerId, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Serialize, Deserialize)] pub struct CheckTokenStatus { pub card_reference: String, pub customer_id: id_type::GlobalCustomerId, } #[derive(Debug, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum TokenStatus { Active, Inactive, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CheckTokenStatusResponsePayload { pub token_expiry_month: Secret<String>, pub token_expiry_year: Secret<String>, pub token_status: TokenStatus, } #[derive(Debug, Deserialize)] pub struct CheckTokenStatusResponse { pub payload: CheckTokenStatusResponsePayload, }
2,640
1,340
hyperswitch
crates/router/src/types/storage.rs
.rs
pub mod address; pub mod api_keys; pub mod authentication; pub mod authorization; pub mod blocklist; pub mod blocklist_fingerprint; pub mod blocklist_lookup; pub mod business_profile; pub mod callback_mapper; pub mod capture; pub mod cards_info; pub mod configs; pub mod customers; pub mod dashboard_metadata; pub mod dispute; pub mod dynamic_routing_stats; pub mod enums; pub mod ephemeral_key; pub mod events; pub mod file; pub mod fraud_check; pub mod generic_link; pub mod gsm; #[cfg(feature = "kv_store")] pub mod kv; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; pub mod payment_attempt; pub mod payment_link; pub mod payment_method; pub mod payout_attempt; pub mod payouts; pub mod refund; #[cfg(feature = "v2")] pub mod revenue_recovery; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; pub mod unified_translations; pub mod user; pub mod user_authentication_method; pub mod user_role; pub use diesel_models::{ process_tracker::business_status, ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner, ProcessTrackerUpdate, }; #[cfg(feature = "v1")] pub use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew; #[cfg(feature = "payouts")] pub use hyperswitch_domain_models::payouts::{ payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate}, payouts::{Payouts, PayoutsNew, PayoutsUpdate}, }; pub use hyperswitch_domain_models::{ payments::{ payment_attempt::{PaymentAttempt, PaymentAttemptUpdate}, payment_intent::{PaymentIntentUpdate, PaymentIntentUpdateFields}, PaymentIntent, }, routing::{ PaymentRoutingInfo, PaymentRoutingInfoInner, PreRoutingConnectorChoice, RoutingData, }, }; pub use scheduler::db::process_tracker; pub use self::{ address::*, api_keys::*, authentication::*, authorization::*, blocklist::*, blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, callback_mapper::*, capture::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*, dispute::*, dynamic_routing_stats::*, ephemeral_key::*, events::*, file::*, fraud_check::*, generic_link::*, gsm::*, locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*, routing_algorithm::*, unified_translations::*, user::*, user_authentication_method::*, user_role::*, };
569
1,341
hyperswitch
crates/router/src/types/storage/payment_link.rs
.rs
use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{associations::HasTable, ExpressionMethods, QueryDsl}; pub use diesel_models::{ payment_link::{PaymentLink, PaymentLinkNew}, schema::payment_link::dsl, }; use error_stack::ResultExt; use crate::{ connection::PgPooledConn, core::errors::{self, CustomResult}, logger, }; #[async_trait::async_trait] pub trait PaymentLinkDbExt: Sized { async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<Self>, errors::DatabaseError>; } #[async_trait::async_trait] impl PaymentLinkDbExt for PaymentLink { async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<Self>, errors::DatabaseError> { let mut filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .order(dsl::created_at.desc()) .into_boxed(); if let Some(created_time) = payment_link_list_constraints.created { filter = filter.filter(dsl::created_at.eq(created_time)); } if let Some(created_time_lt) = payment_link_list_constraints.created_lt { filter = filter.filter(dsl::created_at.lt(created_time_lt)); } if let Some(created_time_gt) = payment_link_list_constraints.created_gt { filter = filter.filter(dsl::created_at.gt(created_time_gt)); } if let Some(created_time_lte) = payment_link_list_constraints.created_lte { filter = filter.filter(dsl::created_at.le(created_time_lte)); } if let Some(created_time_gte) = payment_link_list_constraints.created_gte { filter = filter.filter(dsl::created_at.ge(created_time_gte)); } if let Some(limit) = payment_link_list_constraints.limit { filter = filter.limit(limit); } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string()); filter .get_results_async(conn) .await // The query built here returns an empty Vec when no records are found, and if any error does occur, // it would be an internal database error, due to which we are raising a DatabaseError::Unknown error .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering payment link by specified constraints") } }
588
1,342
hyperswitch
crates/router/src/types/storage/merchant_account.rs
.rs
pub use diesel_models::merchant_account::{ MerchantAccount, MerchantAccountNew, MerchantAccountUpdateInternal, }; pub use crate::types::domain::MerchantAccountUpdate;
34
1,343
hyperswitch
crates/router/src/types/storage/refund.rs
.rs
use api_models::payments::AmountFilter; use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::errors::CustomResult; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl}; pub use diesel_models::refund::{ Refund, RefundCoreWorkflow, RefundNew, RefundUpdate, RefundUpdateInternal, }; use diesel_models::{ enums::{Currency, RefundStatus}, errors, query::generics::db_metrics, schema::refund::dsl, }; use error_stack::ResultExt; use hyperswitch_domain_models::refunds; use crate::{connection::PgPooledConn, logger}; #[async_trait::async_trait] pub trait RefundDbExt: Sized { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &refunds::RefundListConstraints, limit: i64, offset: i64, ) -> CustomResult<Vec<Self>, errors::DatabaseError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_meta_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &common_utils::types::TimeRange, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refunds_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &refunds::RefundListConstraints, ) -> CustomResult<i64, errors::DatabaseError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refund_status_with_count( conn: &PgPooledConn, 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<(RefundStatus, i64)>, errors::DatabaseError>; } #[async_trait::async_trait] impl RefundDbExt for Refund { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &refunds::RefundListConstraints, limit: i64, offset: i64, ) -> CustomResult<Vec<Self>, errors::DatabaseError> { let mut filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .order(dsl::modified_at.desc()) .into_boxed(); let mut search_by_pay_or_ref_id = false; if let (Some(pid), Some(ref_id)) = ( &refund_list_details.payment_id, &refund_list_details.refund_id, ) { search_by_pay_or_ref_id = true; filter = filter .filter( dsl::payment_id .eq(pid.to_owned()) .or(dsl::refund_id.eq(ref_id.to_owned())), ) .limit(limit) .offset(offset); }; if !search_by_pay_or_ref_id { match &refund_list_details.payment_id { Some(pid) => { filter = filter.filter(dsl::payment_id.eq(pid.to_owned())); } None => { filter = filter.limit(limit).offset(offset); } }; } if !search_by_pay_or_ref_id { match &refund_list_details.refund_id { Some(ref_id) => { filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned())); } None => { filter = filter.limit(limit).offset(offset); } }; } match &refund_list_details.profile_id { Some(profile_id) => { filter = filter .filter(dsl::profile_id.eq_any(profile_id.to_owned())) .limit(limit) .offset(offset); } None => { filter = filter.limit(limit).offset(offset); } }; if let Some(time_range) = refund_list_details.time_range { filter = filter.filter(dsl::created_at.ge(time_range.start_time)); if let Some(end_time) = time_range.end_time { filter = filter.filter(dsl::created_at.le(end_time)); } } filter = match refund_list_details.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => filter.filter(dsl::refund_amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => filter.filter(dsl::refund_amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => filter.filter(dsl::refund_amount.le(end)), _ => filter, }; if let Some(connector) = refund_list_details.connector.clone() { filter = filter.filter(dsl::connector.eq_any(connector)); } if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id)); } if let Some(filter_currency) = &refund_list_details.currency { filter = filter.filter(dsl::currency.eq_any(filter_currency.clone())); } if let Some(filter_refund_status) = &refund_list_details.refund_status { filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone())); } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string()); db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_results_async(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering records by predicate") } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_meta_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &common_utils::types::TimeRange, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError> { let start_time = refund_list_details.start_time; let end_time = refund_list_details .end_time .unwrap_or_else(common_utils::date_time::now); let filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .order(dsl::modified_at.desc()) .filter(dsl::created_at.ge(start_time)) .filter(dsl::created_at.le(end_time)); let filter_connector: Vec<String> = filter .clone() .select(dsl::connector) .distinct() .order_by(dsl::connector.asc()) .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering records by connector")?; let filter_currency: Vec<Currency> = filter .clone() .select(dsl::currency) .distinct() .order_by(dsl::currency.asc()) .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering records by currency")?; let filter_status: Vec<RefundStatus> = filter .select(dsl::refund_status) .distinct() .order_by(dsl::refund_status.asc()) .get_results_async(conn) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering records by refund status")?; let meta = api_models::refunds::RefundListMetaData { connector: filter_connector, currency: filter_currency, refund_status: filter_status, }; Ok(meta) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refunds_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &refunds::RefundListConstraints, ) -> CustomResult<i64, errors::DatabaseError> { let mut filter = <Self as HasTable>::table() .count() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .into_boxed(); let mut search_by_pay_or_ref_id = false; if let (Some(pid), Some(ref_id)) = ( &refund_list_details.payment_id, &refund_list_details.refund_id, ) { search_by_pay_or_ref_id = true; filter = filter.filter( dsl::payment_id .eq(pid.to_owned()) .or(dsl::refund_id.eq(ref_id.to_owned())), ); }; if !search_by_pay_or_ref_id { if let Some(pay_id) = &refund_list_details.payment_id { filter = filter.filter(dsl::payment_id.eq(pay_id.to_owned())); } } if !search_by_pay_or_ref_id { if let Some(ref_id) = &refund_list_details.refund_id { filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned())); } } if let Some(profile_id) = &refund_list_details.profile_id { filter = filter.filter(dsl::profile_id.eq_any(profile_id.to_owned())); } if let Some(time_range) = refund_list_details.time_range { filter = filter.filter(dsl::created_at.ge(time_range.start_time)); if let Some(end_time) = time_range.end_time { filter = filter.filter(dsl::created_at.le(end_time)); } } filter = match refund_list_details.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => filter.filter(dsl::refund_amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => filter.filter(dsl::refund_amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => filter.filter(dsl::refund_amount.le(end)), _ => filter, }; if let Some(connector) = refund_list_details.connector.clone() { filter = filter.filter(dsl::connector.eq_any(connector)); } if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id)) } if let Some(filter_currency) = &refund_list_details.currency { filter = filter.filter(dsl::currency.eq_any(filter_currency.clone())); } if let Some(filter_refund_status) = &refund_list_details.refund_status { filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone())); } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string()); filter .get_result_async::<i64>(conn) .await .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering count of refunds") } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refund_status_with_count( conn: &PgPooledConn, 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<(RefundStatus, i64)>, errors::DatabaseError> { let mut query = <Self as HasTable>::table() .group_by(dsl::refund_status) .select((dsl::refund_status, diesel::dsl::count_star())) .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .into_boxed(); if let Some(profile_id) = profile_id_list { query = query.filter(dsl::profile_id.eq_any(profile_id)); } query = query.filter(dsl::created_at.ge(time_range.start_time)); query = match time_range.end_time { Some(ending_at) => query.filter(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::<<Self as HasTable>::Table, _, _>( query.get_results_async::<(RefundStatus, i64)>(conn), db_metrics::DatabaseOperation::Count, ) .await .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering status count of refunds") } }
2,970
1,344
hyperswitch
crates/router/src/types/storage/capture.rs
.rs
pub use diesel_models::capture::*;
7
1,345
hyperswitch
crates/router/src/types/storage/enums.rs
.rs
pub use diesel_models::enums::*;
7
1,346
hyperswitch
crates/router/src/types/storage/kv.rs
.rs
pub use diesel_models::kv::{ AddressUpdateMems, DBOperation, Insertable, PaymentAttemptUpdateMems, PaymentIntentUpdateMems, RefundUpdateMems, TypedSql, Updateable, };
46
1,347
hyperswitch
crates/router/src/types/storage/authorization.rs
.rs
pub use diesel_models::authorization::{Authorization, AuthorizationNew, AuthorizationUpdate};
15
1,348
hyperswitch
crates/router/src/types/storage/file.rs
.rs
pub use diesel_models::file::{ FileMetadata, FileMetadataNew, FileMetadataUpdate, FileMetadataUpdateInternal, };
25
1,349
hyperswitch
crates/router/src/types/storage/authentication.rs
.rs
pub use diesel_models::authentication::{Authentication, AuthenticationNew, AuthenticationUpdate};
15
1,350
hyperswitch
crates/router/src/types/storage/unified_translations.rs
.rs
pub use diesel_models::unified_translations::{ UnifiedTranslations, UnifiedTranslationsNew, UnifiedTranslationsUpdate, UnifiedTranslationsUpdateInternal, };
29
1,351
hyperswitch
crates/router/src/types/storage/api_keys.rs
.rs
#[cfg(feature = "email")] pub use diesel_models::api_keys::ApiKeyExpiryTrackingData; pub use diesel_models::api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, HashedApiKey};
43
1,352
hyperswitch
crates/router/src/types/storage/user.rs
.rs
pub use diesel_models::user::*;
7
1,353
hyperswitch
crates/router/src/types/storage/address.rs
.rs
pub use diesel_models::address::{Address, AddressNew, AddressUpdateInternal}; pub use crate::types::domain::AddressUpdate;
27
1,354
hyperswitch
crates/router/src/types/storage/callback_mapper.rs
.rs
pub use diesel_models::callback_mapper::CallbackMapper;
11
1,355
hyperswitch
crates/router/src/types/storage/locker_mock_up.rs
.rs
pub use diesel_models::locker_mock_up::{LockerMockUp, LockerMockUpNew};
18
1,356
hyperswitch
crates/router/src/types/storage/routing_algorithm.rs
.rs
pub use diesel_models::routing_algorithm::{ RoutingAlgorithm, RoutingAlgorithmMetadata, RoutingProfileMetadata, };
21
1,357
hyperswitch
crates/router/src/types/storage/dynamic_routing_stats.rs
.rs
pub use diesel_models::dynamic_routing_stats::{ DynamicRoutingStats, DynamicRoutingStatsNew, DynamicRoutingStatsUpdate, };
25
1,358
hyperswitch
crates/router/src/types/storage/dispute.rs
.rs
use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::errors::CustomResult; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl}; pub use diesel_models::dispute::{Dispute, DisputeNew, DisputeUpdate}; use diesel_models::{errors, query::generics::db_metrics, schema::dispute::dsl}; use error_stack::ResultExt; use hyperswitch_domain_models::disputes; use crate::{connection::PgPooledConn, logger}; #[async_trait::async_trait] pub trait DisputeDbExt: Sized { async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, dispute_list_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<Self>, errors::DatabaseError>; async fn get_dispute_status_with_count( conn: &PgPooledConn, 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::DatabaseError>; } #[async_trait::async_trait] impl DisputeDbExt for Dispute { async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, dispute_list_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<Self>, errors::DatabaseError> { let mut filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .order(dsl::modified_at.desc()) .into_boxed(); let mut search_by_payment_or_dispute_id = false; if let (Some(payment_id), Some(dispute_id)) = ( &dispute_list_constraints.payment_id, &dispute_list_constraints.dispute_id, ) { search_by_payment_or_dispute_id = true; filter = filter.filter( dsl::payment_id .eq(payment_id.to_owned()) .or(dsl::dispute_id.eq(dispute_id.to_owned())), ); }; if !search_by_payment_or_dispute_id { if let Some(payment_id) = &dispute_list_constraints.payment_id { filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned())); }; } if !search_by_payment_or_dispute_id { if let Some(dispute_id) = &dispute_list_constraints.dispute_id { filter = filter.filter(dsl::dispute_id.eq(dispute_id.clone())); }; } if let Some(time_range) = dispute_list_constraints.time_range { filter = filter.filter(dsl::created_at.ge(time_range.start_time)); if let Some(end_time) = time_range.end_time { filter = filter.filter(dsl::created_at.le(end_time)); } } if let Some(profile_id) = &dispute_list_constraints.profile_id { filter = filter.filter(dsl::profile_id.eq_any(profile_id.clone())); } if let Some(connector_list) = &dispute_list_constraints.connector { filter = filter.filter(dsl::connector.eq_any(connector_list.clone())); } if let Some(reason) = &dispute_list_constraints.reason { filter = filter.filter(dsl::connector_reason.eq(reason.clone())); } if let Some(dispute_stage) = &dispute_list_constraints.dispute_stage { filter = filter.filter(dsl::dispute_stage.eq_any(dispute_stage.clone())); } if let Some(dispute_status) = &dispute_list_constraints.dispute_status { filter = filter.filter(dsl::dispute_status.eq_any(dispute_status.clone())); } if let Some(currency_list) = &dispute_list_constraints.currency { filter = filter.filter(dsl::dispute_currency.eq_any(currency_list.clone())); } if let Some(merchant_connector_id) = &dispute_list_constraints.merchant_connector_id { filter = filter.filter(dsl::merchant_connector_id.eq(merchant_connector_id.clone())) } if let Some(limit) = dispute_list_constraints.limit { filter = filter.limit(limit.into()); } if let Some(offset) = dispute_list_constraints.offset { filter = filter.offset(offset.into()); } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string()); db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_results_async(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering records by predicate") } async fn get_dispute_status_with_count( conn: &PgPooledConn, 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::DatabaseError> { let mut query = <Self as HasTable>::table() .group_by(dsl::dispute_status) .select((dsl::dispute_status, diesel::dsl::count_star())) .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .into_boxed(); if let Some(profile_id) = profile_id_list { query = query.filter(dsl::profile_id.eq_any(profile_id)); } query = query.filter(dsl::created_at.ge(time_range.start_time)); query = match time_range.end_time { Some(ending_at) => query.filter(dsl::created_at.le(ending_at)), None => query, }; logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( query.get_results_async::<(common_enums::DisputeStatus, i64)>(conn), db_metrics::DatabaseOperation::Count, ) .await .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering records by predicate") } }
1,385
1,359
hyperswitch
crates/router/src/types/storage/generic_link.rs
.rs
pub use diesel_models::generic_link::{ GenericLink, GenericLinkData, GenericLinkNew, GenericLinkState, GenericLinkUpdateInternal, PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate, };
45
1,360
hyperswitch
crates/router/src/types/storage/revenue_recovery.rs
.rs
use std::fmt::Debug; use common_utils::id_type; use hyperswitch_domain_models::{business_profile, merchant_account, merchant_key_store}; #[derive(serde::Serialize, serde::Deserialize, Debug)] pub struct PcrWorkflowTrackingData { pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub global_payment_id: id_type::GlobalPaymentId, pub payment_attempt_id: id_type::GlobalAttemptId, } #[derive(Debug, Clone)] pub struct PcrPaymentData { pub merchant_account: merchant_account::MerchantAccount, pub profile: business_profile::Profile, pub key_store: merchant_key_store::MerchantKeyStore, }
147
1,361
hyperswitch
crates/router/src/types/storage/user_authentication_method.rs
.rs
pub use diesel_models::user_authentication_method::*;
9
1,362
hyperswitch
crates/router/src/types/storage/ephemeral_key.rs
.rs
#[cfg(feature = "v2")] pub use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; pub use diesel_models::ephemeral_key::{EphemeralKey, EphemeralKeyNew}; #[cfg(feature = "v2")] use crate::db::errors; #[cfg(feature = "v2")] use crate::types::transformers::ForeignTryFrom; #[cfg(feature = "v2")] impl ForeignTryFrom<ClientSecretType> for api_models::ephemeral_key::ClientSecretResponse { type Error = errors::ApiErrorResponse; fn foreign_try_from(from: ClientSecretType) -> Result<Self, errors::ApiErrorResponse> { match from.resource_id { common_utils::types::authentication::ResourceId::Payment(global_payment_id) => { Err(errors::ApiErrorResponse::InternalServerError) } common_utils::types::authentication::ResourceId::PaymentMethodSession( global_payment_id, ) => Err(errors::ApiErrorResponse::InternalServerError), common_utils::types::authentication::ResourceId::Customer(global_customer_id) => { Ok(Self { resource_id: api_models::ephemeral_key::ResourceId::Customer( global_customer_id.clone(), ), created_at: from.created_at, expires: from.expires, secret: from.secret, id: from.id, }) } } } }
286
1,363
hyperswitch
crates/router/src/types/storage/customers.rs
.rs
pub use diesel_models::customers::{Customer, CustomerNew, CustomerUpdateInternal}; #[cfg(all(feature = "v2", feature = "customer_v2"))] pub use crate::types::domain::CustomerGeneralUpdate; pub use crate::types::domain::CustomerUpdate;
56
1,364
hyperswitch
crates/router/src/types/storage/payout_attempt.rs
.rs
pub use diesel_models::payout_attempt::{ PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal, };
31
1,365
hyperswitch
crates/router/src/types/storage/payment_method.rs
.rs
use api_models::payment_methods; use diesel_models::enums; pub use diesel_models::payment_method::{ PaymentMethod, PaymentMethodNew, PaymentMethodUpdate, PaymentMethodUpdateInternal, TokenizeCoreWorkflow, }; use crate::types::{api, domain}; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum PaymentTokenKind { Temporary, Permanent, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CardTokenData { pub payment_method_id: Option<String>, pub locker_id: Option<String>, pub token: String, pub network_token_locker_id: Option<String>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CardTokenData { pub payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, pub locker_id: Option<String>, pub token: String, } #[derive(Debug, Clone, serde::Serialize, Default, serde::Deserialize)] pub struct PaymentMethodDataWithId { pub payment_method: Option<enums::PaymentMethod>, pub payment_method_data: Option<domain::PaymentMethodData>, pub payment_method_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GenericTokenData { pub token: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct WalletTokenData { pub payment_method_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum PaymentTokenData { // The variants 'Temporary' and 'Permanent' are added for backwards compatibility // with any tokenized data present in Redis at the time of deployment of this change Temporary(GenericTokenData), TemporaryGeneric(GenericTokenData), Permanent(CardTokenData), PermanentCard(CardTokenData), AuthBankDebit(payment_methods::BankAccountTokenData), WalletToken(WalletTokenData), } impl PaymentTokenData { #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub fn permanent_card( payment_method_id: Option<String>, locker_id: Option<String>, token: String, network_token_locker_id: Option<String>, ) -> Self { Self::PermanentCard(CardTokenData { payment_method_id, locker_id, token, network_token_locker_id, }) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn permanent_card( payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, locker_id: Option<String>, token: String, ) -> Self { Self::PermanentCard(CardTokenData { payment_method_id, locker_id, token, }) } pub fn temporary_generic(token: String) -> Self { Self::TemporaryGeneric(GenericTokenData { token }) } pub fn wallet_token(payment_method_id: String) -> Self { Self::WalletToken(WalletTokenData { payment_method_id }) } pub fn is_permanent_card(&self) -> bool { matches!(self, Self::PermanentCard(_) | Self::Permanent(_)) } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodListContext { pub card_details: Option<api::CardDetailFromLocker>, pub hyperswitch_token_data: Option<PaymentTokenData>, #[cfg(feature = "payouts")] pub bank_transfer_details: Option<api::BankPayout>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum PaymentMethodListContext { Card { card_details: api::CardDetailFromLocker, token_data: Option<PaymentTokenData>, }, Bank { token_data: Option<PaymentTokenData>, }, #[cfg(feature = "payouts")] BankTransfer { bank_transfer_details: api::BankPayout, token_data: Option<PaymentTokenData>, }, TemporaryToken { token_data: Option<PaymentTokenData>, }, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl PaymentMethodListContext { pub(crate) fn get_token_data(&self) -> Option<PaymentTokenData> { match self { Self::Card { token_data, .. } | Self::Bank { token_data } | Self::BankTransfer { token_data, .. } | Self::TemporaryToken { token_data } => token_data.clone(), } } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentMethodStatusTrackingData { pub payment_method_id: String, pub prev_status: enums::PaymentMethodStatus, pub curr_status: enums::PaymentMethodStatus, pub merchant_id: common_utils::id_type::MerchantId, }
1,167
1,366
hyperswitch
crates/router/src/types/storage/dashboard_metadata.rs
.rs
pub use diesel_models::user::dashboard_metadata::*;
10
1,367
hyperswitch
crates/router/src/types/storage/fraud_check.rs
.rs
pub use diesel_models::fraud_check::{ FraudCheck, FraudCheckNew, FraudCheckUpdate, FraudCheckUpdateInternal, };
27
1,368
hyperswitch
crates/router/src/types/storage/mandate.rs
.rs
use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::errors::CustomResult; use diesel::{associations::HasTable, ExpressionMethods, QueryDsl}; pub use diesel_models::mandate::{ Mandate, MandateNew, MandateUpdate, MandateUpdateInternal, SingleUseMandate, }; use diesel_models::{errors, schema::mandate::dsl}; use error_stack::ResultExt; use crate::{connection::PgPooledConn, logger}; #[async_trait::async_trait] pub trait MandateDbExt: Sized { async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, mandate_list_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<Self>, errors::DatabaseError>; } #[async_trait::async_trait] impl MandateDbExt for Mandate { async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, mandate_list_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<Self>, errors::DatabaseError> { let mut filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .order(dsl::created_at.desc()) .into_boxed(); if let Some(created_time) = mandate_list_constraints.created_time { filter = filter.filter(dsl::created_at.eq(created_time)); } if let Some(created_time_lt) = mandate_list_constraints.created_time_lt { filter = filter.filter(dsl::created_at.lt(created_time_lt)); } if let Some(created_time_gt) = mandate_list_constraints.created_time_gt { filter = filter.filter(dsl::created_at.gt(created_time_gt)); } if let Some(created_time_lte) = mandate_list_constraints.created_time_lte { filter = filter.filter(dsl::created_at.le(created_time_lte)); } if let Some(created_time_gte) = mandate_list_constraints.created_time_gte { filter = filter.filter(dsl::created_at.ge(created_time_gte)); } if let Some(connector) = mandate_list_constraints.connector { filter = filter.filter(dsl::connector.eq(connector)); } if let Some(mandate_status) = mandate_list_constraints.mandate_status { filter = filter.filter(dsl::mandate_status.eq(mandate_status)); } if let Some(limit) = mandate_list_constraints.limit { filter = filter.limit(limit); } if let Some(offset) = mandate_list_constraints.offset { filter = filter.offset(offset); } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string()); filter .get_results_async(conn) .await // The query built here returns an empty Vec when no records are found, and if any error does occur, // it would be an internal database error, due to which we are raising a DatabaseError::Unknown error .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering mandates by specified constraints") } }
690
1,369
hyperswitch
crates/router/src/types/storage/gsm.rs
.rs
pub use diesel_models::gsm::{ GatewayStatusMap, GatewayStatusMapperUpdateInternal, GatewayStatusMappingNew, GatewayStatusMappingUpdate, };
31
1,370
hyperswitch
crates/router/src/types/storage/merchant_key_store.rs
.rs
pub use diesel_models::merchant_key_store::MerchantKeyStore;
13
1,371
hyperswitch
crates/router/src/types/storage/blocklist_fingerprint.rs
.rs
pub use diesel_models::blocklist_fingerprint::{BlocklistFingerprint, BlocklistFingerprintNew};
21
1,372
hyperswitch
crates/router/src/types/storage/payouts.rs
.rs
pub use diesel_models::payouts::{Payouts, PayoutsNew, PayoutsUpdate, PayoutsUpdateInternal};
29
1,373
hyperswitch
crates/router/src/types/storage/blocklist_lookup.rs
.rs
pub use diesel_models::blocklist_lookup::{BlocklistLookup, BlocklistLookupNew};
18
1,374
hyperswitch
crates/router/src/types/storage/merchant_connector_account.rs
.rs
pub use diesel_models::merchant_connector_account::{ MerchantConnectorAccount, MerchantConnectorAccountNew, MerchantConnectorAccountUpdateInternal, }; pub use crate::types::domain::MerchantConnectorAccountUpdate;
39
1,375
hyperswitch
crates/router/src/types/storage/user_role.rs
.rs
pub use diesel_models::user_role::*;
8
1,376
hyperswitch
crates/router/src/types/storage/events.rs
.rs
pub use diesel_models::events::{Event, EventMetadata, EventNew};
15
1,377
hyperswitch
crates/router/src/types/storage/payment_attempt.rs
.rs
use common_utils::types::MinorUnit; use diesel_models::{capture::CaptureNew, enums}; use error_stack::ResultExt; pub use hyperswitch_domain_models::payments::payment_attempt::{ PaymentAttempt, PaymentAttemptUpdate, }; use crate::{ core::errors, errors::RouterResult, types::transformers::ForeignFrom, utils::OptionExt, }; pub trait PaymentAttemptExt { fn make_new_capture( &self, capture_amount: MinorUnit, capture_status: enums::CaptureStatus, ) -> RouterResult<CaptureNew>; fn get_next_capture_id(&self) -> String; fn get_total_amount(&self) -> MinorUnit; fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails>; } impl PaymentAttemptExt for PaymentAttempt { #[cfg(feature = "v2")] fn make_new_capture( &self, capture_amount: MinorUnit, capture_status: enums::CaptureStatus, ) -> RouterResult<CaptureNew> { todo!() } #[cfg(feature = "v1")] fn make_new_capture( &self, capture_amount: MinorUnit, capture_status: enums::CaptureStatus, ) -> RouterResult<CaptureNew> { let capture_sequence = self.multiple_capture_count.unwrap_or_default() + 1; let now = common_utils::date_time::now(); Ok(CaptureNew { payment_id: self.payment_id.clone(), merchant_id: self.merchant_id.clone(), capture_id: self.get_next_capture_id(), status: capture_status, amount: capture_amount, currency: self.currency, connector: self .connector .clone() .get_required_value("connector") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "connector field is required in payment_attempt to create a capture", )?, error_message: None, tax_amount: None, created_at: now, modified_at: now, error_code: None, error_reason: None, authorized_attempt_id: self.attempt_id.clone(), capture_sequence, connector_capture_id: None, connector_response_reference_id: None, processor_capture_data: None, // Below fields are deprecated. Please add any new fields above this line. connector_capture_data: None, }) } #[cfg(feature = "v1")] fn get_next_capture_id(&self) -> String { let next_sequence_number = self.multiple_capture_count.unwrap_or_default() + 1; format!("{}_{}", self.attempt_id.clone(), next_sequence_number) } #[cfg(feature = "v2")] fn get_next_capture_id(&self) -> String { todo!() } #[cfg(feature = "v1")] fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> { self.net_amount .get_surcharge_amount() .map( |surcharge_amount| api_models::payments::RequestSurchargeDetails { surcharge_amount, tax_amount: self.net_amount.get_tax_on_surcharge(), }, ) } #[cfg(feature = "v2")] fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> { todo!() } #[cfg(feature = "v1")] fn get_total_amount(&self) -> MinorUnit { self.net_amount.get_total_amount() } #[cfg(feature = "v2")] fn get_total_amount(&self) -> MinorUnit { todo!() } } pub trait AttemptStatusExt { fn maps_to_intent_status(self, intent_status: enums::IntentStatus) -> bool; } impl AttemptStatusExt for enums::AttemptStatus { fn maps_to_intent_status(self, intent_status: enums::IntentStatus) -> bool { enums::IntentStatus::foreign_from(self) == intent_status } } #[cfg(test)] #[cfg(all( feature = "v1", // Ignoring tests for v2 since they aren't actively running feature = "dummy_connector" ))] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used, clippy::print_stderr)] use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew; use tokio::sync::oneshot; use uuid::Uuid; use crate::{ configs::settings::Settings, db::StorageImpl, routes, services, types::{self, storage::enums}, }; async fn create_single_connection_test_transaction_pool() -> routes::AppState { // Set pool size to 1 and minimum idle connection size to 0 std::env::set_var("ROUTER__MASTER_DATABASE__POOL_SIZE", "1"); std::env::set_var("ROUTER__MASTER_DATABASE__MIN_IDLE", "0"); std::env::set_var("ROUTER__REPLICA_DATABASE__POOL_SIZE", "1"); std::env::set_var("ROUTER__REPLICA_DATABASE__MIN_IDLE", "0"); let conf = Settings::new().expect("invalid settings"); let tx: oneshot::Sender<()> = oneshot::channel().0; let api_client = Box::new(services::MockApiClient); Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, api_client, )) .await } #[tokio::test] async fn test_payment_attempt_insert() { let state = create_single_connection_test_transaction_pool().await; let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data(); let current_time = common_utils::date_time::now(); let connector = types::Connector::DummyConnector1.to_string(); let payment_attempt = PaymentAttemptNew { payment_id: payment_id.clone(), connector: Some(connector), created_at: current_time.into(), modified_at: current_time.into(), merchant_id: Default::default(), attempt_id: Default::default(), status: Default::default(), net_amount: Default::default(), currency: Default::default(), save_to_locker: Default::default(), error_message: Default::default(), offer_amount: Default::default(), payment_method_id: Default::default(), payment_method: Default::default(), capture_method: Default::default(), capture_on: Default::default(), confirm: Default::default(), authentication_type: Default::default(), last_synced: Default::default(), cancellation_reason: Default::default(), amount_to_capture: Default::default(), mandate_id: Default::default(), browser_info: Default::default(), payment_token: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), payment_experience: Default::default(), payment_method_type: Default::default(), payment_method_data: Default::default(), business_sub_label: Default::default(), straight_through_algorithm: Default::default(), preprocessing_step_id: Default::default(), mandate_details: Default::default(), error_reason: Default::default(), connector_response_reference_id: Default::default(), multiple_capture_count: Default::default(), amount_capturable: Default::default(), updated_by: Default::default(), authentication_data: Default::default(), encoded_data: Default::default(), merchant_connector_id: Default::default(), unified_code: Default::default(), unified_message: Default::default(), external_three_ds_authentication_attempted: Default::default(), authentication_connector: Default::default(), authentication_id: Default::default(), mandate_data: Default::default(), payment_method_billing_address_id: Default::default(), fingerprint_id: Default::default(), client_source: Default::default(), client_version: Default::default(), customer_acceptance: Default::default(), profile_id: common_utils::generate_profile_id_of_default_length(), organization_id: Default::default(), connector_mandate_detail: Default::default(), request_extended_authorization: Default::default(), extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), }; let store = state .stores .get(state.conf.multitenancy.get_tenant_ids().first().unwrap()) .unwrap(); let response = store .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly) .await .unwrap(); eprintln!("{response:?}"); assert_eq!(response.payment_id, payment_id.clone()); } #[tokio::test] /// Example of unit test /// Kind of test: state-based testing async fn test_find_payment_attempt() { let state = create_single_connection_test_transaction_pool().await; let current_time = common_utils::date_time::now(); let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data(); let attempt_id = Uuid::new_v4().to_string(); let merchant_id = common_utils::id_type::MerchantId::new_from_unix_timestamp(); let connector = types::Connector::DummyConnector1.to_string(); let payment_attempt = PaymentAttemptNew { payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), connector: Some(connector), created_at: current_time.into(), modified_at: current_time.into(), attempt_id: attempt_id.clone(), status: Default::default(), net_amount: Default::default(), currency: Default::default(), save_to_locker: Default::default(), error_message: Default::default(), offer_amount: Default::default(), payment_method_id: Default::default(), payment_method: Default::default(), capture_method: Default::default(), capture_on: Default::default(), confirm: Default::default(), authentication_type: Default::default(), last_synced: Default::default(), cancellation_reason: Default::default(), amount_to_capture: Default::default(), mandate_id: Default::default(), browser_info: Default::default(), payment_token: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), payment_experience: Default::default(), payment_method_type: Default::default(), payment_method_data: Default::default(), business_sub_label: Default::default(), straight_through_algorithm: Default::default(), preprocessing_step_id: Default::default(), mandate_details: Default::default(), error_reason: Default::default(), connector_response_reference_id: Default::default(), multiple_capture_count: Default::default(), amount_capturable: Default::default(), updated_by: Default::default(), authentication_data: Default::default(), encoded_data: Default::default(), merchant_connector_id: Default::default(), unified_code: Default::default(), unified_message: Default::default(), external_three_ds_authentication_attempted: Default::default(), authentication_connector: Default::default(), authentication_id: Default::default(), mandate_data: Default::default(), payment_method_billing_address_id: Default::default(), fingerprint_id: Default::default(), client_source: Default::default(), client_version: Default::default(), customer_acceptance: Default::default(), profile_id: common_utils::generate_profile_id_of_default_length(), organization_id: Default::default(), connector_mandate_detail: Default::default(), request_extended_authorization: Default::default(), extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), }; let store = state .stores .get(state.conf.multitenancy.get_tenant_ids().first().unwrap()) .unwrap(); store .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly) .await .unwrap(); let response = store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_id, &merchant_id, &attempt_id, enums::MerchantStorageScheme::PostgresOnly, ) .await .unwrap(); eprintln!("{response:?}"); assert_eq!(response.payment_id, payment_id); } #[tokio::test] /// Example of unit test /// Kind of test: state-based testing async fn test_payment_attempt_mandate_field() { let state = create_single_connection_test_transaction_pool().await; let uuid = Uuid::new_v4().to_string(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant1")) .unwrap(); let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data(); let current_time = common_utils::date_time::now(); let connector = types::Connector::DummyConnector1.to_string(); let payment_attempt = PaymentAttemptNew { payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), connector: Some(connector), created_at: current_time.into(), modified_at: current_time.into(), mandate_id: Some("man_121212".to_string()), attempt_id: uuid.clone(), status: Default::default(), net_amount: Default::default(), currency: Default::default(), save_to_locker: Default::default(), error_message: Default::default(), offer_amount: Default::default(), payment_method_id: Default::default(), payment_method: Default::default(), capture_method: Default::default(), capture_on: Default::default(), confirm: Default::default(), authentication_type: Default::default(), last_synced: Default::default(), cancellation_reason: Default::default(), amount_to_capture: Default::default(), browser_info: Default::default(), payment_token: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), payment_experience: Default::default(), payment_method_type: Default::default(), payment_method_data: Default::default(), business_sub_label: Default::default(), straight_through_algorithm: Default::default(), preprocessing_step_id: Default::default(), mandate_details: Default::default(), error_reason: Default::default(), connector_response_reference_id: Default::default(), multiple_capture_count: Default::default(), amount_capturable: Default::default(), updated_by: Default::default(), authentication_data: Default::default(), encoded_data: Default::default(), merchant_connector_id: Default::default(), unified_code: Default::default(), unified_message: Default::default(), external_three_ds_authentication_attempted: Default::default(), authentication_connector: Default::default(), authentication_id: Default::default(), mandate_data: Default::default(), payment_method_billing_address_id: Default::default(), fingerprint_id: Default::default(), client_source: Default::default(), client_version: Default::default(), customer_acceptance: Default::default(), profile_id: common_utils::generate_profile_id_of_default_length(), organization_id: Default::default(), connector_mandate_detail: Default::default(), request_extended_authorization: Default::default(), extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), }; let store = state .stores .get(state.conf.multitenancy.get_tenant_ids().first().unwrap()) .unwrap(); store .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly) .await .unwrap(); let response = store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_id, &merchant_id, &uuid, enums::MerchantStorageScheme::PostgresOnly, ) .await .unwrap(); // checking it after fetch assert_eq!(response.mandate_id, Some("man_121212".to_string())); } }
3,458
1,378
hyperswitch
crates/router/src/types/storage/reverse_lookup.rs
.rs
pub use diesel_models::reverse_lookup::{ReverseLookup, ReverseLookupNew};
15
1,379
hyperswitch
crates/router/src/types/storage/configs.rs
.rs
pub use diesel_models::configs::{Config, ConfigNew, ConfigUpdate, ConfigUpdateInternal};
19
1,380
hyperswitch
crates/router/src/types/storage/business_profile.rs
.rs
pub use diesel_models::business_profile::{Profile, ProfileNew, ProfileUpdateInternal};
17
1,381
hyperswitch
crates/router/src/types/storage/blocklist.rs
.rs
pub use diesel_models::blocklist::{Blocklist, BlocklistNew};
15
1,382
hyperswitch
crates/router/src/types/storage/cards_info.rs
.rs
pub use diesel_models::cards_info::{CardInfo, UpdateCardInfo};
15
1,383
hyperswitch
crates/router/src/types/storage/role.rs
.rs
pub use diesel_models::role::*;
7
1,384
hyperswitch
crates/router/src/types/api/payment_link.rs
.rs
pub use api_models::payments::RetrievePaymentLinkResponse; use crate::{ consts::DEFAULT_SESSION_EXPIRY, core::{errors::RouterResult, payment_link}, types::storage::{self}, }; #[async_trait::async_trait] pub(crate) trait PaymentLinkResponseExt: Sized { async fn from_db_payment_link(payment_link: storage::PaymentLink) -> RouterResult<Self>; } #[async_trait::async_trait] impl PaymentLinkResponseExt for RetrievePaymentLinkResponse { async fn from_db_payment_link(payment_link: storage::PaymentLink) -> RouterResult<Self> { let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| { payment_link .created_at .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY)) }); let status = payment_link::check_payment_link_status(session_expiry); Ok(Self { link_to_pay: payment_link.link_to_pay, payment_link_id: payment_link.payment_link_id, amount: payment_link.amount, description: payment_link.description, created_at: payment_link.created_at, merchant_id: payment_link.merchant_id, expiry: payment_link.fulfilment_time, currency: payment_link.currency, status, secure_link: payment_link.secure_link, }) } }
273
1,385
hyperswitch
crates/router/src/types/api/payments_v2.rs
.rs
pub use hyperswitch_interfaces::api::payments_v2::{ ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2, };
125
1,386
hyperswitch
crates/router/src/types/api/enums.rs
.rs
pub use api_models::enums::*;
7
1,387
hyperswitch
crates/router/src/types/api/disputes.rs
.rs
pub use hyperswitch_interfaces::{ api::disputes::{AcceptDispute, DefendDispute, Dispute, SubmitEvidence}, disputes::DisputePayload, }; use masking::{Deserialize, Serialize}; use crate::types; #[derive(Default, Debug, Deserialize, Serialize)] pub struct DisputeId { pub dispute_id: String, } pub use hyperswitch_domain_models::router_flow_types::dispute::{Accept, Defend, Evidence}; pub use super::disputes_v2::{AcceptDisputeV2, DefendDisputeV2, DisputeV2, SubmitEvidenceV2}; #[derive(Default, Debug, Deserialize, Serialize)] pub struct DisputeEvidence { pub cancellation_policy: Option<String>, pub customer_communication: Option<String>, pub customer_signature: Option<String>, pub receipt: Option<String>, pub refund_policy: Option<String>, pub service_documentation: Option<String>, pub shipping_documentation: Option<String>, pub invoice_showing_distinct_transactions: Option<String>, pub recurring_transaction_agreement: Option<String>, pub uncategorized_file: Option<String>, } #[derive(Debug, Clone, Serialize)] pub struct AttachEvidenceRequest { pub create_file_request: types::api::CreateFileRequest, pub evidence_type: EvidenceType, } #[derive(Debug, serde::Deserialize, strum::Display, strum::EnumString, Clone, serde::Serialize)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EvidenceType { CancellationPolicy, CustomerCommunication, CustomerSignature, Receipt, RefundPolicy, ServiceDocumentation, ShippingDocumentation, InvoiceShowingDistinctTransactions, RecurringTransactionAgreement, UncategorizedFile, }
366
1,388
hyperswitch
crates/router/src/types/api/bank_accounts.rs
.rs
0
1,389
hyperswitch
crates/router/src/types/api/authentication.rs
.rs
use std::str::FromStr; use api_models::enums; use common_utils::errors::CustomResult; use error_stack::ResultExt; pub use hyperswitch_domain_models::{ router_flow_types::authentication::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, router_request_types::authentication::MessageCategory, }; use crate::{ connector, core::errors, services::connector_integration_interface::ConnectorEnum, types::storage, }; #[derive(Clone, serde::Deserialize, Debug, serde::Serialize)] pub struct AcquirerDetails { pub acquirer_bin: String, pub acquirer_merchant_mid: String, pub acquirer_country_code: Option<String>, } #[derive(Clone, serde::Deserialize, Debug, serde::Serialize)] pub struct AuthenticationResponse { pub trans_status: common_enums::TransactionStatus, pub acs_url: Option<url::Url>, pub challenge_request: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub three_dsserver_trans_id: Option<String>, pub acs_signed_content: Option<String>, } impl TryFrom<storage::Authentication> for AuthenticationResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(authentication: storage::Authentication) -> Result<Self, Self::Error> { let trans_status = authentication.trans_status.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("trans_status must be populated in authentication table authentication call is successful")?; let acs_url = authentication .acs_url .map(|url| url::Url::from_str(&url)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("not a valid URL")?; Ok(Self { trans_status, acs_url, challenge_request: authentication.challenge_request, acs_reference_number: authentication.acs_reference_number, acs_trans_id: authentication.acs_trans_id, three_dsserver_trans_id: authentication.threeds_server_transaction_id, acs_signed_content: authentication.acs_signed_content, }) } } #[derive(Clone, serde::Deserialize, Debug, serde::Serialize)] pub struct PostAuthenticationResponse { pub trans_status: String, pub authentication_value: Option<String>, pub eci: Option<String>, } #[derive(Clone)] pub struct AuthenticationConnectorData { pub connector: ConnectorEnum, pub connector_name: enums::AuthenticationConnectors, } impl AuthenticationConnectorData { pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> { let connector_name = enums::AuthenticationConnectors::from_str(name) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) .attach_printable_lazy(|| format!("unable to parse connector: {name}"))?; let connector = Self::convert_connector(connector_name)?; Ok(Self { connector, connector_name, }) } fn convert_connector( connector_name: enums::AuthenticationConnectors, ) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> { match connector_name { enums::AuthenticationConnectors::Threedsecureio => { Ok(ConnectorEnum::Old(Box::new(&connector::Threedsecureio))) } enums::AuthenticationConnectors::Netcetera => { Ok(ConnectorEnum::Old(Box::new(&connector::Netcetera))) } enums::AuthenticationConnectors::Gpayments => { Ok(ConnectorEnum::Old(Box::new(connector::Gpayments::new()))) } enums::AuthenticationConnectors::CtpMastercard => { Ok(ConnectorEnum::Old(Box::new(&connector::CtpMastercard))) } enums::AuthenticationConnectors::CtpVisa => Ok(ConnectorEnum::Old(Box::new( connector::UnifiedAuthenticationService::new(), ))), enums::AuthenticationConnectors::UnifiedAuthenticationService => Ok( ConnectorEnum::Old(Box::new(connector::UnifiedAuthenticationService::new())), ), enums::AuthenticationConnectors::Juspaythreedsserver => Ok(ConnectorEnum::Old( Box::new(connector::Juspaythreedsserver::new()), )), } } }
907
1,390
hyperswitch
crates/router/src/types/api/connector_onboarding.rs
.rs
pub mod paypal;
4
1,391
hyperswitch
crates/router/src/types/api/authentication_v2.rs
.rs
pub use hyperswitch_domain_models::router_request_types::authentication::MessageCategory; pub use hyperswitch_interfaces::api::authentication_v2::ExternalAuthenticationV2;
33
1,392
hyperswitch
crates/router/src/types/api/api_keys.rs
.rs
pub use api_models::api_keys::{ ApiKeyExpiration, CreateApiKeyRequest, CreateApiKeyResponse, ListApiKeyConstraints, RetrieveApiKeyResponse, RevokeApiKeyResponse, UpdateApiKeyRequest, };
40
1,393
hyperswitch
crates/router/src/types/api/verify_connector.rs
.rs
pub mod paypal; pub mod stripe; use error_stack::ResultExt; use crate::{ consts, core::errors, services::{ self, connector_integration_interface::{BoxedConnectorIntegrationInterface, ConnectorEnum}, }, types::{self, api, api::ConnectorCommon, domain, storage::enums as storage_enums}, SessionState, }; #[derive(Clone)] pub struct VerifyConnectorData { pub connector: ConnectorEnum, pub connector_auth: types::ConnectorAuthType, pub card_details: domain::Card, } impl VerifyConnectorData { fn get_payment_authorize_data(&self) -> types::PaymentsAuthorizeData { types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(self.card_details.clone()), email: None, customer_name: None, amount: 1000, minor_amount: common_utils::types::MinorUnit::new(1000), confirm: true, order_tax_amount: None, currency: storage_enums::Currency::USD, metadata: None, mandate_id: None, webhook_url: None, customer_id: None, off_session: None, browser_info: None, session_token: None, order_details: None, order_category: None, capture_method: None, enrolled_for_3ds: false, router_return_url: None, surcharge_details: None, setup_future_usage: None, payment_experience: None, payment_method_type: None, statement_descriptor: None, setup_mandate_details: None, complete_authorize_url: None, related_transaction_id: None, statement_descriptor_suffix: None, request_extended_authorization: None, request_incremental_authorization: false, authentication_data: None, customer_acceptance: None, split_payments: None, merchant_order_reference_id: None, integrity_object: None, additional_payment_method_data: None, shipping_cost: None, merchant_account_id: None, merchant_config_currency: None, } } fn get_router_data<F, R1, R2>( &self, state: &SessionState, request_data: R1, access_token: Option<types::AccessToken>, ) -> types::RouterData<F, R1, R2> { let attempt_id = common_utils::generate_id_with_default_len(consts::VERIFY_CONNECTOR_ID_PREFIX); types::RouterData { flow: std::marker::PhantomData, status: storage_enums::AttemptStatus::Started, request: request_data, response: Err(errors::ApiErrorResponse::InternalServerError.into()), connector: self.connector.id().to_string(), auth_type: storage_enums::AuthenticationType::NoThreeDs, test_mode: None, attempt_id: attempt_id.clone(), description: None, customer_id: None, tenant_id: state.tenant.tenant_id.clone(), merchant_id: common_utils::id_type::MerchantId::default(), reference_id: None, access_token, session_token: None, payment_method: storage_enums::PaymentMethod::Card, amount_captured: None, minor_amount_captured: None, preprocessing_id: None, connector_customer: None, connector_auth_type: self.connector_auth.clone(), connector_meta_data: None, connector_wallets_details: None, payment_method_token: None, connector_api_version: None, recurring_mandate_payment_data: None, payment_method_status: None, connector_request_reference_id: attempt_id, address: types::PaymentAddress::new(None, None, None, None), payment_id: common_utils::id_type::PaymentId::default() .get_string_repr() .to_owned(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, payment_method_balance: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, } } } #[async_trait::async_trait] pub trait VerifyConnector { async fn verify( state: &SessionState, connector_data: VerifyConnectorData, ) -> errors::RouterResponse<()> { let authorize_data = connector_data.get_payment_authorize_data(); let access_token = Self::get_access_token(state, connector_data.clone()).await?; let router_data = connector_data.get_router_data(state, authorize_data, access_token); let request = connector_data .connector .get_connector_integration() .build_request(&router_data, &state.conf.connectors) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Payment request cannot be built".to_string(), })? .ok_or(errors::ApiErrorResponse::InternalServerError)?; let response = services::call_connector_api(&state.to_owned(), request, "verify_connector_request") .await .change_context(errors::ApiErrorResponse::InternalServerError)?; match response { Ok(_) => Ok(services::ApplicationResponse::StatusOk), Err(error_response) => { Self::handle_payment_error_response::< api::Authorize, types::PaymentFlowData, types::PaymentsAuthorizeData, types::PaymentsResponseData, >( connector_data.connector.get_connector_integration(), error_response, ) .await } } } async fn get_access_token( _state: &SessionState, _connector_data: VerifyConnectorData, ) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> { // AccessToken is None for the connectors without the AccessToken Flow. // If a connector has that, then it should override this implementation. Ok(None) } async fn handle_payment_error_response<F, ResourceCommonData, Req, Resp>( // connector: &(dyn api::Connector + Sync), connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>, error_response: types::Response, ) -> errors::RouterResponse<()> { let error = connector .get_error_response(error_response, None) .change_context(errors::ApiErrorResponse::InternalServerError)?; Err(errors::ApiErrorResponse::InvalidRequestData { message: error.reason.unwrap_or(error.message), } .into()) } async fn handle_access_token_error_response<F, ResourceCommonData, Req, Resp>( connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>, error_response: types::Response, ) -> errors::RouterResult<Option<types::AccessToken>> { let error = connector .get_error_response(error_response, None) .change_context(errors::ApiErrorResponse::InternalServerError)?; Err(errors::ApiErrorResponse::InvalidRequestData { message: error.reason.unwrap_or(error.message), } .into()) } }
1,547
1,394
hyperswitch
crates/router/src/types/api/payments.rs
.rs
#[cfg(feature = "v1")] pub use api_models::payments::{ PaymentListFilterConstraints, PaymentListResponse, PaymentListResponseV2, }; #[cfg(feature = "v2")] pub use api_models::payments::{ PaymentsConfirmIntentRequest, PaymentsCreateIntentRequest, PaymentsIntentResponse, PaymentsUpdateIntentRequest, }; pub use api_models::{ feature_matrix::{ ConnectorFeatureMatrixResponse, FeatureMatrixListResponse, FeatureMatrixRequest, }, payments::{ AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, Card, CryptoData, CustomerAcceptance, CustomerDetails, CustomerDetailsResponse, MandateAmountData, MandateData, MandateTransactionType, MandateType, MandateValidationFields, NextActionType, OnlineMandate, OpenBankingSessionToken, PayLaterData, PaymentIdType, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2, PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsAggregateResponse, PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse, PaymentsExternalAuthenticationRequest, PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest, PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, UrlDetails, VerifyRequest, VerifyResponse, WalletData, }, }; use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, PaymentCreateIntent, PaymentGetIntent, PaymentMethodToken, PaymentUpdateIntent, PostProcessing, PostSessionTokens, PreProcessing, RecordAttempt, Reject, SdkSessionUpdate, Session, SetupMandate, Void, }; pub use hyperswitch_interfaces::api::payments::{ ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize, PaymentAuthorizeSessionToken, PaymentCapture, PaymentIncrementalAuthorization, PaymentPostSessionTokens, PaymentReject, PaymentSession, PaymentSessionUpdate, PaymentSync, PaymentToken, PaymentVoid, PaymentsCompleteAuthorize, PaymentsPostProcessing, PaymentsPreProcessing, TaxCalculation, }; pub use super::payments_v2::{ ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2, }; use crate::core::errors; pub trait PaymentIdTypeExt { #[cfg(feature = "v1")] fn get_payment_intent_id( &self, ) -> errors::CustomResult<common_utils::id_type::PaymentId, errors::ValidationError>; #[cfg(feature = "v2")] fn get_payment_intent_id( &self, ) -> errors::CustomResult<common_utils::id_type::GlobalPaymentId, errors::ValidationError>; } impl PaymentIdTypeExt for PaymentIdType { #[cfg(feature = "v1")] fn get_payment_intent_id( &self, ) -> errors::CustomResult<common_utils::id_type::PaymentId, errors::ValidationError> { match self { Self::PaymentIntentId(id) => Ok(id.clone()), Self::ConnectorTransactionId(_) | Self::PaymentAttemptId(_) | Self::PreprocessingId(_) => Err(errors::ValidationError::IncorrectValueProvided { field_name: "payment_id", }) .attach_printable("Expected payment intent ID but got connector transaction ID"), } } #[cfg(feature = "v2")] fn get_payment_intent_id( &self, ) -> errors::CustomResult<common_utils::id_type::GlobalPaymentId, errors::ValidationError> { match self { Self::PaymentIntentId(id) => Ok(id.clone()), Self::ConnectorTransactionId(_) | Self::PaymentAttemptId(_) | Self::PreprocessingId(_) => Err(errors::ValidationError::IncorrectValueProvided { field_name: "payment_id", }) .attach_printable("Expected payment intent ID but got connector transaction ID"), } } } pub(crate) trait MandateValidationFieldsExt { fn validate_and_get_mandate_type( &self, ) -> errors::CustomResult<Option<MandateTransactionType>, errors::ValidationError>; } impl MandateValidationFieldsExt for MandateValidationFields { fn validate_and_get_mandate_type( &self, ) -> errors::CustomResult<Option<MandateTransactionType>, errors::ValidationError> { match (&self.mandate_data, &self.recurring_details) { (None, None) => Ok(None), (Some(_), Some(_)) => Err(errors::ValidationError::InvalidValue { message: "Expected one out of recurring_details and mandate_data but got both" .to_string(), } .into()), (_, Some(_)) => Ok(Some(MandateTransactionType::RecurringMandateTransaction)), (Some(_), _) => Ok(Some(MandateTransactionType::NewMandateTransaction)), } } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_test { #![allow(clippy::expect_used, clippy::unwrap_used)] use super::*; #[allow(dead_code)] fn card() -> Card { Card { card_number: "1234432112344321".to_string().try_into().unwrap(), card_exp_month: "12".to_string().into(), card_exp_year: "99".to_string().into(), card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())), card_cvc: "123".to_string().into(), card_issuer: Some("HDFC".to_string()), card_network: Some(api_models::enums::CardNetwork::Visa), bank_code: None, card_issuing_country: None, card_type: None, nick_name: Some(masking::Secret::new("nick_name".into())), } } #[allow(dead_code)] fn payments_request() -> PaymentsRequest { PaymentsRequest { amount: Some(Amount::from(common_utils::types::MinorUnit::new(200))), payment_method_data: Some(PaymentMethodDataRequest { payment_method_data: Some(PaymentMethodData::Card(card())), billing: None, }), ..PaymentsRequest::default() } } //#[test] // FIXME: Fix test #[allow(dead_code)] fn verify_payments_request() { let pay_req = payments_request(); let serialized = serde_json::to_string(&pay_req).expect("error serializing payments request"); let _deserialized_pay_req: PaymentsRequest = serde_json::from_str(&serialized).expect("error de-serializing payments response"); //assert_eq!(pay_req, deserialized_pay_req) } // Intended to test the serialization and deserialization of the enum PaymentIdType #[test] fn test_connector_id_type() { let sample_1 = PaymentIdType::PaymentIntentId( common_utils::id_type::PaymentId::try_from(std::borrow::Cow::Borrowed( "test_234565430uolsjdnf48i0", )) .unwrap(), ); let s_sample_1 = serde_json::to_string(&sample_1).unwrap(); let ds_sample_1 = serde_json::from_str::<PaymentIdType>(&s_sample_1).unwrap(); assert_eq!(ds_sample_1, sample_1) } }
1,800
1,395
hyperswitch
crates/router/src/types/api/webhooks.rs
.rs
pub use api_models::webhooks::{ AuthenticationIdType, IncomingWebhookDetails, IncomingWebhookEvent, MerchantWebhookConfig, ObjectReferenceId, OutgoingWebhook, OutgoingWebhookContent, WebhookFlow, }; pub use hyperswitch_interfaces::webhooks::{IncomingWebhook, IncomingWebhookRequestDetails};
68
1,396
hyperswitch
crates/router/src/types/api/mandates.rs
.rs
use api_models::mandates; pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse}; use common_utils::ext_traits::OptionExt; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payment_methods, }, newtype, routes::SessionState, types::{ api, domain, storage::{self, enums as storage_enums}, }, }; newtype!( pub MandateCardDetails = mandates::MandateCardDetails, derives = (Default, Debug, Deserialize, Serialize) ); #[async_trait::async_trait] pub(crate) trait MandateResponseExt: Sized { async fn from_db_mandate( state: &SessionState, key_store: domain::MerchantKeyStore, mandate: storage::Mandate, storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<Self>; } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[async_trait::async_trait] impl MandateResponseExt for MandateResponse { async fn from_db_mandate( state: &SessionState, key_store: domain::MerchantKeyStore, mandate: storage::Mandate, storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<Self> { let db = &*state.store; let payment_method = db .find_payment_method( &(state.into()), &key_store, &mandate.payment_method_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let pm = payment_method .get_payment_method_type() .get_required_value("payment_method") .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("payment_method not found")?; let card = if pm == storage_enums::PaymentMethod::Card { // if locker is disabled , decrypt the payment method data let card_details = if state.conf.locker.locker_enabled { let card = payment_methods::cards::get_card_from_locker( state, &payment_method.customer_id, &payment_method.merchant_id, payment_method .locker_id .as_ref() .unwrap_or(payment_method.get_id()), ) .await?; payment_methods::transformers::get_card_detail(&payment_method, card) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting card details")? } else { payment_methods::cards::get_card_details_without_locker_fallback( &payment_method, state, ) .await? }; Some(MandateCardDetails::from(card_details).into_inner()) } else { None }; let payment_method_type = payment_method .get_payment_method_subtype() .map(|pmt| pmt.to_string()); Ok(Self { mandate_id: mandate.mandate_id, customer_acceptance: Some(api::payments::CustomerAcceptance { acceptance_type: if mandate.customer_ip_address.is_some() { api::payments::AcceptanceType::Online } else { api::payments::AcceptanceType::Offline }, accepted_at: mandate.customer_accepted_at, online: Some(api::payments::OnlineMandate { ip_address: mandate.customer_ip_address, user_agent: mandate.customer_user_agent.unwrap_or_default(), }), }), card, status: mandate.mandate_status, payment_method: pm.to_string(), payment_method_type, payment_method_id: mandate.payment_method_id, }) } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[async_trait::async_trait] impl MandateResponseExt for MandateResponse { async fn from_db_mandate( state: &SessionState, key_store: domain::MerchantKeyStore, mandate: storage::Mandate, storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<Self> { todo!() } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails { fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self { mandates::MandateCardDetails { last4_digits: card_details_from_locker.last4_digits, card_exp_month: card_details_from_locker.expiry_month.clone(), card_exp_year: card_details_from_locker.expiry_year.clone(), card_holder_name: card_details_from_locker.card_holder_name, card_token: card_details_from_locker.card_token, scheme: card_details_from_locker.scheme, issuer_country: card_details_from_locker.issuer_country, card_fingerprint: card_details_from_locker.card_fingerprint, card_isin: card_details_from_locker.card_isin, card_issuer: card_details_from_locker.card_issuer, card_network: card_details_from_locker.card_network, card_type: card_details_from_locker.card_type, nick_name: card_details_from_locker.nick_name, } .into() } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails { fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self { mandates::MandateCardDetails { last4_digits: card_details_from_locker.last4_digits, card_exp_month: card_details_from_locker.expiry_month.clone(), card_exp_year: card_details_from_locker.expiry_year.clone(), card_holder_name: card_details_from_locker.card_holder_name, card_token: None, scheme: None, issuer_country: card_details_from_locker .issuer_country .map(|country| country.to_string()), card_fingerprint: card_details_from_locker.card_fingerprint, card_isin: card_details_from_locker.card_isin, card_issuer: card_details_from_locker.card_issuer, card_network: card_details_from_locker.card_network, card_type: card_details_from_locker .card_type .as_ref() .map(|c| c.to_string()), nick_name: card_details_from_locker.nick_name, } .into() } }
1,439
1,397
hyperswitch
crates/router/src/types/api/routing.rs
.rs
pub use api_models::{ enums as api_enums, routing::{ ConnectorVolumeSplit, RoutableChoiceKind, RoutableConnectorChoice, RoutingAlgorithm, RoutingAlgorithmKind, RoutingAlgorithmRef, RoutingConfigRequest, RoutingDictionary, RoutingDictionaryRecord, StraightThroughAlgorithm, }, }; use super::types::api as api_oss; pub struct SessionRoutingChoice { pub connector: api_oss::ConnectorData, pub payment_method_type: api_enums::PaymentMethodType, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ConnectorVolumeSplitV0 { pub connector: RoutableConnectorChoice, pub split: u8, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RoutingAlgorithmV0 { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplitV0>), Custom { timestamp: i64 }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct FrmRoutingAlgorithm { pub data: String, #[serde(rename = "type")] pub algorithm_type: String, }
267
1,398
hyperswitch
crates/router/src/types/api/payouts_v2.rs
.rs
pub use api_models::payouts::{ AchBankTransfer, BacsBankTransfer, Bank as BankPayout, CardPayout, PayoutActionRequest, PayoutAttemptResponse, PayoutCreateRequest, PayoutCreateResponse, PayoutListConstraints, PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, PayoutMethodData, PayoutRequest, PayoutRetrieveBody, PayoutRetrieveRequest, PixBankTransfer, SepaBankTransfer, Wallet as WalletPayout, }; pub use hyperswitch_domain_models::router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }; pub use hyperswitch_interfaces::api::payouts_v2::{ PayoutCancelV2, PayoutCreateV2, PayoutEligibilityV2, PayoutFulfillV2, PayoutQuoteV2, PayoutRecipientAccountV2, PayoutRecipientV2, PayoutSyncV2, }; use crate::types::api as api_types; pub trait PayoutsV2: api_types::ConnectorCommon + PayoutCancelV2 + PayoutCreateV2 + PayoutEligibilityV2 + PayoutFulfillV2 + PayoutQuoteV2 + PayoutRecipientV2 + PayoutSyncV2 + PayoutRecipientAccountV2 { }
318
1,399
hyperswitch
crates/router/src/types/api/cards.rs
.rs
0
1,400
hyperswitch
crates/router/src/types/api/files_v2.rs
.rs
pub use hyperswitch_domain_models::router_flow_types::files::{Retrieve, Upload}; pub use hyperswitch_interfaces::api::files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2};
44
1,401
hyperswitch
crates/router/src/types/api/disputes_v2.rs
.rs
pub use hyperswitch_interfaces::api::disputes_v2::{ AcceptDisputeV2, DefendDisputeV2, DisputeV2, SubmitEvidenceV2, };
39
1,402
hyperswitch
crates/router/src/types/api/ephemeral_key.rs
.rs
pub use api_models::ephemeral_key::*;
10
1,403
hyperswitch
crates/router/src/types/api/customers.rs
.rs
use api_models::customers; pub use api_models::customers::{ CustomerDeleteResponse, CustomerListRequest, CustomerRequest, CustomerUpdateRequest, CustomerUpdateRequestInternal, }; #[cfg(all(feature = "v2", feature = "customer_v2"))] use hyperswitch_domain_models::customer; use serde::Serialize; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use super::payments; use crate::{ newtype, types::{domain, ForeignFrom}, }; newtype!( pub CustomerResponse = customers::CustomerResponse, derives = (Debug, Clone, Serialize) ); impl common_utils::events::ApiEventMetric for CustomerResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { self.0.get_api_event_type() } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl ForeignFrom<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResponse { fn foreign_from((cust, address): (domain::Customer, Option<payments::AddressDetails>)) -> Self { customers::CustomerResponse { customer_id: cust.customer_id, name: cust.name, email: cust.email, phone: cust.phone, phone_country_code: cust.phone_country_code, description: cust.description, created_at: cust.created_at, metadata: cust.metadata, address, default_payment_method_id: cust.default_payment_method_id, } .into() } } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl ForeignFrom<customer::Customer> for CustomerResponse { fn foreign_from(cust: domain::Customer) -> Self { customers::CustomerResponse { id: cust.id, merchant_reference_id: cust.merchant_reference_id, connector_customer_ids: cust.connector_customer, name: cust.name, email: cust.email, phone: cust.phone, phone_country_code: cust.phone_country_code, description: cust.description, created_at: cust.created_at, metadata: cust.metadata, default_billing_address: None, default_shipping_address: None, default_payment_method_id: cust.default_payment_method_id, } .into() } }
499
1,404