repo
stringclasses
1 value
instance_id
stringlengths
22
24
problem_statement
stringlengths
30
24.1k
patch
stringlengths
0
1.9M
test_patch
stringclasses
1 value
created_at
stringdate
2022-11-25 05:12:07
2025-06-13 10:24:29
hints_text
stringlengths
0
234k
base_commit
stringlengths
40
40
test_instructions
stringlengths
0
232k
filenames
listlengths
0
300
juspay/hyperswitch
juspay__hyperswitch-6642
Bug: refactor(tenant): use tenant id type Refactor: Use tenant_id type instead of string for better type safety
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index 3d57a72376e..a8085564145 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -12,6 +12,7 @@ mod payment; mod profile; mod refunds; mod routing; +mod tenant; #[cfg(feature = "v2")] mod global_id; @@ -40,6 +41,7 @@ pub use profile::ProfileId; pub use refunds::RefundReferenceId; pub use routing::RoutingId; use serde::{Deserialize, Serialize}; +pub use tenant::TenantId; use thiserror::Error; use crate::{fp_utils::when, generate_id_with_default_len}; diff --git a/crates/common_utils/src/id_type/organization.rs b/crates/common_utils/src/id_type/organization.rs index a83f35db1d8..2097fbb2450 100644 --- a/crates/common_utils/src/id_type/organization.rs +++ b/crates/common_utils/src/id_type/organization.rs @@ -18,7 +18,7 @@ crate::impl_to_sql_from_sql_id_type!(OrganizationId); impl OrganizationId { /// Get an organization id from String - pub fn wrap(org_id: String) -> CustomResult<Self, ValidationError> { + pub fn try_from_string(org_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(org_id)) } } diff --git a/crates/common_utils/src/id_type/tenant.rs b/crates/common_utils/src/id_type/tenant.rs new file mode 100644 index 00000000000..953bf82287a --- /dev/null +++ b/crates/common_utils/src/id_type/tenant.rs @@ -0,0 +1,22 @@ +use crate::errors::{CustomResult, ValidationError}; + +crate::id_type!( + TenantId, + "A type for tenant_id that can be used for unique identifier for a tenant" +); +crate::impl_id_type_methods!(TenantId, "tenant_id"); + +// This is to display the `TenantId` as TenantId(abcd) +crate::impl_debug_id_type!(TenantId); +crate::impl_try_from_cow_str_id_type!(TenantId, "tenant_id"); + +crate::impl_serializable_secret_id_type!(TenantId); +crate::impl_queryable_id_type!(TenantId); +crate::impl_to_sql_from_sql_id_type!(TenantId); + +impl TenantId { + /// Get tenant id from String + pub fn try_from_string(tenant_id: String) -> CustomResult<Self, ValidationError> { + Self::try_from(std::borrow::Cow::from(tenant_id)) + } +} diff --git a/crates/common_utils/src/types/theme.rs b/crates/common_utils/src/types/theme.rs index 03b4cf23a6c..9ad9206acce 100644 --- a/crates/common_utils/src/types/theme.rs +++ b/crates/common_utils/src/types/theme.rs @@ -12,15 +12,15 @@ pub enum ThemeLineage { // }, /// Org lineage variant Organization { - /// tenant_id: String - tenant_id: String, + /// tenant_id: TenantId + tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, }, /// Merchant lineage variant Merchant { - /// tenant_id: String - tenant_id: String, + /// tenant_id: TenantId + tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_id: MerchantId @@ -28,8 +28,8 @@ pub enum ThemeLineage { }, /// Profile lineage variant Profile { - /// tenant_id: String - tenant_id: String, + /// tenant_id: TenantId + tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_id: MerchantId diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rs index 2f8152e419c..9841e21443c 100644 --- a/crates/diesel_models/src/user/theme.rs +++ b/crates/diesel_models/src/user/theme.rs @@ -9,7 +9,7 @@ use crate::schema::themes; #[diesel(table_name = themes, primary_key(theme_id), check_for_backend(diesel::pg::Pg))] pub struct Theme { pub theme_id: String, - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub org_id: Option<id_type::OrganizationId>, pub merchant_id: Option<id_type::MerchantId>, pub profile_id: Option<id_type::ProfileId>, @@ -23,7 +23,7 @@ pub struct Theme { #[diesel(table_name = themes)] pub struct ThemeNew { pub theme_id: String, - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub org_id: Option<id_type::OrganizationId>, pub merchant_id: Option<id_type::MerchantId>, pub profile_id: Option<id_type::ProfileId>, diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs index ceddbfd61e4..04f3264b45e 100644 --- a/crates/diesel_models/src/user_role.rs +++ b/crates/diesel_models/src/user_role.rs @@ -24,7 +24,7 @@ pub struct UserRole { pub entity_id: Option<String>, pub entity_type: Option<EntityType>, pub version: enums::UserRoleVersion, - pub tenant_id: String, + pub tenant_id: id_type::TenantId, } impl UserRole { @@ -88,7 +88,7 @@ pub struct UserRoleNew { pub entity_id: Option<String>, pub entity_type: Option<EntityType>, pub version: enums::UserRoleVersion, - pub tenant_id: String, + pub tenant_id: id_type::TenantId, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] diff --git a/crates/drainer/src/handler.rs b/crates/drainer/src/handler.rs index d8a8bff5afc..d0c26195453 100644 --- a/crates/drainer/src/handler.rs +++ b/crates/drainer/src/handler.rs @@ -3,6 +3,7 @@ use std::{ sync::{atomic, Arc}, }; +use common_utils::id_type; use router_env::tracing::Instrument; use tokio::{ sync::{mpsc, oneshot}, @@ -34,12 +35,15 @@ pub struct HandlerInner { loop_interval: Duration, active_tasks: Arc<atomic::AtomicU64>, conf: DrainerSettings, - stores: HashMap<String, Arc<Store>>, + stores: HashMap<id_type::TenantId, Arc<Store>>, running: Arc<atomic::AtomicBool>, } impl Handler { - pub fn from_conf(conf: DrainerSettings, stores: HashMap<String, Arc<Store>>) -> Self { + pub fn from_conf( + conf: DrainerSettings, + stores: HashMap<id_type::TenantId, Arc<Store>>, + ) -> Self { let shutdown_interval = Duration::from_millis(conf.shutdown_interval.into()); let loop_interval = Duration::from_millis(conf.loop_interval.into()); diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs index 48d5f311905..2ca2c1cc79c 100644 --- a/crates/drainer/src/health_check.rs +++ b/crates/drainer/src/health_check.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, sync::Arc}; use actix_web::{web, Scope}; use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, id_type}; use diesel_models::{Config, ConfigNew}; use error_stack::ResultExt; use router_env::{instrument, logger, tracing}; @@ -20,7 +20,7 @@ pub const TEST_STREAM_DATA: &[(&str, &str)] = &[("data", "sample_data")]; pub struct Health; impl Health { - pub fn server(conf: Settings, stores: HashMap<String, Arc<Store>>) -> Scope { + pub fn server(conf: Settings, stores: HashMap<id_type::TenantId, Arc<Store>>) -> Scope { web::scope("health") .app_data(web::Data::new(conf)) .app_data(web::Data::new(stores)) diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs index 5b67640663c..6eb8c505e15 100644 --- a/crates/drainer/src/lib.rs +++ b/crates/drainer/src/lib.rs @@ -14,7 +14,7 @@ use std::{collections::HashMap, sync::Arc}; mod secrets_transformers; use actix_web::dev::Server; -use common_utils::signals::get_allowed_signals; +use common_utils::{id_type, signals::get_allowed_signals}; use diesel_models::kv; use error_stack::ResultExt; use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret; @@ -31,7 +31,7 @@ use crate::{ }; pub async fn start_drainer( - stores: HashMap<String, Arc<Store>>, + stores: HashMap<id_type::TenantId, Arc<Store>>, conf: DrainerSettings, ) -> errors::DrainerResult<()> { let drainer_handler = handler::Handler::from_conf(conf, stores); @@ -62,7 +62,7 @@ pub async fn start_drainer( pub async fn start_web_server( conf: Settings, - stores: HashMap<String, Arc<Store>>, + stores: HashMap<id_type::TenantId, Arc<Store>>, ) -> Result<Server, errors::DrainerError> { let server = conf.server.clone(); let web_server = actix_web::HttpServer::new(move || { diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index 5b391b492e0..9b6c88b3466 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -1,6 +1,6 @@ use std::{collections::HashMap, path::PathBuf, sync::Arc}; -use common_utils::{ext_traits::ConfigExt, DbConnectionParams}; +use common_utils::{ext_traits::ConfigExt, id_type, DbConnectionParams}; use config::{Environment, File}; use external_services::managers::{ encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig, @@ -122,23 +122,23 @@ pub struct Multitenancy { pub tenants: TenantConfig, } impl Multitenancy { - pub fn get_tenants(&self) -> &HashMap<String, Tenant> { + pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> { &self.tenants.0 } - pub fn get_tenant_ids(&self) -> Vec<String> { + pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> { self.tenants .0 .values() .map(|tenant| tenant.tenant_id.clone()) .collect() } - pub fn get_tenant(&self, tenant_id: &str) -> Option<&Tenant> { + pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> { self.tenants.0.get(tenant_id) } } #[derive(Debug, Clone, Default)] -pub struct TenantConfig(pub HashMap<String, Tenant>); +pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>); impl<'de> Deserialize<'de> for TenantConfig { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { @@ -150,7 +150,7 @@ impl<'de> Deserialize<'de> for TenantConfig { clickhouse_database: String, } - let hashmap = <HashMap<String, Inner>>::deserialize(deserializer)?; + let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?; Ok(Self( hashmap @@ -172,9 +172,9 @@ impl<'de> Deserialize<'de> for TenantConfig { } } -#[derive(Debug, Deserialize, Clone, Default)] +#[derive(Debug, Deserialize, Clone)] pub struct Tenant { - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub base_url: String, pub schema: String, pub redis_key_prefix: String, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 76b58f5b67b..7b212ec6d1d 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -6,7 +6,7 @@ use std::{ #[cfg(feature = "olap")] use analytics::{opensearch::OpenSearchConfig, ReportConfig}; use api_models::{enums, payment_methods::RequiredFieldInfo}; -use common_utils::ext_traits::ConfigExt; +use common_utils::{ext_traits::ConfigExt, id_type}; use config::{Environment, File}; use error_stack::ResultExt; #[cfg(feature = "email")] @@ -138,17 +138,17 @@ pub struct Multitenancy { } impl Multitenancy { - pub fn get_tenants(&self) -> &HashMap<String, Tenant> { + pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> { &self.tenants.0 } - pub fn get_tenant_ids(&self) -> Vec<String> { + pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> { self.tenants .0 .values() .map(|tenant| tenant.tenant_id.clone()) .collect() } - pub fn get_tenant(&self, tenant_id: &str) -> Option<&Tenant> { + pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> { self.tenants.0.get(tenant_id) } } @@ -159,11 +159,11 @@ pub struct DecisionConfig { } #[derive(Debug, Clone, Default)] -pub struct TenantConfig(pub HashMap<String, Tenant>); +pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>); -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub struct Tenant { - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub base_url: String, pub schema: String, pub redis_key_prefix: String, @@ -743,8 +743,7 @@ pub struct LockerBasedRecipientConnectorList { #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorRequestReferenceIdConfig { - pub merchant_ids_send_payment_id_as_connector_request_id: - HashSet<common_utils::id_type::MerchantId>, + pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<id_type::MerchantId>, } #[derive(Debug, Deserialize, Clone, Default)] @@ -970,7 +969,7 @@ pub struct ServerTls { #[cfg(feature = "v2")] #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] pub struct CellInformation { - pub id: common_utils::id_type::CellId, + pub id: id_type::CellId, } #[cfg(feature = "v2")] @@ -981,8 +980,8 @@ impl Default for CellInformation { // around the time of deserializing application settings. // And a panic at application startup is considered acceptable. #[allow(clippy::expect_used)] - let cell_id = common_utils::id_type::CellId::from_string("defid") - .expect("Failed to create a default for Cell Id"); + let cell_id = + id_type::CellId::from_string("defid").expect("Failed to create a default for Cell Id"); Self { id: cell_id } } } @@ -1120,7 +1119,7 @@ impl<'de> Deserialize<'de> for TenantConfig { clickhouse_database: String, } - let hashmap = <HashMap<String, Inner>>::deserialize(deserializer)?; + let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?; Ok(Self( hashmap diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index c0f54a30f3f..c3fbfd8afbf 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -389,7 +389,7 @@ pub async fn mk_add_locker_request_hs( locker: &settings::Locker, payload: &StoreLockerReq, locker_choice: api_enums::LockerChoice, - tenant_id: String, + tenant_id: id_type::TenantId, request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let payload = payload @@ -409,7 +409,10 @@ pub async fn mk_add_locker_request_hs( url.push_str("/cards/add"); let mut request = services::Request::new(services::Method::Post, &url); request.add_header(headers::CONTENT_TYPE, "application/json".into()); - request.add_header(headers::X_TENANT_ID, tenant_id.into()); + request.add_header( + headers::X_TENANT_ID, + tenant_id.get_string_repr().to_owned().into(), + ); if let Some(req_id) = request_id { request.add_header( headers::X_REQUEST_ID, @@ -584,7 +587,7 @@ pub async fn mk_get_card_request_hs( merchant_id: &id_type::MerchantId, card_reference: &str, locker_choice: Option<api_enums::LockerChoice>, - tenant_id: String, + tenant_id: id_type::TenantId, request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let merchant_customer_id = customer_id.to_owned(); @@ -612,7 +615,10 @@ pub async fn mk_get_card_request_hs( url.push_str("/cards/retrieve"); let mut request = services::Request::new(services::Method::Post, &url); request.add_header(headers::CONTENT_TYPE, "application/json".into()); - request.add_header(headers::X_TENANT_ID, tenant_id.into()); + request.add_header( + headers::X_TENANT_ID, + tenant_id.get_string_repr().to_owned().into(), + ); if let Some(req_id) = request_id { request.add_header( headers::X_REQUEST_ID, @@ -665,7 +671,7 @@ pub async fn mk_delete_card_request_hs( customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &str, - tenant_id: String, + tenant_id: id_type::TenantId, request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let merchant_customer_id = customer_id.to_owned(); @@ -691,7 +697,10 @@ pub async fn mk_delete_card_request_hs( url.push_str("/cards/delete"); let mut request = services::Request::new(services::Method::Post, &url); request.add_header(headers::CONTENT_TYPE, "application/json".into()); - request.add_header(headers::X_TENANT_ID, tenant_id.into()); + request.add_header( + headers::X_TENANT_ID, + tenant_id.get_string_repr().to_owned().into(), + ); if let Some(req_id) = request_id { request.add_header( headers::X_REQUEST_ID, @@ -711,7 +720,7 @@ pub async fn mk_delete_card_request_hs_by_id( id: &String, merchant_id: &id_type::MerchantId, card_reference: &str, - tenant_id: String, + tenant_id: id_type::TenantId, request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let merchant_customer_id = id.to_owned(); @@ -737,7 +746,10 @@ pub async fn mk_delete_card_request_hs_by_id( url.push_str("/cards/delete"); let mut request = services::Request::new(services::Method::Post, &url); request.add_header(headers::CONTENT_TYPE, "application/json".into()); - request.add_header(headers::X_TENANT_ID, tenant_id.into()); + request.add_header( + headers::X_TENANT_ID, + tenant_id.get_string_repr().to_owned().into(), + ); if let Some(req_id) = request_id { request.add_header( headers::X_REQUEST_ID, @@ -832,7 +844,7 @@ pub fn mk_crud_locker_request( locker: &settings::Locker, path: &str, req: api::TokenizePayloadEncrypted, - tenant_id: String, + tenant_id: id_type::TenantId, request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let mut url = locker.basilisk_host.to_owned(); @@ -840,7 +852,10 @@ pub fn mk_crud_locker_request( let mut request = services::Request::new(services::Method::Post, &url); request.add_default_headers(); request.add_header(headers::CONTENT_TYPE, "application/json".into()); - request.add_header(headers::X_TENANT_ID, tenant_id.into()); + request.add_header( + headers::X_TENANT_ID, + tenant_id.get_string_repr().to_owned().into(), + ); if let Some(req_id) = request_id { request.add_header( headers::X_REQUEST_ID, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index aef89ea8ed9..264328796c8 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -751,7 +751,10 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( &metrics::CONTEXT, 1, &add_attributes([ - ("tenant", state.tenant.tenant_id.clone()), + ( + "tenant", + state.tenant.tenant_id.get_string_repr().to_owned(), + ), ( "merchant_profile_id", format!( diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index bff6205f5db..78f5682fd7f 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1105,11 +1105,15 @@ pub async fn create_internal_user( } })?; - let default_tenant_id = common_utils::consts::DEFAULT_TENANT.to_string(); + let default_tenant_id = common_utils::id_type::TenantId::try_from_string( + common_utils::consts::DEFAULT_TENANT.to_owned(), + ) + .change_context(UserErrors::InternalServerError) + .attach_printable("Unable to parse default tenant id")?; if state.tenant.tenant_id != default_tenant_id { return Err(UserErrors::ForbiddenTenantId) - .attach_printable("Operation allowed only for the default tenant."); + .attach_printable("Operation allowed only for the default tenant"); } let internal_merchant_id = common_utils::id_type::MerchantId::get_internal_user_merchant_id( diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index 651c2ece610..6bb7de1b7d9 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -732,7 +732,10 @@ mod tests { )) .await; let state = &Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1")) diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index be2c25d4767..687f6e8fea2 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1502,8 +1502,12 @@ mod merchant_connector_account_cache_tests { Box::new(services::MockApiClient), )) .await; + let state = &Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) @@ -1685,7 +1689,10 @@ mod merchant_connector_account_cache_tests { )) .await; let state = &Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs index 65a5515a391..9f12ec8e8fd 100644 --- a/crates/router/src/db/merchant_key_store.rs +++ b/crates/router/src/db/merchant_key_store.rs @@ -348,7 +348,10 @@ mod tests { )) .await; let state = &Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); #[allow(clippy::expect_used)] let mock_db = MockDb::new(&redis_interface::RedisSettings::default()) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index baa2ba4ae15..1584cfae2b9 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -7,6 +7,7 @@ use api_models::routing::RoutingRetrieveQuery; use common_enums::TransactionType; #[cfg(feature = "partial-auth")] use common_utils::crypto::Blake3; +use common_utils::id_type; #[cfg(feature = "email")] use external_services::email::{ no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService, @@ -193,14 +194,14 @@ impl SessionStateInfo for SessionState { pub struct AppState { pub flow_name: String, pub global_store: Box<dyn GlobalStorageInterface>, - pub stores: HashMap<String, Box<dyn StorageInterface>>, + pub stores: HashMap<id_type::TenantId, Box<dyn StorageInterface>>, pub conf: Arc<settings::Settings<RawSecret>>, pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<Box<dyn EmailService>>, pub api_client: Box<dyn crate::services::ApiClient>, #[cfg(feature = "olap")] - pub pools: HashMap<String, AnalyticsProvider>, + pub pools: HashMap<id_type::TenantId, AnalyticsProvider>, #[cfg(feature = "olap")] pub opensearch_client: Arc<OpenSearchClient>, pub request_id: Option<RequestId>, @@ -209,7 +210,7 @@ pub struct AppState { pub grpc_client: Arc<GrpcClients>, } impl scheduler::SchedulerAppState for AppState { - fn get_tenants(&self) -> Vec<String> { + fn get_tenants(&self) -> Vec<id_type::TenantId> { self.conf.multitenancy.get_tenant_ids() } } @@ -328,7 +329,7 @@ impl AppState { ); #[cfg(feature = "olap")] - let mut pools: HashMap<String, AnalyticsProvider> = HashMap::new(); + let mut pools: HashMap<id_type::TenantId, AnalyticsProvider> = HashMap::new(); let mut stores = HashMap::new(); #[allow(clippy::expect_used)] let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable) @@ -443,7 +444,11 @@ impl AppState { .await } - pub fn get_session_state<E, F>(self: Arc<Self>, tenant: &str, err: F) -> Result<SessionState, E> + pub fn get_session_state<E, F>( + self: Arc<Self>, + tenant: &id_type::TenantId, + err: F, + ) -> Result<SessionState, E> where F: FnOnce() -> E + Copy, { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index bdd650389a7..9416ff175a8 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -68,7 +68,7 @@ use crate::{ api_logs::{ApiEvent, ApiEventMetric, ApiEventsType}, connector_api_logs::ConnectorEvent, }, - logger, + headers, logger, routes::{ app::{AppStateInfo, ReqState, SessionStateInfo}, metrics, AppState, SessionState, @@ -722,33 +722,44 @@ where let mut event_type = payload.get_api_event_type(); let tenant_id = if !state.conf.multitenancy.enabled { - DEFAULT_TENANT.to_string() + common_utils::id_type::TenantId::try_from_string(DEFAULT_TENANT.to_owned()) + .attach_printable("Unable to get default tenant id") + .change_context(errors::ApiErrorResponse::InternalServerError.switch())? } else { let request_tenant_id = incoming_request_header .get(TENANT_HEADER) .and_then(|value| value.to_str().ok()) - .ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch())?; + .ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch()) + .and_then(|header_value| { + common_utils::id_type::TenantId::try_from_string(header_value.to_string()).map_err( + |_| { + errors::ApiErrorResponse::InvalidRequestData { + message: format!("`{}` header is invalid", headers::X_TENANT_ID), + } + .switch() + }, + ) + })?; state .conf .multitenancy - .get_tenant(request_tenant_id) + .get_tenant(&request_tenant_id) .map(|tenant| tenant.tenant_id.clone()) .ok_or( errors::ApiErrorResponse::InvalidTenant { - tenant_id: request_tenant_id.to_string(), + tenant_id: request_tenant_id.get_string_repr().to_string(), } .switch(), )? }; - let mut session_state = - Arc::new(app_state.clone()).get_session_state(tenant_id.as_str(), || { - errors::ApiErrorResponse::InvalidTenant { - tenant_id: tenant_id.clone(), - } - .switch() - })?; + let mut session_state = Arc::new(app_state.clone()).get_session_state(&tenant_id, || { + errors::ApiErrorResponse::InvalidTenant { + tenant_id: tenant_id.get_string_repr().to_string(), + } + .switch() + })?; session_state.add_request_id(request_id); let mut request_state = session_state.get_req_state(); @@ -757,9 +768,10 @@ where .event_context .record_info(("flow".to_string(), flow.to_string())); - request_state - .event_context - .record_info(("tenant_id".to_string(), tenant_id.to_string())); + request_state.event_context.record_info(( + "tenant_id".to_string(), + tenant_id.get_string_repr().to_string(), + )); // Currently auth failures are not recorded as API events let (auth_out, auth_type) = api_auth diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 2541a5dc7d4..2f5f55b8434 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -185,7 +185,7 @@ pub struct UserFromSinglePurposeToken { pub user_id: String, pub origin: domain::Origin, pub path: Vec<TokenPurpose>, - pub tenant_id: Option<String>, + pub tenant_id: Option<id_type::TenantId>, } #[cfg(feature = "olap")] @@ -196,7 +196,7 @@ pub struct SinglePurposeToken { pub origin: domain::Origin, pub path: Vec<TokenPurpose>, pub exp: u64, - pub tenant_id: Option<String>, + pub tenant_id: Option<id_type::TenantId>, } #[cfg(feature = "olap")] @@ -207,7 +207,7 @@ impl SinglePurposeToken { origin: domain::Origin, settings: &Settings, path: Vec<TokenPurpose>, - tenant_id: Option<String>, + tenant_id: Option<id_type::TenantId>, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::SINGLE_PURPOSE_TOKEN_TIME_IN_SECS); @@ -232,7 +232,7 @@ pub struct AuthToken { pub exp: u64, pub org_id: id_type::OrganizationId, pub profile_id: id_type::ProfileId, - pub tenant_id: Option<String>, + pub tenant_id: Option<id_type::TenantId>, } #[cfg(feature = "olap")] @@ -244,7 +244,7 @@ impl AuthToken { settings: &Settings, org_id: id_type::OrganizationId, profile_id: id_type::ProfileId, - tenant_id: Option<String>, + tenant_id: Option<id_type::TenantId>, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(exp_duration)?.as_secs(); @@ -268,7 +268,7 @@ pub struct UserFromToken { pub role_id: String, pub org_id: id_type::OrganizationId, pub profile_id: id_type::ProfileId, - pub tenant_id: Option<String>, + pub tenant_id: Option<id_type::TenantId>, } pub struct UserIdFromAuth { @@ -282,7 +282,7 @@ pub struct SinglePurposeOrLoginToken { pub role_id: Option<String>, pub purpose: Option<TokenPurpose>, pub exp: u64, - pub tenant_id: Option<String>, + pub tenant_id: Option<id_type::TenantId>, } pub trait AuthInfo { @@ -1110,7 +1110,7 @@ impl<'a> HeaderMapStruct<'a> { self.get_mandatory_header_value_by_key(headers::X_ORGANIZATION_ID) .map(|val| val.to_owned()) .and_then(|organization_id| { - id_type::OrganizationId::wrap(organization_id).change_context( + id_type::OrganizationId::try_from_string(organization_id).change_context( errors::ApiErrorResponse::InvalidRequestData { message: format!("`{}` header is invalid", headers::X_ORGANIZATION_ID), }, diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index 35a0b159ab2..87ff9f6abd5 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -112,12 +112,16 @@ pub fn check_permission( ) } -pub fn check_tenant(token_tenant_id: Option<String>, header_tenant_id: &str) -> RouterResult<()> { +pub fn check_tenant( + token_tenant_id: Option<id_type::TenantId>, + header_tenant_id: &id_type::TenantId, +) -> RouterResult<()> { if let Some(tenant_id) = token_tenant_id { - if tenant_id != header_tenant_id { + if tenant_id != *header_tenant_id { return Err(ApiErrorResponse::InvalidJwtToken).attach_printable(format!( "Token tenant ID: '{}' does not match Header tenant ID: '{}'", - tenant_id, header_tenant_id + tenant_id.get_string_repr().to_owned(), + header_tenant_id.get_string_repr().to_owned() )); } } diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 4cb69e68ed8..6d0d2a4ea07 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -1106,20 +1106,20 @@ pub struct NoLevel; #[derive(Clone)] pub struct OrganizationLevel { - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, } #[derive(Clone)] pub struct MerchantLevel { - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, pub merchant_id: id_type::MerchantId, } #[derive(Clone)] pub struct ProfileLevel { - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, @@ -1156,7 +1156,7 @@ impl NewUserRole<NoLevel> { } pub struct EntityInfo { - tenant_id: String, + tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 8a9daefb287..f115a16c062 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -92,7 +92,7 @@ pub async fn generate_jwt_auth_token_with_attributes( org_id: id_type::OrganizationId, role_id: String, profile_id: id_type::ProfileId, - tenant_id: Option<String>, + tenant_id: Option<id_type::TenantId>, ) -> UserResult<Secret<String>> { let token = AuthToken::new_token( user_id, diff --git a/crates/router/tests/cache.rs b/crates/router/tests/cache.rs index 8c3f34cd1e1..55b92b4aace 100644 --- a/crates/router/tests/cache.rs +++ b/crates/router/tests/cache.rs @@ -18,7 +18,10 @@ async fn invalidate_existing_cache_success() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let cache_key = "cacheKey".to_string(); let cache_key_value = "val".to_string(); diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 6f4855d1e22..9dfd331b72a 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -216,7 +216,10 @@ async fn payments_create_success() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); use router::connector::Aci; @@ -263,7 +266,10 @@ async fn payments_create_failure() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let connector = utils::construct_connector_data_old( Box::new(Aci::new()), @@ -326,7 +332,10 @@ async fn refund_for_successful_payments() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< types::api::Authorize, @@ -396,7 +405,10 @@ async fn refunds_create_failure() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let connector_integration: services::BoxedRefundConnectorIntegrationInterface< types::api::Execute, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 52218b211ac..383b4db358c 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -599,7 +599,10 @@ pub trait ConnectorActions: Connector { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, @@ -639,7 +642,10 @@ pub trait ConnectorActions: Connector { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, @@ -680,7 +686,10 @@ pub trait ConnectorActions: Connector { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, @@ -720,7 +729,10 @@ pub trait ConnectorActions: Connector { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, @@ -811,7 +823,10 @@ pub trait ConnectorActions: Connector { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, @@ -848,7 +863,10 @@ async fn call_connector< )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); services::api::execute_connector_processing_step( &state, diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index df4340a353e..68ca08c8bd3 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -295,7 +295,10 @@ async fn payments_create_core() { let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap(); let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let key_manager_state = &(&state).into(); let key_store = state @@ -552,7 +555,10 @@ async fn payments_create_core_adyen_no_redirect() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let payment_id = diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index b5962d454fa..90fe3a1f847 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -56,7 +56,10 @@ async fn payments_create_core() { let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap(); let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let key_manager_state = &(&state).into(); let key_store = state @@ -321,7 +324,10 @@ async fn payments_create_core_adyen_no_redirect() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let customer_id = format!("cust_{}", Uuid::new_v4()); diff --git a/crates/router/tests/services.rs b/crates/router/tests/services.rs index d907000cccd..c014370b24f 100644 --- a/crates/router/tests/services.rs +++ b/crates/router/tests/services.rs @@ -18,7 +18,10 @@ async fn get_redis_conn_failure() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let _ = state.store.get_redis_conn().map(|conn| { @@ -46,7 +49,10 @@ async fn get_redis_conn_success() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); // Act diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rs index 5791edd31b0..846f1137b12 100644 --- a/crates/scheduler/src/consumer.rs +++ b/crates/scheduler/src/consumer.rs @@ -7,7 +7,7 @@ use std::{ pub mod types; pub mod workflows; -use common_utils::{errors::CustomResult, signals::get_allowed_signals}; +use common_utils::{errors::CustomResult, id_type, signals::get_allowed_signals}; use diesel_models::enums; pub use diesel_models::{self, process_tracker as storage}; use error_stack::ResultExt; @@ -42,7 +42,7 @@ pub async fn start_consumer<T: SchedulerAppState + 'static, U: SchedulerSessionS app_state_to_session_state: F, ) -> CustomResult<(), errors::ProcessTrackerError> where - F: Fn(&T, &str) -> CustomResult<U, errors::ProcessTrackerError>, + F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>, { use std::time::Duration; @@ -88,7 +88,7 @@ where let start_time = std_time::Instant::now(); let tenants = state.get_tenants(); for tenant in tenants { - let session_state = app_state_to_session_state(state, tenant.as_str())?; + let session_state = app_state_to_session_state(state, &tenant)?; pt_utils::consumer_operation_handler( session_state.clone(), settings.clone(), diff --git a/crates/scheduler/src/producer.rs b/crates/scheduler/src/producer.rs index 6f710f55a34..b91434fcbb0 100644 --- a/crates/scheduler/src/producer.rs +++ b/crates/scheduler/src/producer.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, id_type}; use diesel_models::enums::ProcessTrackerStatus; use error_stack::{report, ResultExt}; use router_env::{ @@ -27,7 +27,7 @@ pub async fn start_producer<T, U, F>( app_state_to_session_state: F, ) -> CustomResult<(), errors::ProcessTrackerError> where - F: Fn(&T, &str) -> CustomResult<U, errors::ProcessTrackerError>, + F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>, T: SchedulerAppState, U: SchedulerSessionState, { @@ -69,7 +69,7 @@ where interval.tick().await; let tenants = state.get_tenants(); for tenant in tenants { - let session_state = app_state_to_session_state(state, tenant.as_str())?; + let session_state = app_state_to_session_state(state, &tenant)?; match run_producer_flow(&session_state, &scheduler_settings).await { Ok(_) => (), Err(error) => { diff --git a/crates/scheduler/src/scheduler.rs b/crates/scheduler/src/scheduler.rs index 39a45d02ba9..2685c6311ea 100644 --- a/crates/scheduler/src/scheduler.rs +++ b/crates/scheduler/src/scheduler.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, id_type}; use storage_impl::mock_db::MockDb; #[cfg(feature = "kv_store")] use storage_impl::KVRouterStore; @@ -52,7 +52,7 @@ impl SchedulerInterface for MockDb {} #[async_trait::async_trait] pub trait SchedulerAppState: Send + Sync + Clone { - fn get_tenants(&self) -> Vec<String>; + fn get_tenants(&self) -> Vec<id_type::TenantId>; } #[async_trait::async_trait] pub trait SchedulerSessionState: Send + Sync + Clone { @@ -71,7 +71,7 @@ pub async fn start_process_tracker< app_state_to_session_state: F, ) -> CustomResult<(), errors::ProcessTrackerError> where - F: Fn(&T, &str) -> CustomResult<U, errors::ProcessTrackerError>, + F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>, { match scheduler_flow { SchedulerFlow::Producer => {
2024-11-22T12:01:12Z
## Description Use tenant_id type for better type safety ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#6642](https://github.com/juspay/hyperswitch/issues/6642) ## How did you test it? It refactoring PR, its compiling and checks are passing Tested flows like signup/signin with tenancy featue flag enabled and disabled in local
8d0639ea6f22227253a44e6bd8272d9e55d17f92
It refactoring PR, its compiling and checks are passing Tested flows like signup/signin with tenancy featue flag enabled and disabled in local
[ "crates/common_utils/src/id_type.rs", "crates/common_utils/src/id_type/organization.rs", "crates/common_utils/src/id_type/tenant.rs", "crates/common_utils/src/types/theme.rs", "crates/diesel_models/src/user/theme.rs", "crates/diesel_models/src/user_role.rs", "crates/drainer/src/handler.rs", "crates/drainer/src/health_check.rs", "crates/drainer/src/lib.rs", "crates/drainer/src/settings.rs", "crates/router/src/configs/settings.rs", "crates/router/src/core/payment_methods/transformers.rs", "crates/router/src/core/routing/helpers.rs", "crates/router/src/core/user.rs", "crates/router/src/db/events.rs", "crates/router/src/db/merchant_connector_account.rs", "crates/router/src/db/merchant_key_store.rs", "crates/router/src/routes/app.rs", "crates/router/src/services/api.rs", "crates/router/src/services/authentication.rs", "crates/router/src/services/authorization.rs", "crates/router/src/types/domain/user.rs", "crates/router/src/utils/user.rs", "crates/router/tests/cache.rs", "crates/router/tests/connectors/aci.rs", "crates/router/tests/connectors/utils.rs", "crates/router/tests/payments.rs", "crates/router/tests/payments2.rs", "crates/router/tests/services.rs", "crates/scheduler/src/consumer.rs", "crates/scheduler/src/producer.rs", "crates/scheduler/src/scheduler.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6638
Bug: feat(users): Send welcome to community email in magic link signup Send [this](https://www.figma.com/design/lhmTvW2vuc2p5B4ZvsEOTw/Email-Tempalte-Design?node-id=0-1&t=OKWmXqVOsidKUk7y-1) email when user signs up with magic link.
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index aa427992082..32ca4ad31d7 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -41,3 +41,5 @@ pub const EMAIL_SUBJECT_INVITATION: &str = "You have been invited to join Hypers pub const EMAIL_SUBJECT_MAGIC_LINK: &str = "Unlock Hyperswitch: Use Your Magic Link to Sign In"; pub const EMAIL_SUBJECT_RESET_PASSWORD: &str = "Get back to Hyperswitch - Reset Your Password Now"; pub const EMAIL_SUBJECT_NEW_PROD_INTENT: &str = "New Prod Intent"; +pub const EMAIL_SUBJECT_WELCOME_TO_COMMUNITY: &str = + "Thank you for signing up on Hyperswitch Dashboard!"; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index bff6205f5db..eedd9ac5672 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -246,26 +246,41 @@ pub async fn connect_account( ) .await?; - let email_contents = email_types::VerifyEmail { + let magic_link_email = email_types::VerifyEmail { recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), subject: consts::user::EMAIL_SUBJECT_SIGNUP, auth_id, }; - let send_email_result = state + let magic_link_result = state .email_client .compose_and_send_email( - Box::new(email_contents), + Box::new(magic_link_email), state.conf.proxy.https_url.as_ref(), ) .await; - logger::info!(?send_email_result); + logger::info!(?magic_link_result); + + let welcome_to_community_email = email_types::WelcomeToCommunity { + recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, + subject: consts::user::EMAIL_SUBJECT_WELCOME_TO_COMMUNITY, + }; + + let welcome_email_result = state + .email_client + .compose_and_send_email( + Box::new(welcome_to_community_email), + state.conf.proxy.https_url.as_ref(), + ) + .await; + + logger::info!(?welcome_email_result); return Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { - is_email_sent: send_email_result.is_ok(), + is_email_sent: magic_link_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), }, )); diff --git a/crates/router/src/services/email/assets/welcome_to_community.html b/crates/router/src/services/email/assets/welcome_to_community.html new file mode 100644 index 00000000000..05f7fac1d55 --- /dev/null +++ b/crates/router/src/services/email/assets/welcome_to_community.html @@ -0,0 +1,306 @@ +<!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> diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index cedd17828f1..d092afdc5de 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -57,6 +57,7 @@ pub enum EmailBody { api_key_name: String, prefix: String, }, + WelcomeToCommunity, } pub mod html { @@ -145,6 +146,9 @@ Email : {user_email} prefix = prefix, expires_in = expires_in, ), + EmailBody::WelcomeToCommunity => { + include_str!("assets/welcome_to_community.html").to_string() + } } } } @@ -505,3 +509,21 @@ impl EmailData for ApiKeyExpiryReminder { }) } } + +pub struct WelcomeToCommunity { + pub recipient_email: domain::UserEmail, + pub subject: &'static str, +} + +#[async_trait::async_trait] +impl EmailData for WelcomeToCommunity { + async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + let body = html::get_html_body(EmailBody::WelcomeToCommunity); + + Ok(EmailContents { + subject: self.subject.to_string(), + body: external_services::email::IntermediateString::new(body), + recipient: self.recipient_email.clone().into_inner(), + }) + } +}
2024-11-22T08:42:00Z
## Description <!-- Describe your changes in detail --> Magic link will send one more email along with magic link email if user is signing up. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6638. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Local SES ![image](https://github.com/user-attachments/assets/f4e15419-31c7-452e-ba77-4a8815944ca0) ``` curl --location 'http://localhost:8080/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "new user email" }' ``` The above email should be sent.
83e8bc0775c20e9d055e65bd13a2e8b1148092e1
Local SES ![image](https://github.com/user-attachments/assets/f4e15419-31c7-452e-ba77-4a8815944ca0) ``` curl --location 'http://localhost:8080/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "new user email" }' ``` The above email should be sent.
[ "crates/router/src/consts/user.rs", "crates/router/src/core/user.rs", "crates/router/src/services/email/assets/welcome_to_community.html", "crates/router/src/services/email/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6633
Bug: [FEATURE] [AIRWALLEX] Update production endpoint ### Feature Description Update production endpoint for connector Airwallex (https://api.airwallex.com/) ### Possible Implementation Update production endpoint for connector Airwallex (https://api.airwallex.com/) ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 76f42085f92..ebd9e49d86b 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -28,7 +28,7 @@ adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpaymen adyen.payout_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/" adyen.dispute_base_url = "https://{{merchant_endpoint_prefix}}-ca-live.adyen.com/" adyenplatform.base_url = "https://balanceplatform-api-live.adyen.com/" -airwallex.base_url = "https://api-demo.airwallex.com/" +airwallex.base_url = "https://api.airwallex.com/" amazonpay.base_url = "https://pay-api.amazon.com/v2" applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://api.authorize.net/xml/v1/request.api"
2024-11-21T12:24:28Z
## Description <!-- Describe your changes in detail --> Update production endpoint for connector Airwallex (https://api.airwallex.com/) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/6633 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Only config changes hence no testing required
f24578310f44adf75c993ba42225554377399961
Only config changes hence no testing required
[ "config/deployments/production.toml" ]
juspay/hyperswitch
juspay__hyperswitch-6629
Bug: fix: merchant order ref id filter and refund_id filter - Add merchant_order reference id filter for payments list - Fix refunds list filter, search by refund id. (It is construction a totally new filter ignoring the merchant id when searching)
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 98bc7b754a4..a5fc687ef28 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4923,6 +4923,8 @@ pub struct PaymentListFilterConstraints { pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, + /// The identifier for merchant order reference id + pub merchant_order_reference_id: Option<String>, } impl PaymentListFilterConstraints { diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 4f2053ec6f9..e706c4ae45a 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1002,6 +1002,7 @@ pub struct PaymentIntentListParams { pub limit: Option<u32>, pub order: api_models::payments::Order, pub card_network: Option<Vec<storage_enums::CardNetwork>>, + pub merchant_order_reference_id: Option<String>, } impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchConstraints { @@ -1036,6 +1037,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)), order: Default::default(), card_network: None, + merchant_order_reference_id: None, })) } } @@ -1061,6 +1063,7 @@ impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints { limit: None, order: Default::default(), card_network: None, + merchant_order_reference_id: None, })) } } @@ -1084,6 +1087,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF merchant_connector_id, order, card_network, + merchant_order_reference_id, } = value; if let Some(payment_intent_id) = payment_id { Self::Single { payment_intent_id } @@ -1107,6 +1111,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V2)), order, card_network, + merchant_order_reference_id, })) } } diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs index 2d42aaa0a8a..cf1ff52960f 100644 --- a/crates/router/src/types/storage/dispute.rs +++ b/crates/router/src/types/storage/dispute.rs @@ -1,6 +1,6 @@ use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::errors::CustomResult; -use diesel::{associations::HasTable, ExpressionMethods, QueryDsl}; +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; @@ -43,9 +43,11 @@ impl DisputeDbExt for Dispute { &dispute_list_constraints.dispute_id, ) { search_by_payment_or_dispute_id = true; - filter = filter - .filter(dsl::payment_id.eq(payment_id.to_owned())) - .or_filter(dsl::dispute_id.eq(dispute_id.to_owned())); + 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 { diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs index 8076c2c7a6e..e46fc1a3f47 100644 --- a/crates/router/src/types/storage/refund.rs +++ b/crates/router/src/types/storage/refund.rs @@ -1,7 +1,7 @@ use api_models::payments::AmountFilter; use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::errors::CustomResult; -use diesel::{associations::HasTable, ExpressionMethods, QueryDsl}; +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl}; pub use diesel_models::refund::{ Refund, RefundCoreWorkflow, RefundNew, RefundUpdate, RefundUpdateInternal, }; @@ -67,8 +67,11 @@ impl RefundDbExt for Refund { ) { search_by_pay_or_ref_id = true; filter = filter - .filter(dsl::payment_id.eq(pid.to_owned())) - .or_filter(dsl::refund_id.eq(ref_id.to_owned())) + .filter( + dsl::payment_id + .eq(pid.to_owned()) + .or(dsl::refund_id.eq(ref_id.to_owned())), + ) .limit(limit) .offset(offset); }; @@ -228,9 +231,11 @@ impl RefundDbExt for Refund { &refund_list_details.refund_id, ) { search_by_pay_or_ref_id = true; - filter = filter - .filter(dsl::payment_id.eq(pid.to_owned())) - .or_filter(dsl::refund_id.eq(ref_id.to_owned())); + 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 { diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index f26cf876ade..15f1aa24370 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -871,6 +871,12 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } + if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { + query = query.filter( + pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()), + ) + } + if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); } @@ -1041,6 +1047,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } + if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { + query = query.filter( + pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()), + ) + } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); }
2024-11-21T10:51:13Z
## Description The PR - Add merchant order reference id filter for payments list - Fix bug for search by refund id (or payment_id), using `or` instead of `or_filter`. Earlier we were searching in whole list, ignoring the filter previously applied in the query. However this was the only case for when we were searching dynamically for ids, it can be payment or refund id. It was producing correct result when searching for only payment id or only refund id. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#6629](https://github.com/juspay/hyperswitch/issues/6629) ## How did you test it? Merchant Order filter is working as expected Request ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "merchant_order_reference_id": "test" }' ``` Response: ``` { "count": 1, "total_count": 1, "data": [ { "payment_id": "test_rkAjUPAeyOVH0V1JPBcg", "merchant_id": "merchant_1732182386", "status": "succeeded", "amount": 19900, "net_amount": 19900, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "test_rkAjUPAeyOVH0V1JPBcg_secret_s8xZQVITYn3CT5RKTiUj", "created": "2024-11-20T22:30:10.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_rkAjUPAeyOVH0V1JPBcg_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_7J9fiPceBUM7IMdb045X", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": "test", "order_tax_amount": null, "connector_mandate_id": null } ] } ``` In refunds list when dynamically searching for both payment_id and refund_id, we are getting correct result now ``` curl --location 'http://localhost:8080/refunds/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "refund_id": "test_LlBBfgQbHHJfQxsoLiyT", "payment_id": "test_LlBBfgQbHHJfQxsoLiyT" }' ``` Response: ``` { "count": 0, "total_count": 0, "data": [] } ```
f24578310f44adf75c993ba42225554377399961
Merchant Order filter is working as expected Request ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "merchant_order_reference_id": "test" }' ``` Response: ``` { "count": 1, "total_count": 1, "data": [ { "payment_id": "test_rkAjUPAeyOVH0V1JPBcg", "merchant_id": "merchant_1732182386", "status": "succeeded", "amount": 19900, "net_amount": 19900, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "test_rkAjUPAeyOVH0V1JPBcg_secret_s8xZQVITYn3CT5RKTiUj", "created": "2024-11-20T22:30:10.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_rkAjUPAeyOVH0V1JPBcg_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_7J9fiPceBUM7IMdb045X", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": "test", "order_tax_amount": null, "connector_mandate_id": null } ] } ``` In refunds list when dynamically searching for both payment_id and refund_id, we are getting correct result now ``` curl --location 'http://localhost:8080/refunds/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "refund_id": "test_LlBBfgQbHHJfQxsoLiyT", "payment_id": "test_LlBBfgQbHHJfQxsoLiyT" }' ``` Response: ``` { "count": 0, "total_count": 0, "data": [] } ```
[ "crates/api_models/src/payments.rs", "crates/hyperswitch_domain_models/src/payments/payment_intent.rs", "crates/router/src/types/storage/dispute.rs", "crates/router/src/types/storage/refund.rs", "crates/storage_impl/src/payments/payment_intent.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6626
Bug: fix(analytics): remove `first_attempt` group by in Payment Intent old metrics `first_attempt` as a group by is getting added internally in the queries as it is required by the new PaymentIntent based metrics for Analytics V2 Dashboard. The logic was added for the existing older metrics as well for PaymentIntents on the older dashboard, and is failing when using sqlx as the Pool. Need to remove the logic for adding `first_attempt` as a group_by in the older metrics, and also tweak the manner in which this is getting added as a group_by in the new metrics.
diff --git a/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs index cf733b0c3da..696dd6a584b 100644 --- a/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs @@ -59,10 +59,6 @@ where }) .switch()?; - query_builder - .add_select_column("attempt_count == 1 as first_attempt") - .switch()?; - query_builder.add_select_column("currency").switch()?; query_builder @@ -102,11 +98,6 @@ where .switch()?; } - query_builder - .add_group_by_clause("attempt_count") - .attach_printable("Error grouping by attempt_count") - .switch()?; - query_builder .add_group_by_clause("currency") .attach_printable("Error grouping by currency") diff --git a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs index 07b1bfcf69f..4bb9dc36b07 100644 --- a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs +++ b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs @@ -57,10 +57,6 @@ where }) .switch()?; - query_builder - .add_select_column("(attempt_count == 1) as first_attempt".to_string()) - .switch()?; - query_builder .add_select_column(Aggregate::Min { field: "created_at", @@ -90,11 +86,6 @@ where .switch()?; } - query_builder - .add_group_by_clause("first_attempt") - .attach_printable("Error grouping by first_attempt") - .switch()?; - if let Some(granularity) = granularity.as_ref() { granularity .set_group_by_clause(&mut query_builder) diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs index 2ba75ca8519..0f13ff39af7 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs @@ -59,7 +59,7 @@ where .switch()?; query_builder - .add_select_column("attempt_count == 1 as first_attempt") + .add_select_column("(attempt_count = 1) as first_attempt") .switch()?; query_builder.add_select_column("currency").switch()?; query_builder @@ -98,8 +98,8 @@ where } query_builder - .add_group_by_clause("attempt_count") - .attach_printable("Error grouping by attempt_count") + .add_group_by_clause("first_attempt") + .attach_printable("Error grouping by first_attempt") .switch()?; query_builder .add_group_by_clause("currency") diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs index 0b55c101a7c..437b22aac71 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs @@ -59,7 +59,7 @@ where .switch()?; query_builder - .add_select_column("attempt_count == 1 as first_attempt") + .add_select_column("(attempt_count = 1) as first_attempt") .switch()?; query_builder diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs index 8c340d0b2d6..9716c7ce4de 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs @@ -58,7 +58,7 @@ where .switch()?; query_builder - .add_select_column("(attempt_count == 1) as first_attempt".to_string()) + .add_select_column("(attempt_count = 1) as first_attempt".to_string()) .switch()?; query_builder diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs index b92b7356924..c6d7c59f240 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs @@ -60,7 +60,7 @@ where .switch()?; query_builder - .add_select_column("attempt_count == 1 as first_attempt") + .add_select_column("(attempt_count = 1) as first_attempt") .switch()?; query_builder.add_select_column("currency").switch()?; @@ -105,7 +105,7 @@ where .switch()?; query_builder .add_group_by_clause("currency") - .attach_printable("Error grouping by first_attempt") + .attach_printable("Error grouping by currency") .switch()?; if let Some(granularity) = granularity.as_ref() { granularity diff --git a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs index ac08f59f358..f8acb2e6e9a 100644 --- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs @@ -59,9 +59,6 @@ where }) .switch()?; - query_builder - .add_select_column("attempt_count == 1 as first_attempt") - .switch()?; query_builder.add_select_column("currency").switch()?; query_builder .add_select_column(Aggregate::Min { @@ -98,10 +95,6 @@ where .switch()?; } - query_builder - .add_group_by_clause("first_attempt") - .attach_printable("Error grouping by first_attempt") - .switch()?; query_builder .add_group_by_clause("currency") .attach_printable("Error grouping by currency")
2024-11-21T08:35:38Z
## Description <!-- Describe your changes in detail --> `first_attempt` as a group by is getting added internally in the queries as it is required by the new PaymentIntent based metrics for Analytics V2 Dashboard. The logic was added for the existing older metrics as well for PaymentIntents on the older dashboard, and is failing when using sqlx as the Pool. Need to remove the logic for adding `first_attempt` as a group_by in the older metrics, and also tweak the manner in which this is getting added as a group_by in the new metrics. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fix the error when using older metrics on the old dashboard (PaymentIntent based metrics) ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Hit the curls to test the various metrics. Sessionized_metrics should be tested only on clickhouse. Older metricss can be tested on both sqlx and clickhouse. ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjI3OTExOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.c3u-icFmoDrNwBzR5Av3IiK-tNktGLZarVxSqg3-LgY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-14T18:30:00Z", "endTime": "2024-11-22T15:24:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "smart_retried_amount", "payments_success_rate", "payment_processed_amount", "sessionized_smart_retried_amount", "sessionized_payments_success_rate", "sessionized_payment_processed_amount", "sessionized_payments_distribution" ] } ]' ``` API should not fail, and should give out response as expected. ```json { "queryData": [ { "successful_smart_retries": null, "total_smart_retries": null, "smart_retried_amount": 0, "smart_retried_amount_in_usd": null, "smart_retried_amount_without_smart_retries": 0, "smart_retried_amount_without_smart_retries_in_usd": null, "payment_intent_count": null, "successful_payments": 15, "successful_payments_without_smart_retries": 7, "total_payments": 15, "payments_success_rate": 100.0, "payments_success_rate_without_smart_retries": 46.666666666666664, "payment_processed_amount": 0, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_in_usd": null, "payment_processed_count_without_smart_retries": null, "payments_success_rate_distribution_without_smart_retries": 87.5, "payments_failure_rate_distribution_without_smart_retries": 0.0, "status": null, "currency": null, "profile_id": null, "connector": null, "auth_type": null, "payment_method": null, "payment_method_type": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-14T18:30:00.000Z", "end_time": "2024-11-22T15:24:00.000Z" }, "time_bucket": "2024-11-14 18:30:00" }, { "successful_smart_retries": null, "total_smart_retries": null, "smart_retried_amount": 0, "smart_retried_amount_in_usd": 0, "smart_retried_amount_without_smart_retries": 0, "smart_retried_amount_without_smart_retries_in_usd": 0, "payment_intent_count": null, "successful_payments": null, "successful_payments_without_smart_retries": null, "total_payments": null, "payments_success_rate": null, "payments_success_rate_without_smart_retries": null, "payment_processed_amount": 40000, "payment_processed_amount_in_usd": 40000, "payment_processed_count": 4, "payment_processed_amount_without_smart_retries": 20000, "payment_processed_amount_without_smart_retries_in_usd": 20000, "payment_processed_count_without_smart_retries": 2, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_without_smart_retries": null, "status": null, "currency": "USD", "profile_id": null, "connector": null, "auth_type": null, "payment_method": null, "payment_method_type": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-14T18:30:00.000Z", "end_time": "2024-11-22T15:24:00.000Z" }, "time_bucket": "2024-11-14 18:30:00" }, { "successful_smart_retries": null, "total_smart_retries": null, "smart_retried_amount": 0, "smart_retried_amount_in_usd": 0, "smart_retried_amount_without_smart_retries": 0, "smart_retried_amount_without_smart_retries_in_usd": 0, "payment_intent_count": null, "successful_payments": null, "successful_payments_without_smart_retries": null, "total_payments": null, "payments_success_rate": null, "payments_success_rate_without_smart_retries": null, "payment_processed_amount": 110000, "payment_processed_amount_in_usd": 1302, "payment_processed_count": 11, "payment_processed_amount_without_smart_retries": 50000, "payment_processed_amount_without_smart_retries_in_usd": 591, "payment_processed_count_without_smart_retries": 5, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_without_smart_retries": null, "status": null, "currency": "INR", "profile_id": null, "connector": null, "auth_type": null, "payment_method": null, "payment_method_type": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-14T18:30:00.000Z", "end_time": "2024-11-22T15:24:00.000Z" }, "time_bucket": "2024-11-14 18:30:00" } ], "metaData": [ { "total_success_rate": 100.0, "total_success_rate_without_smart_retries": 46.666666666666664, "total_smart_retried_amount": 0, "total_smart_retried_amount_without_smart_retries": 0, "total_payment_processed_amount": 150000, "total_payment_processed_amount_without_smart_retries": 70000, "total_smart_retried_amount_in_usd": 0, "total_smart_retried_amount_without_smart_retries_in_usd": 0, "total_payment_processed_amount_in_usd": 41302, "total_payment_processed_amount_without_smart_retries_in_usd": 20591, "total_payment_processed_count": 15, "total_payment_processed_count_without_smart_retries": 7 } ] } ```
f24578310f44adf75c993ba42225554377399961
Hit the curls to test the various metrics. Sessionized_metrics should be tested only on clickhouse. Older metricss can be tested on both sqlx and clickhouse. ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjI3OTExOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.c3u-icFmoDrNwBzR5Av3IiK-tNktGLZarVxSqg3-LgY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-14T18:30:00Z", "endTime": "2024-11-22T15:24:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "smart_retried_amount", "payments_success_rate", "payment_processed_amount", "sessionized_smart_retried_amount", "sessionized_payments_success_rate", "sessionized_payment_processed_amount", "sessionized_payments_distribution" ] } ]' ``` API should not fail, and should give out response as expected. ```json { "queryData": [ { "successful_smart_retries": null, "total_smart_retries": null, "smart_retried_amount": 0, "smart_retried_amount_in_usd": null, "smart_retried_amount_without_smart_retries": 0, "smart_retried_amount_without_smart_retries_in_usd": null, "payment_intent_count": null, "successful_payments": 15, "successful_payments_without_smart_retries": 7, "total_payments": 15, "payments_success_rate": 100.0, "payments_success_rate_without_smart_retries": 46.666666666666664, "payment_processed_amount": 0, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_in_usd": null, "payment_processed_count_without_smart_retries": null, "payments_success_rate_distribution_without_smart_retries": 87.5, "payments_failure_rate_distribution_without_smart_retries": 0.0, "status": null, "currency": null, "profile_id": null, "connector": null, "auth_type": null, "payment_method": null, "payment_method_type": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-14T18:30:00.000Z", "end_time": "2024-11-22T15:24:00.000Z" }, "time_bucket": "2024-11-14 18:30:00" }, { "successful_smart_retries": null, "total_smart_retries": null, "smart_retried_amount": 0, "smart_retried_amount_in_usd": 0, "smart_retried_amount_without_smart_retries": 0, "smart_retried_amount_without_smart_retries_in_usd": 0, "payment_intent_count": null, "successful_payments": null, "successful_payments_without_smart_retries": null, "total_payments": null, "payments_success_rate": null, "payments_success_rate_without_smart_retries": null, "payment_processed_amount": 40000, "payment_processed_amount_in_usd": 40000, "payment_processed_count": 4, "payment_processed_amount_without_smart_retries": 20000, "payment_processed_amount_without_smart_retries_in_usd": 20000, "payment_processed_count_without_smart_retries": 2, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_without_smart_retries": null, "status": null, "currency": "USD", "profile_id": null, "connector": null, "auth_type": null, "payment_method": null, "payment_method_type": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-14T18:30:00.000Z", "end_time": "2024-11-22T15:24:00.000Z" }, "time_bucket": "2024-11-14 18:30:00" }, { "successful_smart_retries": null, "total_smart_retries": null, "smart_retried_amount": 0, "smart_retried_amount_in_usd": 0, "smart_retried_amount_without_smart_retries": 0, "smart_retried_amount_without_smart_retries_in_usd": 0, "payment_intent_count": null, "successful_payments": null, "successful_payments_without_smart_retries": null, "total_payments": null, "payments_success_rate": null, "payments_success_rate_without_smart_retries": null, "payment_processed_amount": 110000, "payment_processed_amount_in_usd": 1302, "payment_processed_count": 11, "payment_processed_amount_without_smart_retries": 50000, "payment_processed_amount_without_smart_retries_in_usd": 591, "payment_processed_count_without_smart_retries": 5, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_without_smart_retries": null, "status": null, "currency": "INR", "profile_id": null, "connector": null, "auth_type": null, "payment_method": null, "payment_method_type": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-14T18:30:00.000Z", "end_time": "2024-11-22T15:24:00.000Z" }, "time_bucket": "2024-11-14 18:30:00" } ], "metaData": [ { "total_success_rate": 100.0, "total_success_rate_without_smart_retries": 46.666666666666664, "total_smart_retried_amount": 0, "total_smart_retried_amount_without_smart_retries": 0, "total_payment_processed_amount": 150000, "total_payment_processed_amount_without_smart_retries": 70000, "total_smart_retried_amount_in_usd": 0, "total_smart_retried_amount_without_smart_retries_in_usd": 0, "total_payment_processed_amount_in_usd": 41302, "total_payment_processed_amount_without_smart_retries_in_usd": 20591, "total_payment_processed_count": 15, "total_payment_processed_count_without_smart_retries": 7 } ] } ```
[ "crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs", "crates/analytics/src/payment_intents/metrics/payments_success_rate.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs", "crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6623
Bug: Address `CVE-2024-21538` in Cypress https://vulert.com/vuln-db/CVE-2024-21538
diff --git a/cypress-tests-v2/package-lock.json b/cypress-tests-v2/package-lock.json index 36f801468a9..cac88cab055 100644 --- a/cypress-tests-v2/package-lock.json +++ b/cypress-tests-v2/package-lock.json @@ -10,7 +10,7 @@ "license": "ISC", "devDependencies": { "@types/fs-extra": "^11.0.4", - "cypress": "^13.15.2", + "cypress": "^13.16.0", "cypress-mochawesome-reporter": "^3.8.2", "jsqr": "^1.4.0", "nanoid": "^5.0.8", @@ -727,8 +727,8 @@ "license": "MIT" }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, "license": "MIT", @@ -742,9 +742,9 @@ } }, "node_modules/cypress": { - "version": "13.15.2", - "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.15.2.tgz", - "integrity": "sha512-ARbnUorjcCM3XiPwgHKuqsyr5W9Qn+pIIBPaoilnoBkLdSC2oLQjV1BUpnmc7KR+b7Avah3Ly2RMFnfxr96E/A==", + "version": "13.16.0", + "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.16.0.tgz", + "integrity": "sha512-g6XcwqnvzXrqiBQR/5gN+QsyRmKRhls1y5E42fyOvsmU7JuY+wM6uHJWj4ZPttjabzbnRvxcik2WemR8+xT6FA==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -1057,7 +1057,7 @@ "dev": true, "license": "MIT", "dependencies": { - "cross-spawn": "^7.0.0", + "cross-spawn": "^7.0.6", "get-stream": "^5.0.0", "human-signals": "^1.1.1", "is-stream": "^2.0.0", diff --git a/cypress-tests-v2/package.json b/cypress-tests-v2/package.json index 20403f9e777..37a51db93cb 100644 --- a/cypress-tests-v2/package.json +++ b/cypress-tests-v2/package.json @@ -15,7 +15,7 @@ "license": "ISC", "devDependencies": { "@types/fs-extra": "^11.0.4", - "cypress": "^13.15.2", + "cypress": "^13.16.0", "cypress-mochawesome-reporter": "^3.8.2", "jsqr": "^1.4.0", "prettier": "^3.3.2",
2024-11-21T07:17:18Z
## Description <!-- Describe your changes in detail --> This PR update Cypress packages to address [CVE-2024-21538](https://vulert.com/vuln-db/CVE-2024-21538). Closes https://github.com/juspay/hyperswitch/issues/6623 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> CVE. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> No tests needed as it is just a dependency update. CI passing should be enough.
f24578310f44adf75c993ba42225554377399961
No tests needed as it is just a dependency update. CI passing should be enough.
[ "cypress-tests-v2/package-lock.json", "cypress-tests-v2/package.json" ]
juspay/hyperswitch
juspay__hyperswitch-6620
Bug: feat(themes): Support naming themes Currently themes don't have names, and it's better to have a way to attach a name to a theme. So that we can know about theme without having to look at the theme data.
diff --git a/crates/common_utils/src/types/theme.rs b/crates/common_utils/src/types/theme.rs index a2e6fe4b19c..03b4cf23a6c 100644 --- a/crates/common_utils/src/types/theme.rs +++ b/crates/common_utils/src/types/theme.rs @@ -4,11 +4,12 @@ use crate::id_type; /// Currently being used for theme related APIs and queries. #[derive(Debug)] pub enum ThemeLineage { - /// Tenant lineage variant - Tenant { - /// tenant_id: String - tenant_id: String, - }, + // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType + // /// Tenant lineage variant + // Tenant { + // /// tenant_id: String + // tenant_id: String, + // }, /// Org lineage variant Organization { /// tenant_id: String diff --git a/crates/diesel_models/src/query/user/theme.rs b/crates/diesel_models/src/query/user/theme.rs index c021edca325..78fd5025ef9 100644 --- a/crates/diesel_models/src/query/user/theme.rs +++ b/crates/diesel_models/src/query/user/theme.rs @@ -3,7 +3,7 @@ use diesel::{ associations::HasTable, pg::Pg, sql_types::{Bool, Nullable}, - BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, + BoolExpressionMethods, ExpressionMethods, }; use crate::{ @@ -27,14 +27,15 @@ impl Theme { + 'static, > { match lineage { - ThemeLineage::Tenant { tenant_id } => Box::new( - dsl::tenant_id - .eq(tenant_id) - .and(dsl::org_id.is_null()) - .and(dsl::merchant_id.is_null()) - .and(dsl::profile_id.is_null()) - .nullable(), - ), + // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType + // ThemeLineage::Tenant { tenant_id } => Box::new( + // dsl::tenant_id + // .eq(tenant_id) + // .and(dsl::org_id.is_null()) + // .and(dsl::merchant_id.is_null()) + // .and(dsl::profile_id.is_null()) + // .nullable(), + // ), ThemeLineage::Organization { tenant_id, org_id } => Box::new( dsl::tenant_id .eq(tenant_id) diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 19a0763d770..4b3a374090e 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1279,6 +1279,10 @@ diesel::table! { profile_id -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, + #[max_length = 64] + entity_type -> Varchar, + #[max_length = 64] + theme_name -> Varchar, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index e3097f80db9..21f112ea37c 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1225,6 +1225,10 @@ diesel::table! { profile_id -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, + #[max_length = 64] + entity_type -> Varchar, + #[max_length = 64] + theme_name -> Varchar, } } diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rs index 0824ae71919..2f8152e419c 100644 --- a/crates/diesel_models/src/user/theme.rs +++ b/crates/diesel_models/src/user/theme.rs @@ -1,3 +1,4 @@ +use common_enums::EntityType; use common_utils::id_type; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; @@ -14,6 +15,8 @@ pub struct Theme { pub profile_id: Option<id_type::ProfileId>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, + pub entity_type: EntityType, + pub theme_name: String, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -26,4 +29,6 @@ pub struct ThemeNew { pub profile_id: Option<id_type::ProfileId>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, + pub entity_type: EntityType, + pub theme_name: String, } diff --git a/crates/router/src/db/user/theme.rs b/crates/router/src/db/user/theme.rs index d71b82cdea4..f1e4f4f794e 100644 --- a/crates/router/src/db/user/theme.rs +++ b/crates/router/src/db/user/theme.rs @@ -65,12 +65,13 @@ impl ThemeInterface for Store { fn check_theme_with_lineage(theme: &storage::Theme, lineage: &ThemeLineage) -> bool { match lineage { - ThemeLineage::Tenant { tenant_id } => { - &theme.tenant_id == tenant_id - && theme.org_id.is_none() - && theme.merchant_id.is_none() - && theme.profile_id.is_none() - } + // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType + // ThemeLineage::Tenant { tenant_id } => { + // &theme.tenant_id == tenant_id + // && theme.org_id.is_none() + // && theme.merchant_id.is_none() + // && theme.profile_id.is_none() + // } ThemeLineage::Organization { tenant_id, org_id } => { &theme.tenant_id == tenant_id && theme @@ -156,6 +157,8 @@ impl ThemeInterface for MockDb { profile_id: new_theme.profile_id, created_at: new_theme.created_at, last_modified_at: new_theme.last_modified_at, + entity_type: new_theme.entity_type, + theme_name: new_theme.theme_name, }; themes.push(theme.clone()); diff --git a/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/down.sql b/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/down.sql new file mode 100644 index 00000000000..a56426b60c0 --- /dev/null +++ b/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE themes DROP COLUMN IF EXISTS entity_type; +ALTER TABLE themes DROP COLUMN IF EXISTS theme_name; diff --git a/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/up.sql b/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/up.sql new file mode 100644 index 00000000000..924385d45d6 --- /dev/null +++ b/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE themes ADD COLUMN IF NOT EXISTS entity_type VARCHAR(64) NOT NULL; +ALTER TABLE themes ADD COLUMN IF NOT EXISTS theme_name VARCHAR(64) NOT NULL;
2024-11-20T12:13:51Z
## Description <!-- Describe your changes in detail --> This PR adds `theme_name` and `entity_type` in the themes table. This will help us in 1. Having a name for the theme. 2. EntityType identifier to help us identity the lineage type instead of guessing it. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 3. `crates/router/src/configs` 4. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6620. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This is an internal change and doesn't affect any APIs.
43d87913ab3d177a6d193b3e475c96609cc09a28
This is an internal change and doesn't affect any APIs.
[ "crates/common_utils/src/types/theme.rs", "crates/diesel_models/src/query/user/theme.rs", "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/schema_v2.rs", "crates/diesel_models/src/user/theme.rs", "crates/router/src/db/user/theme.rs", "migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/down.sql", "migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-5156
Bug: [FEATURE] Add support for SMTP email server ### Feature Description Add support for sending emails with a custom SMTP server. (Currently only AWS SES is supported) ### Possible Implementation Could be implemented using `lettre` crate. Steps to implement: - Create the email building and sending logic - Impl the EmailClient trait - Add a new arm to the match statement in `create_email_client()` function ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index 27b4158ba61..a2ede8c08c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1888,9 +1888,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.1.18" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b62ac837cdb5cb22e10a256099b4fc502b1dfe560cb282963a974d7abd80e476" +checksum = "fd9de9f2205d5ef3fd67e685b0df337994ddd4495e2a28d185500d0e1edfea47" dependencies = [ "jobserver", "libc", @@ -1963,6 +1963,16 @@ dependencies = [ "phf_codegen", ] +[[package]] +name = "chumsky" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eebd66744a15ded14960ab4ccdbfb51ad3b81f51f3f04a80adac98c985396c9" +dependencies = [ + "hashbrown 0.14.5", + "stacker", +] + [[package]] name = "ciborium" version = "0.2.2" @@ -2962,6 +2972,22 @@ dependencies = [ "zeroize", ] +[[package]] +name = "email-encoding" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60d1d33cdaede7e24091f039632eb5d3c7469fe5b066a985281a34fc70fa317f" +dependencies = [ + "base64 0.22.1", + "memchr", +] + +[[package]] +name = "email_address" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" + [[package]] name = "encoding_rs" version = "0.8.34" @@ -3134,6 +3160,7 @@ dependencies = [ "hyper-proxy", "hyper-util", "hyperswitch_interfaces", + "lettre", "masking", "once_cell", "prost 0.13.2", @@ -3732,6 +3759,17 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "hostname" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c7c7c8ac16c798734b8a24560c1362120597c40d5e1459f09498f8f6c8f2ba" +dependencies = [ + "cfg-if 1.0.0", + "libc", + "windows", +] + [[package]] name = "hsdev" version = "0.1.0" @@ -4117,6 +4155,124 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locid" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locid_transform" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_locid_transform_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locid_transform_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" + +[[package]] +name = "icu_normalizer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec 1.13.2", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" + +[[package]] +name = "icu_properties" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locid_transform", + "icu_properties_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" + +[[package]] +name = "icu_provider" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_provider_macros", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_provider_macros" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.77", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -4133,6 +4289,27 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "idna" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +dependencies = [ + "idna_adapter", + "smallvec 1.13.2", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "ignore" version = "0.4.22" @@ -4456,6 +4633,31 @@ dependencies = [ "spin 0.9.8", ] +[[package]] +name = "lettre" +version = "0.11.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0161e452348e399deb685ba05e55ee116cae9410f4f51fe42d597361444521d9" +dependencies = [ + "base64 0.22.1", + "chumsky", + "email-encoding", + "email_address", + "fastrand 2.1.1", + "futures-util", + "hostname", + "httpdate", + "idna 1.0.3", + "mime", + "native-tls", + "nom", + "percent-encoding", + "quoted_printable", + "socket2", + "tokio 1.40.0", + "url", +] + [[package]] name = "libc" version = "0.2.158" @@ -4531,6 +4733,12 @@ version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" +[[package]] +name = "litemap" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" + [[package]] name = "local-channel" version = "0.1.5" @@ -5832,7 +6040,7 @@ checksum = "f8650aabb6c35b860610e9cff5dc1af886c9e25073b7b1712a68972af4281302" dependencies = [ "bytes 1.7.1", "heck 0.5.0", - "itertools 0.12.1", + "itertools 0.13.0", "log", "multimap", "once_cell", @@ -5865,7 +6073,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acf0c195eebb4af52c752bec4f52f645da98b6e92077a04110c7f349477ae5ac" dependencies = [ "anyhow", - "itertools 0.12.1", + "itertools 0.13.0", "proc-macro2", "quote", "syn 2.0.77", @@ -5880,6 +6088,15 @@ dependencies = [ "prost 0.13.2", ] +[[package]] +name = "psm" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200b9ff220857e53e184257720a14553b2f4aa02577d2ed9842d45d4b9654810" +dependencies = [ + "cc", +] + [[package]] name = "ptr_meta" version = "0.1.4" @@ -5949,6 +6166,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "quoted_printable" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "640c9bd8497b02465aeef5375144c26062e0dcd5939dfcbb0f5db76cb8c17c73" + [[package]] name = "r2d2" version = "0.8.10" @@ -7669,6 +7892,19 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" +[[package]] +name = "stacker" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799c883d55abdb5e98af1a7b3f23b9b6de8ecada0ecac058672d7635eb48ca7b" +dependencies = [ + "cc", + "cfg-if 1.0.0", + "libc", + "psm", + "windows-sys 0.59.0", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -8092,6 +8328,16 @@ dependencies = [ "crunchy", ] +[[package]] +name = "tinystr" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tinytemplate" version = "1.2.1" @@ -8939,7 +9185,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" dependencies = [ "form_urlencoded", - "idna", + "idna 0.5.0", "percent-encoding", "serde", ] @@ -8956,6 +9202,18 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "110352d4e9076c67839003c7788d8604e24dcded13e0b375af3efaa8cf468517" +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "utf8parse" version = "0.2.2" @@ -9001,7 +9259,7 @@ version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da339118f018cc70ebf01fafc103360528aad53717e4bf311db929cb01cb9345" dependencies = [ - "idna", + "idna 0.5.0", "once_cell", "regex", "serde", @@ -9290,6 +9548,16 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" +dependencies = [ + "windows-core", + "windows-targets 0.52.6", +] + [[package]] name = "windows-core" version = "0.52.0" @@ -9529,6 +9797,18 @@ dependencies = [ "url", ] +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" + [[package]] name = "ws2_32-sys" version = "0.2.1" @@ -9580,6 +9860,30 @@ dependencies = [ "linked-hash-map", ] +[[package]] +name = "yoke" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" +dependencies = [ + "serde", + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.77", + "synstructure 0.13.1", +] + [[package]] name = "zerocopy" version = "0.7.35" @@ -9601,12 +9905,55 @@ dependencies = [ "syn 2.0.77", ] +[[package]] +name = "zerofrom" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.77", + "synstructure 0.13.1", +] + [[package]] name = "zeroize" version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" +[[package]] +name = "zerovec" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.77", +] + [[package]] name = "zstd" version = "0.13.2" diff --git a/config/development.toml b/config/development.toml index 6a6fda6755e..97739c3f5cd 100644 --- a/config/development.toml +++ b/config/development.toml @@ -311,7 +311,7 @@ wildcard_origin = true sender_email = "example@example.com" aws_region = "" allowed_unverified_days = 1 -active_email_client = "SES" +active_email_client = "NO_EMAIL_CLIENT" recon_recipient_email = "recon@example.com" prod_intent_recipient_email = "business@example.com" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 7adeee8a376..d71be958486 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -676,7 +676,7 @@ connector_list = "cybersource" sender_email = "example@example.com" # Sender email aws_region = "" # AWS region used by AWS SES allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email -active_email_client = "SES" # The currently active email client +active_email_client = "NO_EMAIL_CLIENT" # The currently active email client recon_recipient_email = "recon@example.com" # Recipient email for recon request email prod_intent_recipient_email = "business@example.com" # Recipient email for prod intent email diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 12b9dd3b0f3..e617dbe8351 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -29,6 +29,7 @@ error-stack = "0.4.1" hex = "0.4.3" hyper = "0.14.28" hyper-proxy = "0.9.1" +lettre = "0.11.10" once_cell = "1.19.0" serde = { version = "1.0.197", features = ["derive"] } thiserror = "1.0.58" diff --git a/crates/external_services/src/email.rs b/crates/external_services/src/email.rs index 5751de95c12..2e05a26e1f1 100644 --- a/crates/external_services/src/email.rs +++ b/crates/external_services/src/email.rs @@ -7,6 +7,12 @@ use serde::Deserialize; /// Implementation of aws ses client pub mod ses; +/// Implementation of SMTP server client +pub mod smtp; + +/// Implementation of Email client when email support is disabled +pub mod no_email; + /// Custom Result type alias for Email operations. pub type EmailResult<T> = CustomResult<T, EmailError>; @@ -114,14 +120,27 @@ dyn_clone::clone_trait_object!(EmailClient<RichText = Body>); /// List of available email clients to choose from #[derive(Debug, Clone, Default, Deserialize)] -pub enum AvailableEmailClients { +#[serde(tag = "active_email_client")] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum EmailClientConfigs { #[default] + /// Default Email client to use when no client is specified + NoEmailClient, /// AWS ses email client - SES, + Ses { + /// AWS SES client configuration + aws_ses: ses::SESConfig, + }, + /// Other Simple SMTP server + Smtp { + /// SMTP server configuration + smtp: smtp::SmtpServerConfig, + }, } /// Struct that contains the settings required to construct an EmailClient. #[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] pub struct EmailSettings { /// The AWS region to send SES requests to. pub aws_region: String, @@ -132,11 +151,9 @@ pub struct EmailSettings { /// Sender email pub sender_email: String, - /// Configs related to AWS Simple Email Service - pub aws_ses: Option<ses::SESConfig>, - - /// The active email client to use - pub active_email_client: AvailableEmailClients, + #[serde(flatten)] + /// The client specific configurations + pub client_config: EmailClientConfigs, /// Recipient email for recon emails pub recon_recipient_email: pii::Email, @@ -145,6 +162,17 @@ pub struct EmailSettings { pub prod_intent_recipient_email: pii::Email, } +impl EmailSettings { + /// Validation for the Email client specific configurations + pub fn validate(&self) -> Result<(), &'static str> { + match &self.client_config { + EmailClientConfigs::Ses { ref aws_ses } => aws_ses.validate(), + EmailClientConfigs::Smtp { ref smtp } => smtp.validate(), + EmailClientConfigs::NoEmailClient => Ok(()), + } + } +} + /// Errors that could occur from EmailClient. #[derive(Debug, thiserror::Error)] pub enum EmailError { diff --git a/crates/external_services/src/email/no_email.rs b/crates/external_services/src/email/no_email.rs new file mode 100644 index 00000000000..6ec5d69e1ab --- /dev/null +++ b/crates/external_services/src/email/no_email.rs @@ -0,0 +1,37 @@ +use common_utils::{errors::CustomResult, pii}; +use router_env::logger; + +use crate::email::{EmailClient, EmailError, EmailResult, IntermediateString}; + +/// Client when email support is disabled +#[derive(Debug, Clone, Default, serde::Deserialize)] +pub struct NoEmailClient {} + +impl NoEmailClient { + /// Constructs a new client when email is disabled + pub async fn create() -> Self { + Self {} + } +} + +#[async_trait::async_trait] +impl EmailClient for NoEmailClient { + type RichText = String; + fn convert_to_rich_text( + &self, + intermediate_string: IntermediateString, + ) -> CustomResult<Self::RichText, EmailError> { + Ok(intermediate_string.into_inner()) + } + + async fn send_email( + &self, + _recipient: pii::Email, + _subject: String, + _body: Self::RichText, + _proxy_url: Option<&String>, + ) -> EmailResult<()> { + logger::info!("Email not sent as email support is disabled, please enable any of the supported email clients to send emails"); + Ok(()) + } +} diff --git a/crates/external_services/src/email/ses.rs b/crates/external_services/src/email/ses.rs index 73599b344cd..f9dcc8f26ad 100644 --- a/crates/external_services/src/email/ses.rs +++ b/crates/external_services/src/email/ses.rs @@ -7,7 +7,7 @@ use aws_sdk_sesv2::{ Client, }; use aws_sdk_sts::config::Credentials; -use common_utils::{errors::CustomResult, ext_traits::OptionExt, pii}; +use common_utils::{errors::CustomResult, pii}; use error_stack::{report, ResultExt}; use hyper::Uri; use masking::PeekInterface; @@ -19,6 +19,7 @@ use crate::email::{EmailClient, EmailError, EmailResult, EmailSettings, Intermed #[derive(Debug, Clone)] pub struct AwsSes { sender: String, + ses_config: SESConfig, settings: EmailSettings, } @@ -32,6 +33,21 @@ pub struct SESConfig { pub sts_role_session_name: String, } +impl SESConfig { + /// Validation for the SES client specific configs + pub fn validate(&self) -> Result<(), &'static str> { + use common_utils::{ext_traits::ConfigExt, fp_utils::when}; + + when(self.email_role_arn.is_default_or_empty(), || { + Err("email.aws_ses.email_role_arn must not be empty") + })?; + + when(self.sts_role_session_name.is_default_or_empty(), || { + Err("email.aws_ses.sts_role_session_name must not be empty") + }) + } +} + /// Errors that could occur during SES operations. #[derive(Debug, thiserror::Error)] pub enum AwsSesError { @@ -67,15 +83,20 @@ pub enum AwsSesError { impl AwsSes { /// Constructs a new AwsSes client - pub async fn create(conf: &EmailSettings, proxy_url: Option<impl AsRef<str>>) -> Self { + pub async fn create( + conf: &EmailSettings, + ses_config: &SESConfig, + proxy_url: Option<impl AsRef<str>>, + ) -> Self { // Build the client initially which will help us know if the email configuration is correct - Self::create_client(conf, proxy_url) + Self::create_client(conf, ses_config, proxy_url) .await .map_err(|error| logger::error!(?error, "Failed to initialize SES Client")) .ok(); Self { sender: conf.sender_email.clone(), + ses_config: ses_config.clone(), settings: conf.clone(), } } @@ -83,19 +104,13 @@ impl AwsSes { /// A helper function to create ses client pub async fn create_client( conf: &EmailSettings, + ses_config: &SESConfig, proxy_url: Option<impl AsRef<str>>, ) -> CustomResult<Client, AwsSesError> { let sts_config = Self::get_shared_config(conf.aws_region.to_owned(), proxy_url.as_ref())? .load() .await; - let ses_config = conf - .aws_ses - .as_ref() - .get_required_value("aws ses configuration") - .attach_printable("The selected email client is aws ses, but configuration is missing") - .change_context(AwsSesError::MissingConfigurationVariable("aws_ses"))?; - let role = aws_sdk_sts::Client::new(&sts_config) .assume_role() .role_arn(&ses_config.email_role_arn) @@ -219,7 +234,7 @@ impl EmailClient for AwsSes { ) -> EmailResult<()> { // Not using the same email client which was created at startup as the role session would expire // Create a client every time when the email is being sent - let email_client = Self::create_client(&self.settings, proxy_url) + let email_client = Self::create_client(&self.settings, &self.ses_config, proxy_url) .await .change_context(EmailError::ClientBuildingFailure)?; diff --git a/crates/external_services/src/email/smtp.rs b/crates/external_services/src/email/smtp.rs new file mode 100644 index 00000000000..33ab89f4571 --- /dev/null +++ b/crates/external_services/src/email/smtp.rs @@ -0,0 +1,189 @@ +use std::time::Duration; + +use common_utils::{errors::CustomResult, pii}; +use error_stack::ResultExt; +use lettre::{ + address::AddressError, + error, + message::{header::ContentType, Mailbox}, + transport::smtp::{self, authentication::Credentials}, + Message, SmtpTransport, Transport, +}; +use masking::{PeekInterface, Secret}; + +use crate::email::{EmailClient, EmailError, EmailResult, EmailSettings, IntermediateString}; + +/// Client for SMTP server operation +#[derive(Debug, Clone, Default, serde::Deserialize)] +pub struct SmtpServer { + /// sender email id + pub sender: String, + /// SMTP server specific configs + pub smtp_config: SmtpServerConfig, +} + +impl SmtpServer { + /// A helper function to create SMTP server client + pub fn create_client(&self) -> Result<SmtpTransport, SmtpError> { + let host = self.smtp_config.host.clone(); + let port = self.smtp_config.port; + let timeout = Some(Duration::from_secs(self.smtp_config.timeout)); + let credentials = self + .smtp_config + .username + .clone() + .zip(self.smtp_config.password.clone()) + .map(|(username, password)| { + Credentials::new(username.peek().to_owned(), password.peek().to_owned()) + }); + match &self.smtp_config.connection { + SmtpConnection::StartTls => match credentials { + Some(credentials) => Ok(SmtpTransport::starttls_relay(&host) + .map_err(SmtpError::ConnectionFailure)? + .port(port) + .timeout(timeout) + .credentials(credentials) + .build()), + None => Ok(SmtpTransport::starttls_relay(&host) + .map_err(SmtpError::ConnectionFailure)? + .port(port) + .timeout(timeout) + .build()), + }, + SmtpConnection::Plaintext => match credentials { + Some(credentials) => Ok(SmtpTransport::builder_dangerous(&host) + .port(port) + .timeout(timeout) + .credentials(credentials) + .build()), + None => Ok(SmtpTransport::builder_dangerous(&host) + .port(port) + .timeout(timeout) + .build()), + }, + } + } + /// Constructs a new SMTP client + pub async fn create(conf: &EmailSettings, smtp_config: SmtpServerConfig) -> Self { + Self { + sender: conf.sender_email.clone(), + smtp_config: smtp_config.clone(), + } + } + /// helper function to convert email id into Mailbox + fn to_mail_box(email: String) -> EmailResult<Mailbox> { + Ok(Mailbox::new( + None, + email + .parse() + .map_err(SmtpError::EmailParsingFailed) + .change_context(EmailError::EmailSendingFailure)?, + )) + } +} +/// Struct that contains the SMTP server specific configs required +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct SmtpServerConfig { + /// hostname of the SMTP server eg: smtp.gmail.com + pub host: String, + /// portname of the SMTP server eg: 25 + pub port: u16, + /// timeout for the SMTP server connection in seconds eg: 10 + pub timeout: u64, + /// Username name of the SMTP server + pub username: Option<Secret<String>>, + /// Password of the SMTP server + pub password: Option<Secret<String>>, + /// Connection type of the SMTP server + #[serde(default)] + pub connection: SmtpConnection, +} + +/// Enum that contains the connection types of the SMTP server +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SmtpConnection { + #[default] + /// Plaintext connection which MUST then successfully upgrade to TLS via STARTTLS + StartTls, + /// Plaintext connection (very insecure) + Plaintext, +} + +impl SmtpServerConfig { + /// Validation for the SMTP server client specific configs + pub fn validate(&self) -> Result<(), &'static str> { + use common_utils::{ext_traits::ConfigExt, fp_utils::when}; + when(self.host.is_default_or_empty(), || { + Err("email.smtp.host must not be empty") + })?; + self.username.clone().zip(self.password.clone()).map_or( + Ok(()), + |(username, password)| { + when(username.peek().is_default_or_empty(), || { + Err("email.smtp.username must not be empty") + })?; + when(password.peek().is_default_or_empty(), || { + Err("email.smtp.password must not be empty") + }) + }, + )?; + Ok(()) + } +} + +#[async_trait::async_trait] +impl EmailClient for SmtpServer { + type RichText = String; + fn convert_to_rich_text( + &self, + intermediate_string: IntermediateString, + ) -> CustomResult<Self::RichText, EmailError> { + Ok(intermediate_string.into_inner()) + } + + async fn send_email( + &self, + recipient: pii::Email, + subject: String, + body: Self::RichText, + _proxy_url: Option<&String>, + ) -> EmailResult<()> { + // Create a client every time when the email is being sent + let email_client = + Self::create_client(self).change_context(EmailError::EmailSendingFailure)?; + + let email = Message::builder() + .to(Self::to_mail_box(recipient.peek().to_string())?) + .from(Self::to_mail_box(self.sender.clone())?) + .subject(subject) + .header(ContentType::TEXT_HTML) + .body(body) + .map_err(SmtpError::MessageBuildingFailed) + .change_context(EmailError::EmailSendingFailure)?; + + email_client + .send(&email) + .map_err(SmtpError::SendingFailure) + .change_context(EmailError::EmailSendingFailure)?; + Ok(()) + } +} + +/// Errors that could occur during SES operations. +#[derive(Debug, thiserror::Error)] +pub enum SmtpError { + /// An error occurred in the SMTP while sending email. + #[error("Failed to Send Email {0:?}")] + SendingFailure(smtp::Error), + /// An error occurred in the SMTP while building the message content. + #[error("Failed to create connection {0:?}")] + ConnectionFailure(smtp::Error), + /// An error occurred in the SMTP while building the message content. + #[error("Failed to Build Email content {0:?}")] + MessageBuildingFailed(error::Error), + /// An error occurred in the SMTP while building the message content. + #[error("Failed to parse given email {0:?}")] + EmailParsingFailed(AddressError), +} diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index f675aad11a7..76b58f5b67b 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -881,6 +881,10 @@ impl Settings<SecuredSecret> { .transpose()?; self.key_manager.get_inner().validate()?; + #[cfg(feature = "email")] + self.email + .validate() + .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; Ok(()) } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 1d7e9727cf3..baa2ba4ae15 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -8,7 +8,9 @@ use common_enums::TransactionType; #[cfg(feature = "partial-auth")] use common_utils::crypto::Blake3; #[cfg(feature = "email")] -use external_services::email::{ses::AwsSes, EmailService}; +use external_services::email::{ + no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService, +}; use external_services::{file_storage::FileStorageInterface, grpc_client::GrpcClients}; use hyperswitch_interfaces::{ encryption_interface::EncryptionManagementInterface, @@ -97,7 +99,7 @@ pub struct SessionState { pub api_client: Box<dyn crate::services::ApiClient>, pub event_handler: EventsHandler, #[cfg(feature = "email")] - pub email_client: Arc<dyn EmailService>, + pub email_client: Arc<Box<dyn EmailService>>, #[cfg(feature = "olap")] pub pool: AnalyticsProvider, pub file_storage_client: Arc<dyn FileStorageInterface>, @@ -195,7 +197,7 @@ pub struct AppState { pub conf: Arc<settings::Settings<RawSecret>>, pub event_handler: EventsHandler, #[cfg(feature = "email")] - pub email_client: Arc<dyn EmailService>, + pub email_client: Arc<Box<dyn EmailService>>, pub api_client: Box<dyn crate::services::ApiClient>, #[cfg(feature = "olap")] pub pools: HashMap<String, AnalyticsProvider>, @@ -215,7 +217,7 @@ pub trait AppStateInfo { fn conf(&self) -> settings::Settings<RawSecret>; fn event_handler(&self) -> EventsHandler; #[cfg(feature = "email")] - fn email_client(&self) -> Arc<dyn EmailService>; + fn email_client(&self) -> Arc<Box<dyn EmailService>>; fn add_request_id(&mut self, request_id: RequestId); fn add_flow_name(&mut self, flow_name: String); fn get_request_id(&self) -> Option<String>; @@ -232,7 +234,7 @@ impl AppStateInfo for AppState { self.conf.as_ref().to_owned() } #[cfg(feature = "email")] - fn email_client(&self) -> Arc<dyn EmailService> { + fn email_client(&self) -> Arc<Box<dyn EmailService>> { self.email_client.to_owned() } fn event_handler(&self) -> EventsHandler { @@ -258,11 +260,22 @@ impl AsRef<Self> for AppState { } #[cfg(feature = "email")] -pub async fn create_email_client(settings: &settings::Settings<RawSecret>) -> impl EmailService { - match settings.email.active_email_client { - external_services::email::AvailableEmailClients::SES => { - AwsSes::create(&settings.email, settings.proxy.https_url.to_owned()).await +pub async fn create_email_client( + settings: &settings::Settings<RawSecret>, +) -> Box<dyn EmailService> { + match &settings.email.client_config { + EmailClientConfigs::Ses { aws_ses } => Box::new( + AwsSes::create( + &settings.email, + aws_ses, + settings.proxy.https_url.to_owned(), + ) + .await, + ), + EmailClientConfigs::Smtp { smtp } => { + Box::new(SmtpServer::create(&settings.email, smtp.clone()).await) } + EmailClientConfigs::NoEmailClient => Box::new(NoEmailClient::create().await), } } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 934b072f14a..288e72164cf 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -384,7 +384,7 @@ public = { base_url = "http://localhost:8080", schema = "public", redis_key_pref sender_email = "example@example.com" aws_region = "" allowed_unverified_days = 1 -active_email_client = "SES" +active_email_client = "NO_EMAIL_CLIENT" recon_recipient_email = "recon@example.com" prod_intent_recipient_email = "business@example.com"
2024-11-19T19:55:34Z
## Description <!-- Describe your changes in detail --> Add SMTP support to allow mails through self-hosted/custom SMTP server #5156 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Hyperswitch currently supports only AWS SES to send emails, other open users who want to use some custom SMTP server will have no way to configure it. With this implementation users can change below config to use their own SMTP server. ``` [email] active_email_client = "SMTP" [email.smtp] host = "127.0.0.1" port = 1025 timeout = 10 connection = "plaintext" #currently plaintext and starttls are supported ``` ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Setup mailhog to test emails locally ```docker run -p 1025:1025 -p 8025:8025 mailhog/mailhog``` 1. Check if is possible to disable email with the env config ``` [email] active_email_client = "NO_EMAIL_CLIENT" ``` Start the server with `cargo r` and there should be no error 2. Check the SMTP server without authentication and No TLS with the above configs Start the server with `cargo r`, and there should be no error Start the dashboard and change the below config ``` [user] base_url = "http://localhost:9000" ``` - Check if signup email is sent correctly - Check if reset password email is sent correctly: Profile -> Reset Password - Check if Forgot password email is sent correctly - Check if magic link is working - Check if invite user email is sent correctly <img width="785" alt="Screenshot 2024-11-20 at 01 24 02" src="https://github.com/user-attachments/assets/feb21b27-07c4-4135-8ff2-bd114a704fcf"> <img width="1342" alt="Screenshot 2024-11-20 at 01 24 28" src="https://github.com/user-attachments/assets/7c141481-7a81-41cb-9253-b6fc2a6a07b7">
43d87913ab3d177a6d193b3e475c96609cc09a28
Setup mailhog to test emails locally ```docker run -p 1025:1025 -p 8025:8025 mailhog/mailhog``` 1. Check if is possible to disable email with the env config ``` [email] active_email_client = "NO_EMAIL_CLIENT" ``` Start the server with `cargo r` and there should be no error 2. Check the SMTP server without authentication and No TLS with the above configs Start the server with `cargo r`, and there should be no error Start the dashboard and change the below config ``` [user] base_url = "http://localhost:9000" ``` - Check if signup email is sent correctly - Check if reset password email is sent correctly: Profile -> Reset Password - Check if Forgot password email is sent correctly - Check if magic link is working - Check if invite user email is sent correctly <img width="785" alt="Screenshot 2024-11-20 at 01 24 02" src="https://github.com/user-attachments/assets/feb21b27-07c4-4135-8ff2-bd114a704fcf"> <img width="1342" alt="Screenshot 2024-11-20 at 01 24 28" src="https://github.com/user-attachments/assets/7c141481-7a81-41cb-9253-b6fc2a6a07b7">
[ "Cargo.lock", "config/development.toml", "config/docker_compose.toml", "crates/external_services/Cargo.toml", "crates/external_services/src/email.rs", "crates/external_services/src/email/no_email.rs", "crates/external_services/src/email/ses.rs", "crates/external_services/src/email/smtp.rs", "crates/router/src/configs/settings.rs", "crates/router/src/routes/app.rs", "loadtest/config/development.toml" ]
juspay/hyperswitch
juspay__hyperswitch-6615
Bug: feat(analytics): Add refund sessionized metrics for Analytics V2 dashboard Create the new refund sessionized metrics for Analytics V2 dashboard.
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index f56e875f720..cd870c12b23 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -16,7 +16,9 @@ use super::{ distribution::PaymentDistributionRow, filters::PaymentFilterRow, metrics::PaymentMetricRow, }, query::{Aggregate, ToSql, Window}, - refunds::{filters::RefundFilterRow, metrics::RefundMetricRow}, + refunds::{ + distribution::RefundDistributionRow, filters::RefundFilterRow, metrics::RefundMetricRow, + }, sdk_events::{filters::SdkEventFilter, metrics::SdkEventMetricRow}, types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, QueryExecutionError}, }; @@ -170,6 +172,7 @@ impl super::payment_intents::filters::PaymentIntentFilterAnalytics for Clickhous impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for ClickhouseClient {} impl super::refunds::metrics::RefundMetricAnalytics for ClickhouseClient {} impl super::refunds::filters::RefundFilterAnalytics for ClickhouseClient {} +impl super::refunds::distribution::RefundDistributionAnalytics for ClickhouseClient {} impl super::frm::metrics::FrmMetricAnalytics for ClickhouseClient {} impl super::frm::filters::FrmFilterAnalytics for ClickhouseClient {} impl super::sdk_events::filters::SdkEventFilterAnalytics for ClickhouseClient {} @@ -300,6 +303,16 @@ impl TryInto<RefundFilterRow> for serde_json::Value { } } +impl TryInto<RefundDistributionRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<RefundDistributionRow, Self::Error> { + serde_json::from_value(self).change_context(ParsingError::StructParseFailure( + "Failed to parse RefundDistributionRow in clickhouse results", + )) + } +} + impl TryInto<FrmMetricRow> for serde_json::Value { type Error = Report<ParsingError>; diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 224cd82ccd3..13fdefe864d 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -29,6 +29,7 @@ use hyperswitch_interfaces::secrets_interface::{ secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; +use refunds::distribution::{RefundDistribution, RefundDistributionRow}; pub use types::AnalyticsDomain; pub mod lambda_utils; pub mod utils; @@ -52,7 +53,7 @@ use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetrics, SdkEventMetricsBucketIdentifier, }, - Distribution, Granularity, TimeRange, + Granularity, PaymentDistributionBody, RefundDistributionBody, TimeRange, }; use clickhouse::ClickhouseClient; pub use clickhouse::ClickhouseConfig; @@ -215,7 +216,7 @@ impl AnalyticsProvider { pub async fn get_payment_distribution( &self, - distribution: &Distribution, + distribution: &PaymentDistributionBody, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, @@ -528,6 +529,116 @@ impl AnalyticsProvider { .await } + pub async fn get_refund_distribution( + &self, + distribution: &RefundDistributionBody, + dimensions: &[RefundDimensions], + auth: &AuthInfo, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + ) -> types::MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> { + // Metrics to get the fetch time for each payment metric + metrics::request::record_operation_time( + async { + match self { + Self::Sqlx(pool) => { + distribution.distribution_for + .load_distribution( + distribution, + dimensions, + auth, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::Clickhouse(pool) => { + distribution.distribution_for + .load_distribution( + distribution, + dimensions, + auth, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::CombinedCkh(sqlx_pool, ckh_pool) => { + let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for + .load_distribution( + distribution, + dimensions, + auth, + filters, + granularity, + time_range, + ckh_pool, + ), + distribution.distribution_for + .load_distribution( + distribution, + dimensions, + auth, + filters, + granularity, + time_range, + sqlx_pool, + )); + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution") + }, + _ => {} + + }; + + ckh_result + } + Self::CombinedSqlx(sqlx_pool, ckh_pool) => { + let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for + .load_distribution( + distribution, + dimensions, + auth, + filters, + granularity, + time_range, + ckh_pool, + ), + distribution.distribution_for + .load_distribution( + distribution, + dimensions, + auth, + filters, + granularity, + time_range, + sqlx_pool, + )); + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution") + }, + _ => {} + + }; + + sqlx_result + } + } + }, + &metrics::METRIC_FETCH_TIME, + &distribution.distribution_for, + self, + ) + .await + } + pub async fn get_frm_metrics( &self, metric: &FrmMetrics, diff --git a/crates/analytics/src/payments/distribution.rs b/crates/analytics/src/payments/distribution.rs index 213b6244574..055572a0805 100644 --- a/crates/analytics/src/payments/distribution.rs +++ b/crates/analytics/src/payments/distribution.rs @@ -2,7 +2,7 @@ use api_models::analytics::{ payments::{ PaymentDimensions, PaymentDistributions, PaymentFilters, PaymentMetricsBucketIdentifier, }, - Distribution, Granularity, TimeRange, + Granularity, PaymentDistributionBody, TimeRange, }; use diesel_models::enums as storage_enums; use time::PrimitiveDateTime; @@ -53,7 +53,7 @@ where #[allow(clippy::too_many_arguments)] async fn load_distribution( &self, - distribution: &Distribution, + distribution: &PaymentDistributionBody, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, @@ -75,7 +75,7 @@ where { async fn load_distribution( &self, - distribution: &Distribution, + distribution: &PaymentDistributionBody, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, diff --git a/crates/analytics/src/payments/distribution/payment_error_message.rs b/crates/analytics/src/payments/distribution/payment_error_message.rs index 241754ee041..de5cb3ae5e8 100644 --- a/crates/analytics/src/payments/distribution/payment_error_message.rs +++ b/crates/analytics/src/payments/distribution/payment_error_message.rs @@ -1,6 +1,6 @@ use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, - Distribution, Granularity, TimeRange, + Granularity, PaymentDistributionBody, TimeRange, }; use common_utils::errors::ReportSwitchExt; use diesel_models::enums as storage_enums; @@ -31,7 +31,7 @@ where { async fn load_distribution( &self, - distribution: &Distribution, + distribution: &PaymentDistributionBody, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index caa112ec175..cbb0cf6737c 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -9,7 +9,7 @@ use api_models::{ frm::{FrmDimensions, FrmTransactionType}, payment_intents::PaymentIntentDimensions, payments::{PaymentDimensions, PaymentDistributions}, - refunds::{RefundDimensions, RefundType}, + refunds::{RefundDimensions, RefundDistributions, RefundType}, sdk_events::{SdkEventDimensions, SdkEventNames}, Granularity, }, @@ -488,6 +488,7 @@ impl_to_sql_for_to_string!( PaymentIntentDimensions, &PaymentDistributions, RefundDimensions, + &RefundDistributions, FrmDimensions, PaymentMethod, PaymentMethodType, diff --git a/crates/analytics/src/refunds.rs b/crates/analytics/src/refunds.rs index 590dc148ebf..ed6f396ccec 100644 --- a/crates/analytics/src/refunds.rs +++ b/crates/analytics/src/refunds.rs @@ -1,6 +1,7 @@ pub mod accumulator; mod core; +pub mod distribution; pub mod filters; pub mod metrics; pub mod types; diff --git a/crates/analytics/src/refunds/accumulator.rs b/crates/analytics/src/refunds/accumulator.rs index add38c98162..840d46bbab7 100644 --- a/crates/analytics/src/refunds/accumulator.rs +++ b/crates/analytics/src/refunds/accumulator.rs @@ -1,19 +1,56 @@ -use api_models::analytics::refunds::RefundMetricsBucketValue; +use api_models::analytics::refunds::{ + ErrorMessagesResult, ReasonsResult, RefundMetricsBucketValue, +}; +use bigdecimal::ToPrimitive; use diesel_models::enums as storage_enums; -use super::metrics::RefundMetricRow; +use super::{distribution::RefundDistributionRow, metrics::RefundMetricRow}; #[derive(Debug, Default)] pub struct RefundMetricsAccumulator { pub refund_success_rate: SuccessRateAccumulator, pub refund_count: CountAccumulator, pub refund_success: CountAccumulator, - pub processed_amount: PaymentProcessedAmountAccumulator, + pub processed_amount: RefundProcessedAmountAccumulator, + pub refund_reason: RefundReasonAccumulator, + pub refund_reason_distribution: RefundReasonDistributionAccumulator, + pub refund_error_message: RefundReasonAccumulator, + pub refund_error_message_distribution: RefundErrorMessageDistributionAccumulator, } #[derive(Debug, Default)] -pub struct SuccessRateAccumulator { - pub success: i64, +pub struct RefundReasonDistributionRow { + pub count: i64, + pub total: i64, + pub refund_reason: String, +} + +#[derive(Debug, Default)] +pub struct RefundReasonDistributionAccumulator { + pub refund_reason_vec: Vec<RefundReasonDistributionRow>, +} + +#[derive(Debug, Default)] +pub struct RefundErrorMessageDistributionRow { + pub count: i64, pub total: i64, + pub refund_error_message: String, +} + +#[derive(Debug, Default)] +pub struct RefundErrorMessageDistributionAccumulator { + pub refund_error_message_vec: Vec<RefundErrorMessageDistributionRow>, +} + +#[derive(Debug, Default)] +#[repr(transparent)] +pub struct RefundReasonAccumulator { + pub count: u64, +} + +#[derive(Debug, Default)] +pub struct SuccessRateAccumulator { + pub success: u32, + pub total: u32, } #[derive(Debug, Default)] #[repr(transparent)] @@ -21,8 +58,8 @@ pub struct CountAccumulator { pub count: Option<i64>, } #[derive(Debug, Default)] -#[repr(transparent)] -pub struct PaymentProcessedAmountAccumulator { +pub struct RefundProcessedAmountAccumulator { + pub count: Option<i64>, pub total: Option<i64>, } @@ -34,6 +71,93 @@ pub trait RefundMetricAccumulator { fn collect(self) -> Self::MetricOutput; } +pub trait RefundDistributionAccumulator { + type DistributionOutput; + + fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow); + + fn collect(self) -> Self::DistributionOutput; +} + +impl RefundDistributionAccumulator for RefundReasonDistributionAccumulator { + type DistributionOutput = Option<Vec<ReasonsResult>>; + + fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow) { + self.refund_reason_vec.push(RefundReasonDistributionRow { + count: distribution.count.unwrap_or_default(), + total: distribution + .total + .clone() + .map(|i| i.to_i64().unwrap_or_default()) + .unwrap_or_default(), + refund_reason: distribution.refund_reason.clone().unwrap_or_default(), + }) + } + + fn collect(mut self) -> Self::DistributionOutput { + if self.refund_reason_vec.is_empty() { + None + } else { + self.refund_reason_vec.sort_by(|a, b| b.count.cmp(&a.count)); + let mut res: Vec<ReasonsResult> = Vec::new(); + for val in self.refund_reason_vec.into_iter() { + let perc = f64::from(u32::try_from(val.count).ok()?) * 100.0 + / f64::from(u32::try_from(val.total).ok()?); + + res.push(ReasonsResult { + reason: val.refund_reason, + count: val.count, + percentage: (perc * 100.0).round() / 100.0, + }) + } + + Some(res) + } + } +} + +impl RefundDistributionAccumulator for RefundErrorMessageDistributionAccumulator { + type DistributionOutput = Option<Vec<ErrorMessagesResult>>; + + fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow) { + self.refund_error_message_vec + .push(RefundErrorMessageDistributionRow { + count: distribution.count.unwrap_or_default(), + total: distribution + .total + .clone() + .map(|i| i.to_i64().unwrap_or_default()) + .unwrap_or_default(), + refund_error_message: distribution + .refund_error_message + .clone() + .unwrap_or_default(), + }) + } + + fn collect(mut self) -> Self::DistributionOutput { + if self.refund_error_message_vec.is_empty() { + None + } else { + self.refund_error_message_vec + .sort_by(|a, b| b.count.cmp(&a.count)); + let mut res: Vec<ErrorMessagesResult> = Vec::new(); + for val in self.refund_error_message_vec.into_iter() { + let perc = f64::from(u32::try_from(val.count).ok()?) * 100.0 + / f64::from(u32::try_from(val.total).ok()?); + + res.push(ErrorMessagesResult { + error_message: val.refund_error_message, + count: val.count, + percentage: (perc * 100.0).round() / 100.0, + }) + } + + Some(res) + } + } +} + impl RefundMetricAccumulator for CountAccumulator { type MetricOutput = Option<u64>; #[inline] @@ -50,62 +174,103 @@ impl RefundMetricAccumulator for CountAccumulator { } } -impl RefundMetricAccumulator for PaymentProcessedAmountAccumulator { - type MetricOutput = (Option<u64>, Option<u64>); +impl RefundMetricAccumulator for RefundProcessedAmountAccumulator { + type MetricOutput = (Option<u64>, Option<u64>, Option<u64>); #[inline] fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) { self.total = match ( self.total, - metrics - .total - .as_ref() - .and_then(bigdecimal::ToPrimitive::to_i64), + metrics.total.as_ref().and_then(ToPrimitive::to_i64), ) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), - } + }; + + self.count = match (self.count, metrics.count) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + }; } #[inline] fn collect(self) -> Self::MetricOutput { - (self.total.and_then(|i| u64::try_from(i).ok()), Some(0)) + let total = u64::try_from(self.total.unwrap_or_default()).ok(); + let count = self.count.and_then(|i| u64::try_from(i).ok()); + + (total, count, Some(0)) } } impl RefundMetricAccumulator for SuccessRateAccumulator { - type MetricOutput = Option<f64>; + type MetricOutput = (Option<u32>, Option<u32>, Option<f64>); fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) { if let Some(ref refund_status) = metrics.refund_status { if refund_status.as_ref() == &storage_enums::RefundStatus::Success { - self.success += metrics.count.unwrap_or_default(); + if let Some(success) = metrics + .count + .and_then(|success| u32::try_from(success).ok()) + { + self.success += success; + } } }; - self.total += metrics.count.unwrap_or_default(); + if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) { + self.total += total; + } } fn collect(self) -> Self::MetricOutput { - if self.total <= 0 { - None + if self.total == 0 { + (None, None, None) } else { - Some( - f64::from(u32::try_from(self.success).ok()?) * 100.0 - / f64::from(u32::try_from(self.total).ok()?), - ) + let success = Some(self.success); + let total = Some(self.total); + let success_rate = match (success, total) { + (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + (success, total, success_rate) + } + } +} + +impl RefundMetricAccumulator for RefundReasonAccumulator { + type MetricOutput = Option<u64>; + + fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) { + if let Some(count) = metrics.count { + if let Ok(count_u64) = u64::try_from(count) { + self.count += count_u64; + } } } + + fn collect(self) -> Self::MetricOutput { + Some(self.count) + } } impl RefundMetricsAccumulator { pub fn collect(self) -> RefundMetricsBucketValue { - let (refund_processed_amount, refund_processed_amount_in_usd) = + let (successful_refunds, total_refunds, refund_success_rate) = + self.refund_success_rate.collect(); + let (refund_processed_amount, refund_processed_count, refund_processed_amount_in_usd) = self.processed_amount.collect(); RefundMetricsBucketValue { - refund_success_rate: self.refund_success_rate.collect(), + successful_refunds, + total_refunds, + refund_success_rate, refund_count: self.refund_count.collect(), refund_success_count: self.refund_success.collect(), refund_processed_amount, refund_processed_amount_in_usd, + refund_processed_count, + refund_reason_distribution: self.refund_reason_distribution.collect(), + refund_error_message_distribution: self.refund_error_message_distribution.collect(), + refund_reason_count: self.refund_reason.collect(), + refund_error_message_count: self.refund_error_message.collect(), } } } diff --git a/crates/analytics/src/refunds/core.rs b/crates/analytics/src/refunds/core.rs index e3bfa4da9d1..205600b9259 100644 --- a/crates/analytics/src/refunds/core.rs +++ b/crates/analytics/src/refunds/core.rs @@ -1,15 +1,17 @@ #![allow(dead_code)] -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use api_models::analytics::{ refunds::{ - RefundDimensions, RefundMetrics, RefundMetricsBucketIdentifier, RefundMetricsBucketResponse, + RefundDimensions, RefundDistributions, RefundMetrics, RefundMetricsBucketIdentifier, + RefundMetricsBucketResponse, }, GetRefundFilterRequest, GetRefundMetricRequest, RefundFilterValue, RefundFiltersResponse, RefundsAnalyticsMetadata, RefundsMetricsResponse, }; use bigdecimal::ToPrimitive; use common_enums::Currency; +use common_utils::errors::CustomResult; use currency_conversion::{conversion::convert, types::ExchangeRates}; use error_stack::ResultExt; use router_env::{ @@ -19,17 +21,31 @@ use router_env::{ }; use super::{ + distribution::RefundDistributionRow, filters::{get_refund_filter_for_dimension, RefundFilterRow}, + metrics::RefundMetricRow, RefundMetricsAccumulator, }; use crate::{ enums::AuthInfo, errors::{AnalyticsError, AnalyticsResult}, metrics, - refunds::RefundMetricAccumulator, + refunds::{accumulator::RefundDistributionAccumulator, RefundMetricAccumulator}, AnalyticsProvider, }; +#[derive(Debug)] +pub enum TaskType { + MetricTask( + RefundMetrics, + CustomResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, AnalyticsError>, + ), + DistributionTask( + RefundDistributions, + CustomResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>, AnalyticsError>, + ), +} + pub async fn get_metrics( pool: &AnalyticsProvider, ex_rates: &ExchangeRates, @@ -62,65 +78,145 @@ pub async fn get_metrics( ) .await .change_context(AnalyticsError::UnknownError); - (metric_type, data) + TaskType::MetricTask(metric_type, data) + } + .instrument(task_span), + ); + } + + if let Some(distribution) = req.clone().distribution { + let req = req.clone(); + let pool = pool.clone(); + let task_span = tracing::debug_span!( + "analytics_refunds_distribution_query", + refund_distribution = distribution.distribution_for.as_ref() + ); + + let auth_scoped = auth.to_owned(); + set.spawn( + async move { + let data = pool + .get_refund_distribution( + &distribution, + &req.group_by_names.clone(), + &auth_scoped, + &req.filters, + &req.time_series.map(|t| t.granularity), + &req.time_range, + ) + .await + .change_context(AnalyticsError::UnknownError); + TaskType::DistributionTask(distribution.distribution_for, data) } .instrument(task_span), ); } - while let Some((metric, data)) = set + while let Some(task_type) = set .join_next() .await .transpose() .change_context(AnalyticsError::UnknownError)? { - let data = data?; - let attributes = &add_attributes([ - ("metric_type", metric.to_string()), - ("source", pool.to_string()), - ]); - - let value = u64::try_from(data.len()); - if let Ok(val) = value { - metrics::BUCKETS_FETCHED.record(&metrics::CONTEXT, val, attributes); - logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val); - } + match task_type { + TaskType::MetricTask(metric, data) => { + let data = data?; + let attributes = &add_attributes([ + ("metric_type", metric.to_string()), + ("source", pool.to_string()), + ]); - for (id, value) in data { - logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}"); - let metrics_builder = metrics_accumulator.entry(id).or_default(); - match metric { - RefundMetrics::RefundSuccessRate | RefundMetrics::SessionizedRefundSuccessRate => { - metrics_builder - .refund_success_rate - .add_metrics_bucket(&value) + let value = u64::try_from(data.len()); + if let Ok(val) = value { + metrics::BUCKETS_FETCHED.record(&metrics::CONTEXT, val, attributes); + logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val); } - RefundMetrics::RefundCount | RefundMetrics::SessionizedRefundCount => { - metrics_builder.refund_count.add_metrics_bucket(&value) + + for (id, value) in data { + logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}"); + let metrics_builder = metrics_accumulator.entry(id).or_default(); + match metric { + RefundMetrics::RefundSuccessRate + | RefundMetrics::SessionizedRefundSuccessRate => metrics_builder + .refund_success_rate + .add_metrics_bucket(&value), + RefundMetrics::RefundCount | RefundMetrics::SessionizedRefundCount => { + metrics_builder.refund_count.add_metrics_bucket(&value) + } + RefundMetrics::RefundSuccessCount + | RefundMetrics::SessionizedRefundSuccessCount => { + metrics_builder.refund_success.add_metrics_bucket(&value) + } + RefundMetrics::RefundProcessedAmount + | RefundMetrics::SessionizedRefundProcessedAmount => { + metrics_builder.processed_amount.add_metrics_bucket(&value) + } + RefundMetrics::SessionizedRefundReason => { + metrics_builder.refund_reason.add_metrics_bucket(&value) + } + RefundMetrics::SessionizedRefundErrorMessage => metrics_builder + .refund_error_message + .add_metrics_bucket(&value), + } } - RefundMetrics::RefundSuccessCount - | RefundMetrics::SessionizedRefundSuccessCount => { - metrics_builder.refund_success.add_metrics_bucket(&value) + + logger::debug!( + "Analytics Accumulated Results: metric: {}, results: {:#?}", + metric, + metrics_accumulator + ); + } + TaskType::DistributionTask(distribution, data) => { + let data = data?; + let attributes = &add_attributes([ + ("distribution_type", distribution.to_string()), + ("source", pool.to_string()), + ]); + let value = u64::try_from(data.len()); + if let Ok(val) = value { + metrics::BUCKETS_FETCHED.record(&metrics::CONTEXT, val, attributes); + logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val); } - RefundMetrics::RefundProcessedAmount - | RefundMetrics::SessionizedRefundProcessedAmount => { - metrics_builder.processed_amount.add_metrics_bucket(&value) + + for (id, value) in data { + logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for distribution {distribution}"); + + let metrics_builder = metrics_accumulator.entry(id).or_default(); + match distribution { + RefundDistributions::SessionizedRefundReason => metrics_builder + .refund_reason_distribution + .add_distribution_bucket(&value), + RefundDistributions::SessionizedRefundErrorMessage => metrics_builder + .refund_error_message_distribution + .add_distribution_bucket(&value), + } } + logger::debug!( + "Analytics Accumulated Results: distribution: {}, results: {:#?}", + distribution, + metrics_accumulator + ); } } - - logger::debug!( - "Analytics Accumulated Results: metric: {}, results: {:#?}", - metric, - metrics_accumulator - ); } + + let mut success = 0; + let mut total = 0; let mut total_refund_processed_amount = 0; let mut total_refund_processed_amount_in_usd = 0; + let mut total_refund_processed_count = 0; + let mut total_refund_reason_count = 0; + let mut total_refund_error_message_count = 0; let query_data: Vec<RefundMetricsBucketResponse> = metrics_accumulator .into_iter() .map(|(id, val)| { let mut collected_values = val.collect(); + if let Some(success_count) = collected_values.successful_refunds { + success += success_count; + } + if let Some(total_count) = collected_values.total_refunds { + total += total_count; + } if let Some(amount) = collected_values.refund_processed_amount { let amount_in_usd = id .currency @@ -142,18 +238,34 @@ pub async fn get_metrics( total_refund_processed_amount += amount; total_refund_processed_amount_in_usd += amount_in_usd.unwrap_or(0); } + if let Some(count) = collected_values.refund_processed_count { + total_refund_processed_count += count; + } + if let Some(total_count) = collected_values.refund_reason_count { + total_refund_reason_count += total_count; + } + if let Some(total_count) = collected_values.refund_error_message_count { + total_refund_error_message_count += total_count; + } RefundMetricsBucketResponse { values: collected_values, dimensions: id, } }) .collect(); - + let total_refund_success_rate = match (success, total) { + (s, t) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; Ok(RefundsMetricsResponse { query_data, meta_data: [RefundsAnalyticsMetadata { + total_refund_success_rate, total_refund_processed_amount: Some(total_refund_processed_amount), total_refund_processed_amount_in_usd: Some(total_refund_processed_amount_in_usd), + total_refund_processed_count: Some(total_refund_processed_count), + total_refund_reason_count: Some(total_refund_reason_count), + total_refund_error_message_count: Some(total_refund_error_message_count), }], }) } @@ -229,6 +341,8 @@ pub async fn get_filters( RefundDimensions::Connector => fil.connector, RefundDimensions::RefundType => fil.refund_type.map(|i| i.as_ref().to_string()), RefundDimensions::ProfileId => fil.profile_id, + RefundDimensions::RefundReason => fil.refund_reason, + RefundDimensions::RefundErrorMessage => fil.refund_error_message, }) .collect::<Vec<String>>(); res.query_data.push(RefundFilterValue { diff --git a/crates/analytics/src/refunds/distribution.rs b/crates/analytics/src/refunds/distribution.rs new file mode 100644 index 00000000000..962f74acd1a --- /dev/null +++ b/crates/analytics/src/refunds/distribution.rs @@ -0,0 +1,105 @@ +use api_models::analytics::{ + refunds::{ + RefundDimensions, RefundDistributions, RefundFilters, RefundMetricsBucketIdentifier, + RefundType, + }, + Granularity, RefundDistributionBody, TimeRange, +}; +use diesel_models::enums as storage_enums; +use time::PrimitiveDateTime; + +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, +}; + +mod sessionized_distribution; + +#[derive(Debug, PartialEq, Eq, serde::Deserialize)] +pub struct RefundDistributionRow { + pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, + pub refund_status: Option<DBEnumWrapper<storage_enums::RefundStatus>>, + pub connector: Option<String>, + pub refund_type: Option<DBEnumWrapper<RefundType>>, + pub profile_id: Option<String>, + pub total: Option<bigdecimal::BigDecimal>, + pub count: Option<i64>, + pub refund_reason: Option<String>, + pub refund_error_message: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub start_bucket: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub end_bucket: Option<PrimitiveDateTime>, +} + +pub trait RefundDistributionAnalytics: LoadRow<RefundDistributionRow> {} + +#[async_trait::async_trait] +pub trait RefundDistribution<T> +where + T: AnalyticsDataSource + RefundDistributionAnalytics, +{ + #[allow(clippy::too_many_arguments)] + async fn load_distribution( + &self, + distribution: &RefundDistributionBody, + dimensions: &[RefundDimensions], + auth: &AuthInfo, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>>; +} + +#[async_trait::async_trait] +impl<T> RefundDistribution<T> for RefundDistributions +where + T: AnalyticsDataSource + RefundDistributionAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_distribution( + &self, + distribution: &RefundDistributionBody, + dimensions: &[RefundDimensions], + auth: &AuthInfo, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> { + match self { + Self::SessionizedRefundReason => { + sessionized_distribution::RefundReason + .load_distribution( + distribution, + dimensions, + auth, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::SessionizedRefundErrorMessage => { + sessionized_distribution::RefundErrorMessage + .load_distribution( + distribution, + dimensions, + auth, + filters, + granularity, + time_range, + pool, + ) + .await + } + } + } +} diff --git a/crates/analytics/src/refunds/distribution/sessionized_distribution.rs b/crates/analytics/src/refunds/distribution/sessionized_distribution.rs new file mode 100644 index 00000000000..391b855e96e --- /dev/null +++ b/crates/analytics/src/refunds/distribution/sessionized_distribution.rs @@ -0,0 +1,7 @@ +mod refund_error_message; +mod refund_reason; + +pub(super) use refund_error_message::RefundErrorMessage; +pub(super) use refund_reason::RefundReason; + +pub use super::{RefundDistribution, RefundDistributionAnalytics, RefundDistributionRow}; diff --git a/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_error_message.rs b/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_error_message.rs new file mode 100644 index 00000000000..a4268c86cbe --- /dev/null +++ b/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_error_message.rs @@ -0,0 +1,177 @@ +use api_models::analytics::{ + refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, + Granularity, RefundDistributionBody, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::{RefundDistribution, RefundDistributionRow}; +use crate::{ + enums::AuthInfo, + query::{ + Aggregate, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct RefundErrorMessage; + +#[async_trait::async_trait] +impl<T> RefundDistribution<T> for RefundErrorMessage +where + T: AnalyticsDataSource + super::RefundDistributionAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_distribution( + &self, + distribution: &RefundDistributionBody, + dimensions: &[RefundDimensions], + auth: &AuthInfo, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::RefundSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(&distribution.distribution_for) + .switch()?; + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + query_builder + .add_filter_clause( + RefundDimensions::RefundStatus, + storage_enums::RefundStatus::Failure, + ) + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + query_builder + .add_group_by_clause(&distribution.distribution_for) + .attach_printable("Error grouping by distribution_for") + .switch()?; + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + for dim in dimensions.iter() { + query_builder.add_outer_select_column(dim).switch()?; + } + + query_builder + .add_outer_select_column(&distribution.distribution_for) + .switch()?; + query_builder.add_outer_select_column("count").switch()?; + query_builder + .add_outer_select_column("start_bucket") + .switch()?; + query_builder + .add_outer_select_column("end_bucket") + .switch()?; + let sql_dimensions = query_builder.transform_to_sql_values(dimensions).switch()?; + + query_builder + .add_outer_select_column(Window::Sum { + field: "count", + partition_by: Some(sql_dimensions), + order_by: None, + alias: Some("total"), + }) + .switch()?; + + query_builder + .add_top_n_clause( + dimensions, + distribution.distribution_cardinality.into(), + "count", + Order::Descending, + ) + .switch()?; + + query_builder + .execute_query::<RefundDistributionRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + RefundMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + i.refund_status.as_ref().map(|i| i.0.to_string()), + i.connector.clone(), + i.refund_type.as_ref().map(|i| i.0.to_string()), + i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_reason.rs b/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_reason.rs new file mode 100644 index 00000000000..a2a933db8cb --- /dev/null +++ b/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_reason.rs @@ -0,0 +1,169 @@ +use api_models::analytics::{ + refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, + Granularity, RefundDistributionBody, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::{RefundDistribution, RefundDistributionRow}; +use crate::{ + enums::AuthInfo, + query::{ + Aggregate, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct RefundReason; + +#[async_trait::async_trait] +impl<T> RefundDistribution<T> for RefundReason +where + T: AnalyticsDataSource + super::RefundDistributionAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_distribution( + &self, + distribution: &RefundDistributionBody, + dimensions: &[RefundDimensions], + auth: &AuthInfo, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::RefundSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(&distribution.distribution_for) + .switch()?; + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + query_builder + .add_group_by_clause(&distribution.distribution_for) + .attach_printable("Error grouping by distribution_for") + .switch()?; + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + for dim in dimensions.iter() { + query_builder.add_outer_select_column(dim).switch()?; + } + + query_builder + .add_outer_select_column(&distribution.distribution_for) + .switch()?; + query_builder.add_outer_select_column("count").switch()?; + query_builder + .add_outer_select_column("start_bucket") + .switch()?; + query_builder + .add_outer_select_column("end_bucket") + .switch()?; + let sql_dimensions = query_builder.transform_to_sql_values(dimensions).switch()?; + + query_builder + .add_outer_select_column(Window::Sum { + field: "count", + partition_by: Some(sql_dimensions), + order_by: None, + alias: Some("total"), + }) + .switch()?; + + query_builder + .add_top_n_clause( + dimensions, + distribution.distribution_cardinality.into(), + "count", + Order::Descending, + ) + .switch()?; + + query_builder + .execute_query::<RefundDistributionRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + RefundMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + i.refund_status.as_ref().map(|i| i.0.to_string()), + i.connector.clone(), + i.refund_type.as_ref().map(|i| i.0.to_string()), + i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/refunds/filters.rs b/crates/analytics/src/refunds/filters.rs index d87a778ebf3..b742187c4e6 100644 --- a/crates/analytics/src/refunds/filters.rs +++ b/crates/analytics/src/refunds/filters.rs @@ -56,4 +56,6 @@ pub struct RefundFilterRow { pub connector: Option<String>, pub refund_type: Option<DBEnumWrapper<RefundType>>, pub profile_id: Option<String>, + pub refund_reason: Option<String>, + pub refund_error_message: Option<String>, } diff --git a/crates/analytics/src/refunds/metrics.rs b/crates/analytics/src/refunds/metrics.rs index c211ea82d7a..57e6511d92c 100644 --- a/crates/analytics/src/refunds/metrics.rs +++ b/crates/analytics/src/refunds/metrics.rs @@ -31,6 +31,8 @@ pub struct RefundMetricRow { pub connector: Option<String>, pub refund_type: Option<DBEnumWrapper<RefundType>>, pub profile_id: Option<String>, + pub refund_reason: Option<String>, + pub refund_error_message: Option<String>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, #[serde(with = "common_utils::custom_serde::iso8601::option")] @@ -122,6 +124,16 @@ where .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } + Self::SessionizedRefundReason => { + sessionized_metrics::RefundReason + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedRefundErrorMessage => { + sessionized_metrics::RefundErrorMessage + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } } } } diff --git a/crates/analytics/src/refunds/metrics/refund_count.rs b/crates/analytics/src/refunds/metrics/refund_count.rs index 07de04c5898..7079993094d 100644 --- a/crates/analytics/src/refunds/metrics/refund_count.rs +++ b/crates/analytics/src/refunds/metrics/refund_count.rs @@ -99,6 +99,8 @@ where i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs index 6cba5f58fed..3890b8be6e9 100644 --- a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs +++ b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs @@ -107,6 +107,8 @@ where i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/refunds/metrics/refund_success_count.rs b/crates/analytics/src/refunds/metrics/refund_success_count.rs index 642cf70580d..4c3f600b05c 100644 --- a/crates/analytics/src/refunds/metrics/refund_success_count.rs +++ b/crates/analytics/src/refunds/metrics/refund_success_count.rs @@ -102,6 +102,8 @@ where i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/refunds/metrics/refund_success_rate.rs b/crates/analytics/src/refunds/metrics/refund_success_rate.rs index 7b5716ba41a..8ed144999a7 100644 --- a/crates/analytics/src/refunds/metrics/refund_success_rate.rs +++ b/crates/analytics/src/refunds/metrics/refund_success_rate.rs @@ -97,6 +97,8 @@ where i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics.rs index bb404cd3410..3a5195be6c9 100644 --- a/crates/analytics/src/refunds/metrics/sessionized_metrics.rs +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics.rs @@ -1,10 +1,14 @@ mod refund_count; +mod refund_error_message; mod refund_processed_amount; +mod refund_reason; mod refund_success_count; mod refund_success_rate; pub(super) use refund_count::RefundCount; +pub(super) use refund_error_message::RefundErrorMessage; pub(super) use refund_processed_amount::RefundProcessedAmount; +pub(super) use refund_reason::RefundReason; pub(super) use refund_success_count::RefundSuccessCount; pub(super) use refund_success_rate::RefundSuccessRate; diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs index c77e1f7a52c..20989daca7d 100644 --- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs @@ -100,6 +100,8 @@ where i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs new file mode 100644 index 00000000000..72e32907efb --- /dev/null +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs @@ -0,0 +1,190 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::RefundMetricRow; +use crate::{ + enums::AuthInfo, + query::{ + Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, + ToSql, Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct RefundErrorMessage; + +#[async_trait::async_trait] +impl<T> super::RefundMetric<T> for RefundErrorMessage +where + T: AnalyticsDataSource + super::RefundMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[RefundDimensions], + auth: &AuthInfo, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { + let mut inner_query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::RefundSessionized); + inner_query_builder + .add_select_column("sum(sign_flag)") + .switch()?; + + inner_query_builder + .add_custom_filter_clause( + RefundDimensions::RefundErrorMessage, + "NULL", + FilterTypes::IsNotNull, + ) + .switch()?; + + time_range + .set_filter_clause(&mut inner_query_builder) + .attach_printable("Error filtering time range for inner query") + .switch()?; + + let inner_query_string = inner_query_builder + .build_query() + .attach_printable("Error building inner query") + .change_context(MetricsError::QueryBuildingError)?; + + let mut outer_query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::RefundSessionized); + + for dim in dimensions.iter() { + outer_query_builder.add_select_column(dim).switch()?; + } + + outer_query_builder + .add_select_column("sum(sign_flag) AS count") + .switch()?; + + outer_query_builder + .add_select_column(format!("({}) AS total", inner_query_string)) + .switch()?; + + outer_query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + + outer_query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters + .set_filter_clause(&mut outer_query_builder) + .switch()?; + + auth.set_filter_clause(&mut outer_query_builder).switch()?; + + time_range + .set_filter_clause(&mut outer_query_builder) + .attach_printable("Error filtering time range for outer query") + .switch()?; + + outer_query_builder + .add_filter_clause( + RefundDimensions::RefundStatus, + storage_enums::RefundStatus::Failure, + ) + .switch()?; + + outer_query_builder + .add_custom_filter_clause( + RefundDimensions::RefundErrorMessage, + "NULL", + FilterTypes::IsNotNull, + ) + .switch()?; + + for dim in dimensions.iter() { + outer_query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut outer_query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + outer_query_builder + .add_order_by_clause("count", Order::Descending) + .attach_printable("Error adding order by clause") + .switch()?; + + let filtered_dimensions: Vec<&RefundDimensions> = dimensions + .iter() + .filter(|&&dim| dim != RefundDimensions::RefundErrorMessage) + .collect(); + + for dim in &filtered_dimensions { + outer_query_builder + .add_order_by_clause(*dim, Order::Ascending) + .attach_printable("Error adding order by clause") + .switch()?; + } + + outer_query_builder + .execute_query::<RefundMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + RefundMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.refund_type.as_ref().map(|i| i.0.to_string()), + i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs index c91938228af..93880824ef9 100644 --- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs @@ -47,6 +47,12 @@ where query_builder.add_select_column(dim).switch()?; } + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; query_builder .add_select_column(Aggregate::Sum { field: "refund_amount", @@ -109,6 +115,8 @@ where i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs new file mode 100644 index 00000000000..0df28901e8f --- /dev/null +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs @@ -0,0 +1,182 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::RefundMetricRow; +use crate::{ + enums::AuthInfo, + query::{ + Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, + ToSql, Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct RefundReason; + +#[async_trait::async_trait] +impl<T> super::RefundMetric<T> for RefundReason +where + T: AnalyticsDataSource + super::RefundMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[RefundDimensions], + auth: &AuthInfo, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { + let mut inner_query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::RefundSessionized); + inner_query_builder + .add_select_column("sum(sign_flag)") + .switch()?; + + inner_query_builder + .add_custom_filter_clause( + RefundDimensions::RefundReason, + "NULL", + FilterTypes::IsNotNull, + ) + .switch()?; + + time_range + .set_filter_clause(&mut inner_query_builder) + .attach_printable("Error filtering time range for inner query") + .switch()?; + + let inner_query_string = inner_query_builder + .build_query() + .attach_printable("Error building inner query") + .change_context(MetricsError::QueryBuildingError)?; + + let mut outer_query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::RefundSessionized); + + for dim in dimensions.iter() { + outer_query_builder.add_select_column(dim).switch()?; + } + + outer_query_builder + .add_select_column("sum(sign_flag) AS count") + .switch()?; + + outer_query_builder + .add_select_column(format!("({}) AS total", inner_query_string)) + .switch()?; + + outer_query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + + outer_query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters + .set_filter_clause(&mut outer_query_builder) + .switch()?; + + auth.set_filter_clause(&mut outer_query_builder).switch()?; + + time_range + .set_filter_clause(&mut outer_query_builder) + .attach_printable("Error filtering time range for outer query") + .switch()?; + + outer_query_builder + .add_custom_filter_clause( + RefundDimensions::RefundReason, + "NULL", + FilterTypes::IsNotNull, + ) + .switch()?; + + for dim in dimensions.iter() { + outer_query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut outer_query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + outer_query_builder + .add_order_by_clause("count", Order::Descending) + .attach_printable("Error adding order by clause") + .switch()?; + + let filtered_dimensions: Vec<&RefundDimensions> = dimensions + .iter() + .filter(|&&dim| dim != RefundDimensions::RefundReason) + .collect(); + + for dim in &filtered_dimensions { + outer_query_builder + .add_order_by_clause(*dim, Order::Ascending) + .attach_printable("Error adding order by clause") + .switch()?; + } + + outer_query_builder + .execute_query::<RefundMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + RefundMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.refund_type.as_ref().map(|i| i.0.to_string()), + i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs index 332261a3208..c0bb139c46f 100644 --- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs @@ -102,6 +102,8 @@ where i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs index 35ee0d61b50..e2348d51ad7 100644 --- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs @@ -97,6 +97,8 @@ where i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), + i.refund_reason.clone(), + i.refund_error_message.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/refunds/types.rs b/crates/analytics/src/refunds/types.rs index 3f22081a69d..c0735557d1c 100644 --- a/crates/analytics/src/refunds/types.rs +++ b/crates/analytics/src/refunds/types.rs @@ -42,6 +42,21 @@ where .attach_printable("Error adding profile id filter")?; } + if !self.refund_reason.is_empty() { + builder + .add_filter_in_range_clause(RefundDimensions::RefundReason, &self.refund_reason) + .attach_printable("Error adding refund reason filter")?; + } + + if !self.refund_error_message.is_empty() { + builder + .add_filter_in_range_clause( + RefundDimensions::RefundErrorMessage, + &self.refund_error_message, + ) + .attach_printable("Error adding refund error message filter")?; + } + Ok(()) } } diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 1d91ce17c6a..2a94d528768 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -154,6 +154,7 @@ impl super::payment_intents::filters::PaymentIntentFilterAnalytics for SqlxClien impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for SqlxClient {} impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {} impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {} +impl super::refunds::distribution::RefundDistributionAnalytics for SqlxClient {} impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {} impl super::disputes::metrics::DisputeMetricAnalytics for SqlxClient {} impl super::frm::metrics::FrmMetricAnalytics for SqlxClient {} @@ -214,6 +215,15 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let refund_error_message: Option<String> = + row.try_get("refund_error_message").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -235,6 +245,8 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow { connector, refund_type, profile_id, + refund_reason, + refund_error_message, total, count, start_bucket, @@ -791,12 +803,88 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::filters::RefundFilterRow { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let refund_error_message: Option<String> = + row.try_get("refund_error_message").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; Ok(Self { currency, refund_status, connector, refund_type, profile_id, + refund_reason, + refund_error_message, + }) + } +} + +impl<'a> FromRow<'a, PgRow> for super::refunds::distribution::RefundDistributionRow { + fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { + let currency: Option<DBEnumWrapper<Currency>> = + row.try_get("currency").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let refund_status: Option<DBEnumWrapper<RefundStatus>> = + row.try_get("refund_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let connector: Option<String> = row.try_get("connector").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let refund_type: Option<DBEnumWrapper<RefundType>> = + row.try_get("refund_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let count: Option<i64> = row.try_get("count").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let refund_error_message: Option<String> = + row.try_get("refund_error_message").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + // Removing millisecond precision to get accurate diffs against clickhouse + let start_bucket: Option<PrimitiveDateTime> = row + .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? + .and_then(|dt| dt.replace_millisecond(0).ok()); + let end_bucket: Option<PrimitiveDateTime> = row + .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? + .and_then(|dt| dt.replace_millisecond(0).ok()); + Ok(Self { + currency, + refund_status, + connector, + refund_type, + profile_id, + total, + count, + refund_reason, + refund_error_message, + start_bucket, + end_bucket, }) } } diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index b6d4044c5f3..806eb4b6e0e 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -12,7 +12,7 @@ use self::{ frm::{FrmDimensions, FrmMetrics}, payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics}, - refunds::{RefundDimensions, RefundMetrics}, + refunds::{RefundDimensions, RefundDistributions, RefundMetrics}, sdk_events::{SdkEventDimensions, SdkEventMetrics}, }; pub mod active_payments; @@ -73,7 +73,7 @@ pub struct GetPaymentMetricRequest { #[serde(default)] pub filters: payments::PaymentFilters, pub metrics: HashSet<PaymentMetrics>, - pub distribution: Option<Distribution>, + pub distribution: Option<PaymentDistributionBody>, #[serde(default)] pub delta: bool, } @@ -98,11 +98,18 @@ impl Into<u64> for QueryLimit { #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] -pub struct Distribution { +pub struct PaymentDistributionBody { pub distribution_for: PaymentDistributions, pub distribution_cardinality: QueryLimit, } +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RefundDistributionBody { + pub distribution_for: RefundDistributions, + pub distribution_cardinality: QueryLimit, +} + #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ReportRequest { @@ -142,6 +149,7 @@ pub struct GetRefundMetricRequest { #[serde(default)] pub filters: refunds::RefundFilters, pub metrics: HashSet<RefundMetrics>, + pub distribution: Option<RefundDistributionBody>, #[serde(default)] pub delta: bool, } @@ -230,8 +238,12 @@ pub struct PaymentIntentsAnalyticsMetadata { #[derive(Debug, serde::Serialize)] pub struct RefundsAnalyticsMetadata { + pub total_refund_success_rate: Option<f64>, pub total_refund_processed_amount: Option<u64>, pub total_refund_processed_amount_in_usd: Option<u64>, + pub total_refund_processed_count: Option<u64>, + pub total_refund_reason_count: Option<u64>, + pub total_refund_error_message_count: Option<u64>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs index d981bd4382f..0afca6c1ef6 100644 --- a/crates/api_models/src/analytics/refunds.rs +++ b/crates/api_models/src/analytics/refunds.rs @@ -43,6 +43,10 @@ pub struct RefundFilters { pub refund_type: Vec<RefundType>, #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, + #[serde(default)] + pub refund_reason: Vec<String>, + #[serde(default)] + pub refund_error_message: Vec<String>, } #[derive( @@ -67,6 +71,8 @@ pub enum RefundDimensions { Connector, RefundType, ProfileId, + RefundReason, + RefundErrorMessage, } #[derive( @@ -92,6 +98,44 @@ pub enum RefundMetrics { SessionizedRefundCount, SessionizedRefundSuccessCount, SessionizedRefundProcessedAmount, + SessionizedRefundReason, + SessionizedRefundErrorMessage, +} + +#[derive(Debug, Default, serde::Serialize)] +pub struct ReasonsResult { + pub reason: String, + pub count: i64, + pub percentage: f64, +} + +#[derive(Debug, Default, serde::Serialize)] +pub struct ErrorMessagesResult { + pub error_message: String, + pub count: i64, + pub percentage: f64, +} + +#[derive( + Clone, + Copy, + Debug, + Hash, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumIter, + strum::AsRefStr, +)] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum RefundDistributions { + #[strum(serialize = "refund_reason")] + SessionizedRefundReason, + #[strum(serialize = "refund_error_message")] + SessionizedRefundErrorMessage, } pub mod metric_behaviour { @@ -124,9 +168,10 @@ pub struct RefundMetricsBucketIdentifier { pub currency: Option<Currency>, pub refund_status: Option<String>, pub connector: Option<String>, - pub refund_type: Option<String>, pub profile_id: Option<String>, + pub refund_reason: Option<String>, + pub refund_error_message: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] @@ -141,6 +186,8 @@ impl Hash for RefundMetricsBucketIdentifier { self.connector.hash(state); self.refund_type.hash(state); self.profile_id.hash(state); + self.refund_reason.hash(state); + self.refund_error_message.hash(state); self.time_bucket.hash(state); } } @@ -155,12 +202,15 @@ impl PartialEq for RefundMetricsBucketIdentifier { } impl RefundMetricsBucketIdentifier { + #[allow(clippy::too_many_arguments)] pub fn new( currency: Option<Currency>, refund_status: Option<String>, connector: Option<String>, refund_type: Option<String>, profile_id: Option<String>, + refund_reason: Option<String>, + refund_error_message: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { @@ -169,6 +219,8 @@ impl RefundMetricsBucketIdentifier { connector, refund_type, profile_id, + refund_reason, + refund_error_message, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -176,11 +228,18 @@ impl RefundMetricsBucketIdentifier { } #[derive(Debug, serde::Serialize)] pub struct RefundMetricsBucketValue { + pub successful_refunds: Option<u32>, + pub total_refunds: Option<u32>, pub refund_success_rate: Option<f64>, pub refund_count: Option<u64>, pub refund_success_count: Option<u64>, pub refund_processed_amount: Option<u64>, pub refund_processed_amount_in_usd: Option<u64>, + pub refund_processed_count: Option<u64>, + pub refund_reason_distribution: Option<Vec<ReasonsResult>>, + pub refund_error_message_distribution: Option<Vec<ErrorMessagesResult>>, + pub refund_reason_count: Option<u64>, + pub refund_error_message_count: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct RefundMetricsBucketResponse {
2024-11-19T17:04:47Z
## Description <!-- Describe your changes in detail --> Adding metrics, and support for Refund Page in Analytics V2 Dashboard through sessionizer. The metrics added are as follows: - **Static Metrics in overview section:** - Refund Success Rate - Total Refunds Processed (Amount) - Successful Refunds - Failed Refunds - Pending Refunds - **Series Graphs:** - Refunds Processed (Amount and Count) (With granularity) - Refunds Success Rate (With granularity) - **Distributions:** - Successful Refunds by connector - Failed Refunds by connector - **Tables** - Refund Reasons - Failed Refund Error Message - Failed Refund Error Reasons This PR also adds support for refunds distribution, similar to payments distribution, which may be needed in the future for more advanced analytics. The following distributions are added: - Refund Reasons - Refund Error Message ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Provide more insights into Refunds data for the merchants to make important business decisions ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Refunds Success Rate: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "source": "BATCH", "metrics": [ "sessionized_refund_success_rate" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": 6, "total_refunds": 10, "refund_success_rate": 60.0, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": 60.0, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "successful_refunds": 6, "total_refunds": 10, "refund_success_rate": 60.0, ``` - metaData: ```json "total_refund_success_rate": 60.0, ``` Total Refunds Processed (Amount) ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "source": "BATCH", "metrics": [ "sessionized_refund_processed_amount" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 1800, "refund_processed_amount_in_usd": 21, "refund_processed_count": 3, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": "INR", "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 1800, "refund_processed_amount_in_usd": 1800, "refund_processed_count": 3, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": "USD", "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 3600, "total_refund_processed_amount_in_usd": 1821, "total_refund_processed_count": 6, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_processed_amount": 1800, "refund_processed_amount_in_usd": 21, "refund_processed_count": 3, ``` - metaData: ```json "total_refund_processed_amount": 3600, "total_refund_processed_amount_in_usd": 1821, "total_refund_processed_count": 6, ``` Successful Refunds: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "filters": { "refund_status": [ "success" ] }, "source": "BATCH", "metrics": [ "sessionized_refund_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 6, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_count": 6, ``` Failed Refunds ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "filters": { "refund_status": [ "failure" ] }, "source": "BATCH", "metrics": [ "sessionized_refund_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 4, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_count": 4, ``` Pending Refunds ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "filters": { "refund_status": [ "pending" ] }, "source": "BATCH", "metrics": [ "sessionized_refund_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 0, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_count": 0, ``` Refund Success Rate series graph is similar to Refund Success Rate above, granularity will be added. Refund Processed Amount and Count series graph is similar to the one above, granularity will be added. Successful Refunds Distribution by connector: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector" ], "source": "BATCH", "metrics": [ "sessionized_refund_count", "sessionized_refund_success_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 7, "refund_success_count": 6, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 3, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested and taken into account: - queryData: ```json "refund_count": 7, "refund_success_count": 6, "connector": "stripe_test", ``` Failed Refunds Distribution by connector: - This will have multiple API calls from FE, and data would be calculated at FE only. - First Request: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector" ], "source": "BATCH", "metrics": [ "sessionized_refund_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 7, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 3, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested and taken into account: - queryData: ```json "refund_count": 7, "connector": "stripe_test", ``` - Second Request: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "filters": { "refund_status": [ "failure" ] }, "groupByNames": [ "connector" ], "source": "BATCH", "metrics": [ "sessionized_refund_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 3, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 1, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested and taken into account: - queryData: ```json "refund_count": 1, "connector": "stripe_test", ``` From the two API calls, failed refunds and total refunds can be calculated for every connector, and the failed refunds distribution can be plotted and displayed. Refund Reasons: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector", "refund_reason" ], "source": "BATCH", "metrics": [ "sessionized_refund_reason" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 1, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": "Test REFUND - 1", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 6, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": "Customer returned product", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 1, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 3", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 2, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 2", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 10, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_reason_count": 1, "refund_reason": "Test Refund - 3", "connector": "stripe_test", ``` - metaData: ```json "total_refund_reason_count": 10, ``` Failed Refund Reasons: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector", "refund_reason" ], "filters": { "refund_status": ["failure"] }, "source": "BATCH", "metrics": [ "sessionized_refund_reason" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 2, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 2", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 1, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": "Customer returned product", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 1, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 3", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 4, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_reason_count": 1, "refund_reason": "Test Refund - 3", "connector": "adyen", ``` - metaData: ```json "total_refund_reason_count": 4, ``` Failed Refund Error Message: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector", "refund_error_message" ], "source": "BATCH", "metrics": [ "sessionized_refund_error_message" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 1, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": "The refund failed due to test-failure 3.", "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 1, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": "The refund failed due to test-failure.", "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 2 } ] } ``` Fields to be tested: - queryData: ```json "refund_error_message_count": 1, "refund_error_message": "The refund failed due to test-failure.", "connector": "adyen", ``` - metaData: ```json "total_refund_error_message_count": 2 ``` Refund Reasons Distribution: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector" ], "distribution": { "distributionFor": "sessionized_refund_reason", "distributionCardinality": "TOP_5" }, "metrics": [ ], "source": "BATCH", "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": [ { "reason": "Test REFUND - 1", "count": 1, "percentage": 14.29 } ], "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": "Test REFUND - 1", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": [ { "reason": "Test Refund - 2", "count": 2, "percentage": 66.67 } ], "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 2", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": [ { "reason": "Test Refund - 3", "count": 1, "percentage": 33.33 } ], "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 3", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": [ { "reason": "Customer returned product", "count": 6, "percentage": 85.71 } ], "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": "Customer returned product", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_reason_distribution": [ { "reason": "Test REFUND - 1", "count": 1, "percentage": 14.29 } ], "connector": "stripe_test", ``` Refund Error Message Distribution: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector" ], "distribution": { "distributionFor": "sessionized_refund_error_message", "distributionCardinality": "TOP_5" }, "metrics": [ ], "source": "BATCH", "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": [ { "error_message": "The refund failed due to test-failure 3.", "count": 1, "percentage": 33.33 } ], "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": "The refund failed due to test-failure 3.", "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": [ { "error_message": "", "count": 1, "percentage": 33.33 } ], "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": [ { "error_message": "The refund failed due to test-failure.", "count": 1, "percentage": 33.33 } ], "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": "The refund failed due to test-failure.", "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": [ { "error_message": "", "count": 1, "percentage": 100.0 } ], "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_error_message_distribution": [ { "error_message": "The refund failed due to test-failure 3.", "count": 1, "percentage": 33.33 } ], "connector": "adyen", ```
64383915bda5693df1cecf6cc5683e8b9aaef99b
Refunds Success Rate: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "source": "BATCH", "metrics": [ "sessionized_refund_success_rate" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": 6, "total_refunds": 10, "refund_success_rate": 60.0, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": 60.0, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "successful_refunds": 6, "total_refunds": 10, "refund_success_rate": 60.0, ``` - metaData: ```json "total_refund_success_rate": 60.0, ``` Total Refunds Processed (Amount) ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "source": "BATCH", "metrics": [ "sessionized_refund_processed_amount" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 1800, "refund_processed_amount_in_usd": 21, "refund_processed_count": 3, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": "INR", "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 1800, "refund_processed_amount_in_usd": 1800, "refund_processed_count": 3, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": "USD", "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 3600, "total_refund_processed_amount_in_usd": 1821, "total_refund_processed_count": 6, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_processed_amount": 1800, "refund_processed_amount_in_usd": 21, "refund_processed_count": 3, ``` - metaData: ```json "total_refund_processed_amount": 3600, "total_refund_processed_amount_in_usd": 1821, "total_refund_processed_count": 6, ``` Successful Refunds: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "filters": { "refund_status": [ "success" ] }, "source": "BATCH", "metrics": [ "sessionized_refund_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 6, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_count": 6, ``` Failed Refunds ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "filters": { "refund_status": [ "failure" ] }, "source": "BATCH", "metrics": [ "sessionized_refund_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 4, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_count": 4, ``` Pending Refunds ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "filters": { "refund_status": [ "pending" ] }, "source": "BATCH", "metrics": [ "sessionized_refund_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 0, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_count": 0, ``` Refund Success Rate series graph is similar to Refund Success Rate above, granularity will be added. Refund Processed Amount and Count series graph is similar to the one above, granularity will be added. Successful Refunds Distribution by connector: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector" ], "source": "BATCH", "metrics": [ "sessionized_refund_count", "sessionized_refund_success_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 7, "refund_success_count": 6, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 3, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested and taken into account: - queryData: ```json "refund_count": 7, "refund_success_count": 6, "connector": "stripe_test", ``` Failed Refunds Distribution by connector: - This will have multiple API calls from FE, and data would be calculated at FE only. - First Request: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector" ], "source": "BATCH", "metrics": [ "sessionized_refund_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 7, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 3, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested and taken into account: - queryData: ```json "refund_count": 7, "connector": "stripe_test", ``` - Second Request: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "filters": { "refund_status": [ "failure" ] }, "groupByNames": [ "connector" ], "source": "BATCH", "metrics": [ "sessionized_refund_count" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 3, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": 1, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested and taken into account: - queryData: ```json "refund_count": 1, "connector": "stripe_test", ``` From the two API calls, failed refunds and total refunds can be calculated for every connector, and the failed refunds distribution can be plotted and displayed. Refund Reasons: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector", "refund_reason" ], "source": "BATCH", "metrics": [ "sessionized_refund_reason" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 1, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": "Test REFUND - 1", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 6, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": "Customer returned product", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 1, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 3", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 2, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 2", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 10, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_reason_count": 1, "refund_reason": "Test Refund - 3", "connector": "stripe_test", ``` - metaData: ```json "total_refund_reason_count": 10, ``` Failed Refund Reasons: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector", "refund_reason" ], "filters": { "refund_status": ["failure"] }, "source": "BATCH", "metrics": [ "sessionized_refund_reason" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 2, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 2", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 1, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": "Customer returned product", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 1, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 3", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 4, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_reason_count": 1, "refund_reason": "Test Refund - 3", "connector": "adyen", ``` - metaData: ```json "total_refund_reason_count": 4, ``` Failed Refund Error Message: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector", "refund_error_message" ], "source": "BATCH", "metrics": [ "sessionized_refund_error_message" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 1, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": "The refund failed due to test-failure 3.", "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 1, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": "The refund failed due to test-failure.", "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 2 } ] } ``` Fields to be tested: - queryData: ```json "refund_error_message_count": 1, "refund_error_message": "The refund failed due to test-failure.", "connector": "adyen", ``` - metaData: ```json "total_refund_error_message_count": 2 ``` Refund Reasons Distribution: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector" ], "distribution": { "distributionFor": "sessionized_refund_reason", "distributionCardinality": "TOP_5" }, "metrics": [ ], "source": "BATCH", "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": [ { "reason": "Test REFUND - 1", "count": 1, "percentage": 14.29 } ], "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": "Test REFUND - 1", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": [ { "reason": "Test Refund - 2", "count": 2, "percentage": 66.67 } ], "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 2", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": [ { "reason": "Test Refund - 3", "count": 1, "percentage": 33.33 } ], "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": "Test Refund - 3", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": [ { "reason": "Customer returned product", "count": 6, "percentage": 85.71 } ], "refund_error_message_distribution": null, "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": "Customer returned product", "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_reason_distribution": [ { "reason": "Test REFUND - 1", "count": 1, "percentage": 14.29 } ], "connector": "stripe_test", ``` Refund Error Message Distribution: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T09:00:00Z", "endTime": "2024-11-29T09:30:39Z" }, "groupByNames": [ "connector" ], "distribution": { "distributionFor": "sessionized_refund_error_message", "distributionCardinality": "TOP_5" }, "metrics": [ ], "source": "BATCH", "delta": true } ]' ``` Response: ```json { "queryData": [ { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": [ { "error_message": "The refund failed due to test-failure 3.", "count": 1, "percentage": 33.33 } ], "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": "The refund failed due to test-failure 3.", "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": [ { "error_message": "", "count": 1, "percentage": 33.33 } ], "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": [ { "error_message": "The refund failed due to test-failure.", "count": 1, "percentage": 33.33 } ], "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "adyen", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": "The refund failed due to test-failure.", "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" }, { "successful_refunds": null, "total_refunds": null, "refund_success_rate": null, "refund_count": null, "refund_success_count": null, "refund_processed_amount": 0, "refund_processed_amount_in_usd": null, "refund_processed_count": null, "refund_reason_distribution": null, "refund_error_message_distribution": [ { "error_message": "", "count": 1, "percentage": 100.0 } ], "refund_reason_count": 0, "refund_error_message_count": 0, "currency": null, "refund_status": null, "connector": "stripe_test", "refund_type": null, "profile_id": null, "refund_reason": null, "refund_error_message": null, "time_range": { "start_time": "2024-11-01T09:00:00.000Z", "end_time": "2024-11-29T09:30:39.000Z" }, "time_bucket": "2024-11-01 09:00:00" } ], "metaData": [ { "total_refund_success_rate": null, "total_refund_processed_amount": 0, "total_refund_processed_amount_in_usd": 0, "total_refund_processed_count": 0, "total_refund_reason_count": 0, "total_refund_error_message_count": 0 } ] } ``` Fields to be tested: - queryData: ```json "refund_error_message_distribution": [ { "error_message": "The refund failed due to test-failure 3.", "count": 1, "percentage": 33.33 } ], "connector": "adyen", ```
[ "crates/analytics/src/clickhouse.rs", "crates/analytics/src/lib.rs", "crates/analytics/src/payments/distribution.rs", "crates/analytics/src/payments/distribution/payment_error_message.rs", "crates/analytics/src/query.rs", "crates/analytics/src/refunds.rs", "crates/analytics/src/refunds/accumulator.rs", "crates/analytics/src/refunds/core.rs", "crates/analytics/src/refunds/distribution.rs", "crates/analytics/src/refunds/distribution/sessionized_distribution.rs", "crates/analytics/src/refunds/distribution/sessionized_distribution/refund_error_message.rs", "crates/analytics/src/refunds/distribution/sessionized_distribution/refund_reason.rs", "crates/analytics/src/refunds/filters.rs", "crates/analytics/src/refunds/metrics.rs", "crates/analytics/src/refunds/metrics/refund_count.rs", "crates/analytics/src/refunds/metrics/refund_processed_amount.rs", "crates/analytics/src/refunds/metrics/refund_success_count.rs", "crates/analytics/src/refunds/metrics/refund_success_rate.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs", "crates/analytics/src/refunds/types.rs", "crates/analytics/src/sqlx.rs", "crates/api_models/src/analytics.rs", "crates/api_models/src/analytics/refunds.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6609
Bug: [FEATURE] align the JSON deserialization errors into expected ErrorResponse format ### Feature Description HyperSwitch uses an error format for responding back with the errors in the API. This error structure is uniform across different stages of the flow. For any deserialization errors in the API, error response with a different structure is returned. Expected ``` { "error": { "error_type": "invalid_request", "message": "Json deserialize error: unknown variant `automatiac`, expected one of `automatic`, `manual`, `manual_multiple`, `scheduled` at line 5 column 34", "code": "IR_06" } } ``` Actual ``` { "error": "Json deserialize error: unknown variant `automatiac`, expected one of `automatic`, `manual`, `manual_multiple`, `scheduled` at line 5 column 34" } ``` ### Possible Implementation Update the `Display` implementation of `CustomJsonError` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 515c9a94ce8..ca61543ec57 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -81,7 +81,11 @@ pub mod error_parser { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str( serde_json::to_string(&serde_json::json!({ - "error": self.err.to_string() + "error": { + "error_type": "invalid_request", + "message": self.err.to_string(), + "code": "IR_06", + } })) .as_deref() .unwrap_or("Invalid Json Error"), diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js index c2d1b7483c1..d445dbd26cd 100644 --- a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js +++ b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js @@ -964,7 +964,11 @@ export const connectorDetails = { Response: { status: 400, body: { - error: "Json deserialize error: invalid card number length", + error: { + error_type: "invalid_request", + message: "Json deserialize error: invalid card number length", + code: "IR_06" + }, }, }, }, @@ -1068,8 +1072,11 @@ export const connectorDetails = { Response: { status: 400, body: { - error: - "Json deserialize error: unknown variant `United`, expected one of `AED`, `AFN`, `ALL`, `AMD`, `ANG`, `AOA`, `ARS`, `AUD`, `AWG`, `AZN`, `BAM`, `BBD`, `BDT`, `BGN`, `BHD`, `BIF`, `BMD`, `BND`, `BOB`, `BRL`, `BSD`, `BTN`, `BWP`, `BYN`, `BZD`, `CAD`, `CDF`, `CHF`, `CLP`, `CNY`, `COP`, `CRC`, `CUP`, `CVE`, `CZK`, `DJF`, `DKK`, `DOP`, `DZD`, `EGP`, `ERN`, `ETB`, `EUR`, `FJD`, `FKP`, `GBP`, `GEL`, `GHS`, `GIP`, `GMD`, `GNF`, `GTQ`, `GYD`, `HKD`, `HNL`, `HRK`, `HTG`, `HUF`, `IDR`, `ILS`, `INR`, `IQD`, `IRR`, `ISK`, `JMD`, `JOD`, `JPY`, `KES`, `KGS`, `KHR`, `KMF`, `KPW`, `KRW`, `KWD`, `KYD`, `KZT`, `LAK`, `LBP`, `LKR`, `LRD`, `LSL`, `LYD`, `MAD`, `MDL`, `MGA`, `MKD`, `MMK`, `MNT`, `MOP`, `MRU`, `MUR`, `MVR`, `MWK`, `MXN`, `MYR`, `MZN`, `NAD`, `NGN`, `NIO`, `NOK`, `NPR`, `NZD`, `OMR`, `PAB`, `PEN`, `PGK`, `PHP`, `PKR`, `PLN`, `PYG`, `QAR`, `RON`, `RSD`, `RUB`, `RWF`, `SAR`, `SBD`, `SCR`, `SDG`, `SEK`, `SGD`, `SHP`, `SLE`, `SLL`, `SOS`, `SRD`, `SSP`, `STN`, `SVC`, `SYP`, `SZL`, `THB`, `TJS`, `TMT`, `TND`, `TOP`, `TRY`, `TTD`, `TWD`, `TZS`, `UAH`, `UGX`, `USD`, `UYU`, `UZS`, `VES`, `VND`, `VUV`, `WST`, `XAF`, `XCD`, `XOF`, `XPF`, `YER`, `ZAR`, `ZMW`, `ZWL`", + error: { + error_type: "invalid_request", + message: "Json deserialize error: unknown variant `United`, expected one of `AED`, `AFN`, `ALL`, `AMD`, `ANG`, `AOA`, `ARS`, `AUD`, `AWG`, `AZN`, `BAM`, `BBD`, `BDT`, `BGN`, `BHD`, `BIF`, `BMD`, `BND`, `BOB`, `BRL`, `BSD`, `BTN`, `BWP`, `BYN`, `BZD`, `CAD`, `CDF`, `CHF`, `CLP`, `CNY`, `COP`, `CRC`, `CUP`, `CVE`, `CZK`, `DJF`, `DKK`, `DOP`, `DZD`, `EGP`, `ERN`, `ETB`, `EUR`, `FJD`, `FKP`, `GBP`, `GEL`, `GHS`, `GIP`, `GMD`, `GNF`, `GTQ`, `GYD`, `HKD`, `HNL`, `HRK`, `HTG`, `HUF`, `IDR`, `ILS`, `INR`, `IQD`, `IRR`, `ISK`, `JMD`, `JOD`, `JPY`, `KES`, `KGS`, `KHR`, `KMF`, `KPW`, `KRW`, `KWD`, `KYD`, `KZT`, `LAK`, `LBP`, `LKR`, `LRD`, `LSL`, `LYD`, `MAD`, `MDL`, `MGA`, `MKD`, `MMK`, `MNT`, `MOP`, `MRU`, `MUR`, `MVR`, `MWK`, `MXN`, `MYR`, `MZN`, `NAD`, `NGN`, `NIO`, `NOK`, `NPR`, `NZD`, `OMR`, `PAB`, `PEN`, `PGK`, `PHP`, `PKR`, `PLN`, `PYG`, `QAR`, `RON`, `RSD`, `RUB`, `RWF`, `SAR`, `SBD`, `SCR`, `SDG`, `SEK`, `SGD`, `SHP`, `SLE`, `SLL`, `SOS`, `SRD`, `SSP`, `STN`, `SVC`, `SYP`, `SZL`, `THB`, `TJS`, `TMT`, `TND`, `TOP`, `TRY`, `TTD`, `TWD`, `TZS`, `UAH`, `UGX`, `USD`, `UYU`, `UZS`, `VES`, `VND`, `VUV`, `WST`, `XAF`, `XCD`, `XOF`, `XPF`, `YER`, `ZAR`, `ZMW`, `ZWL`", + code: "IR_06" + }, }, }, }, @@ -1093,8 +1100,11 @@ export const connectorDetails = { Response: { status: 400, body: { - error: - "Json deserialize error: unknown variant `auto`, expected one of `automatic`, `manual`, `manual_multiple`, `scheduled`", + error: { + error_type: "invalid_request", + message: "Json deserialize error: unknown variant `auto`, expected one of `automatic`, `manual`, `manual_multiple`, `scheduled`", + code: "IR_06" + }, }, }, }, @@ -1117,8 +1127,11 @@ export const connectorDetails = { Response: { status: 400, body: { - error: - "Json deserialize error: unknown variant `this_supposed_to_be_a_card`, expected one of `card`, `card_redirect`, `pay_later`, `wallet`, `bank_redirect`, `bank_transfer`, `crypto`, `bank_debit`, `reward`, `real_time_payment`, `upi`, `voucher`, `gift_card`, `open_banking`", + error: { + error_type: "invalid_request", + message: "Json deserialize error: unknown variant `this_supposed_to_be_a_card`, expected one of `card`, `card_redirect`, `pay_later`, `wallet`, `bank_redirect`, `bank_transfer`, `crypto`, `bank_debit`, `reward`, `real_time_payment`, `upi`, `voucher`, `gift_card`, `open_banking`, `mobile_payment`", + code: "IR_06" + }, }, }, }, diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js b/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js index 9785839f422..569b557b690 100644 --- a/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js +++ b/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js @@ -88,9 +88,14 @@ export function defaultErrorHandler(response, response_data) { if (typeof response.body.error === "object") { for (const key in response_data.body.error) { - expect(response_data.body.error[key]).to.equal(response.body.error[key]); + // Check if the error message is a Json deserialize error + let apiResponseContent = response.body.error[key]; + let expectedContent = response_data.body.error[key]; + if (typeof apiResponseContent === "string" && apiResponseContent.includes("Json deserialize error")) { + expect(apiResponseContent).to.include(expectedContent); + } else { + expect(apiResponseContent).to.equal(expectedContent); + } } - } else if (typeof response.body.error === "string") { - expect(response.body.error).to.include(response_data.body.error); } }
2024-11-19T11:05:09Z
## Description Described in #6609 ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Locally.
8e9c3ec8931851dae638037b91eb1611399be0bf
Locally.
[ "crates/router/src/utils.rs", "cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js", "cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js" ]
juspay/hyperswitch
juspay__hyperswitch-6605
Bug: feat(analytics): add first_attempt as a filter for PaymentFilters Need to add `first_attempt` as a filter in PaymentFilters. This is required for the new Analytics v2 `Smart Retries Metrics`, specifically S`mart Retries Successful Distribution `and `Smart Retries Failure Distribution`, for calculations only involving smart retries (ignoring first attempts).
diff --git a/crates/analytics/src/payments/filters.rs b/crates/analytics/src/payments/filters.rs index 51805acaae2..668bdaa6c8b 100644 --- a/crates/analytics/src/payments/filters.rs +++ b/crates/analytics/src/payments/filters.rs @@ -64,4 +64,5 @@ pub struct PaymentFilterRow { pub card_last_4: Option<String>, pub card_issuer: Option<String>, pub error_reason: Option<String>, + pub first_attempt: Option<bool>, } diff --git a/crates/analytics/src/payments/types.rs b/crates/analytics/src/payments/types.rs index e23fc6cbbb3..b9af3cd0610 100644 --- a/crates/analytics/src/payments/types.rs +++ b/crates/analytics/src/payments/types.rs @@ -104,6 +104,11 @@ where .add_filter_in_range_clause(PaymentDimensions::ErrorReason, &self.error_reason) .attach_printable("Error adding error reason filter")?; } + if !self.first_attempt.is_empty() { + builder + .add_filter_in_range_clause("first_attempt", &self.first_attempt) + .attach_printable("Error adding first attempt filter")?; + } Ok(()) } } diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index d746594e36e..e80f762c41b 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -457,6 +457,12 @@ impl<T: AnalyticsDataSource> ToSql<T> for common_utils::id_type::CustomerId { } } +impl<T: AnalyticsDataSource> ToSql<T> for bool { + fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { + Ok(self.to_string().to_owned()) + } +} + /// Implement `ToSql` on arrays of types that impl `ToString`. macro_rules! impl_to_sql_for_to_string { ($($type:ty),+) => { diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 0a641fbc5f9..16523d5d0a7 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -569,6 +569,10 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; Ok(Self { currency, status, @@ -584,6 +588,7 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow { card_last_4, card_issuer, error_reason, + first_attempt, }) } } diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs index b34f8c9293c..23d64ff1886 100644 --- a/crates/api_models/src/analytics/payments.rs +++ b/crates/api_models/src/analytics/payments.rs @@ -41,6 +41,8 @@ pub struct PaymentFilters { pub card_issuer: Vec<String>, #[serde(default)] pub error_reason: Vec<String>, + #[serde(default)] + pub first_attempt: Vec<bool>, } #[derive(
2024-11-19T08:32:54Z
## Description <!-- Describe your changes in detail --> Added `first_attempt` as a filter in `PaymentFilters`. This is required for the new Analytics v2 `Smart Retries` Metrics, specifically `Smart Retries Successful Distribution` and `Smart Retries Failure Distribution`, for calculations only involving smart retries (ignoring first attempts). ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Helps in calculating certain metrics seamlessly. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: test_admin' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjYwODUzNCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.tQYvWyhWQInhAymh0c4itE1CWVwhOG3L4_yHMY4RLkQ' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-19T00:30:00Z", "endTime": "2024-11-19T23:30:00Z" }, "groupByNames": [ "connector" ], "filters": { "first_attempt": [false] }, "source": "BATCH", "metrics": [ "payments_distribution" ], "delta": true } ]' ``` Response body: ```json { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": 100.0, "payments_success_rate_distribution_without_smart_retries": null, "payments_success_rate_distribution_with_only_retries": 100.0, "payments_failure_rate_distribution": 0.0, "payments_failure_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_with_only_retries": 0.0, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": null, "status": null, "connector": "stripe_test", "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-19T00:30:00.000Z", "end_time": "2024-11-19T23:30:00.000Z" }, "time_bucket": "2024-11-19 00:30:00" } ], "metaData": [ { "total_payment_processed_amount": 0, "total_payment_processed_amount_in_usd": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 0, "total_failure_reasons_count_without_smart_retries": 0 } ] } ``` Now this response will only have data related to the attempts which are not the first attempt, and are only subsequent smart rertries. Fields that can be observed in the `queryData`: ```json "payments_success_rate_distribution_with_only_retries": 100.0, "payments_failure_rate_distribution_with_only_retries": 0.0, ```
65bf75a75e1e7d705de3ee3e9080a7a86099ffc3
Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: test_admin' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjYwODUzNCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.tQYvWyhWQInhAymh0c4itE1CWVwhOG3L4_yHMY4RLkQ' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-19T00:30:00Z", "endTime": "2024-11-19T23:30:00Z" }, "groupByNames": [ "connector" ], "filters": { "first_attempt": [false] }, "source": "BATCH", "metrics": [ "payments_distribution" ], "delta": true } ]' ``` Response body: ```json { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": 100.0, "payments_success_rate_distribution_without_smart_retries": null, "payments_success_rate_distribution_with_only_retries": 100.0, "payments_failure_rate_distribution": 0.0, "payments_failure_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_with_only_retries": 0.0, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": null, "status": null, "connector": "stripe_test", "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-19T00:30:00.000Z", "end_time": "2024-11-19T23:30:00.000Z" }, "time_bucket": "2024-11-19 00:30:00" } ], "metaData": [ { "total_payment_processed_amount": 0, "total_payment_processed_amount_in_usd": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 0, "total_failure_reasons_count_without_smart_retries": 0 } ] } ``` Now this response will only have data related to the attempts which are not the first attempt, and are only subsequent smart rertries. Fields that can be observed in the `queryData`: ```json "payments_success_rate_distribution_with_only_retries": 100.0, "payments_failure_rate_distribution_with_only_retries": 0.0, ```
[ "crates/analytics/src/payments/filters.rs", "crates/analytics/src/payments/types.rs", "crates/analytics/src/query.rs", "crates/analytics/src/sqlx.rs", "crates/api_models/src/analytics/payments.rs" ]
juspay/hyperswitch
juspay__hyperswitch-5895
Bug: [CYPRESS] : Add Noon Connector **Description:** This task involves adding a connector for the Noon functionality in Cypress. For reference, similar connectors have already been implemented in the repository. You can refer to the existing connectors here: https://github.com/juspay/hyperswitch/tree/main/cypress-tests/cypress/e2e/PaymentUtils **Pre-requisites:** - Cypress is the testing framework that Hyperswitch is using to run automated tests. Having good grip on Javascript to work on Cypress is a must. - Please follow the [README](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/readme.md) for guidelines on file structure, formatting and instructions on how to set up and run Cypress. **Steps:** 1. Add the Noon connector .js files under the PaymentUtils directory: [PaymentUtils Directory](https://github.com/juspay/hyperswitch/tree/main/cypress-tests/cypress/e2e/PaymentUtils) 2. Add the card details and corresponding test case functions for Noon, following the format used in the [Cybersource.js connector](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js). 3. In the Noon connector, map the test cases and statuses properly. To do this, use the below dashboard credentials where Noon is already configured, test the flows, and then assign the correct statuses. URL: https://integ.hyperswitch.io Username, Password: Please drop a comment requesting credentials. The Creds are only shared on request **Test Cases:** - Add test cases only for card payments. - Test creds for noon https://docs.noonpayments.com/test/cards **Postman collection for reference** https://www.postman.com/altimetry-participant-63653904/hyperswitch Note: - Test cases for other payment methods should be skipped. ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
2024-11-19T06:46:36Z
## Description Add Noon Connector for Cypress Automation Note : Noon supports only 3ds payments , so all the no_three_ds payments are skipped ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Noon connector was not available in the cypress automation ## How did you test it? <img width="710" alt="image" src="https://github.com/user-attachments/assets/88aec323-824c-49e3-b51e-67d469c9826a">
65bf75a75e1e7d705de3ee3e9080a7a86099ffc3
<img width="710" alt="image" src="https://github.com/user-attachments/assets/88aec323-824c-49e3-b51e-67d469c9826a">
[]
juspay/hyperswitch
juspay__hyperswitch-6600
Bug: fix(users): Only use lowercase letters in emails Currently uppercase letters in emails are being using at it is. Ideally we should convert them to lowercase before performing any DB operations with it.
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 5a881728b07..4cb69e68ed8 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -103,7 +103,7 @@ impl UserEmail { pub fn new(email: Secret<String, pii::EmailStrategy>) -> UserResult<Self> { use validator::ValidateEmail; - let email_string = email.expose(); + let email_string = email.expose().to_lowercase(); let email = pii::Email::from_str(&email_string).change_context(UserErrors::EmailParsingError)?; @@ -123,21 +123,8 @@ impl UserEmail { } pub fn from_pii_email(email: pii::Email) -> UserResult<Self> { - use validator::ValidateEmail; - - let email_string = email.peek(); - if email_string.validate_email() { - let (_username, domain) = match email_string.split_once('@') { - Some((u, d)) => (u, d), - None => return Err(UserErrors::EmailParsingError.into()), - }; - if BLOCKED_EMAIL.contains(domain) { - return Err(UserErrors::InvalidEmailError.into()); - } - Ok(Self(email)) - } else { - Err(UserErrors::EmailParsingError.into()) - } + let email_string = email.expose().map(|inner| inner.to_lowercase()); + Self::new(email_string) } pub fn into_inner(self) -> pii::Email {
2024-11-18T13:19:55Z
## Description <!-- Describe your changes in detail --> This PR changes will convert emails from request to lowercase before performing any DB operations. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6600. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "USER@Example.com" }' ``` This email in the about request will be inserted as `user@example.com` in DB.
43d87913ab3d177a6d193b3e475c96609cc09a28
``` curl --location 'http://localhost:8080/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "USER@Example.com" }' ``` This email in the about request will be inserted as `user@example.com` in DB.
[ "crates/router/src/types/domain/user.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6598
Bug: feat(authn): Use cookies for authentication Currently we use auth headers and local storage in FE for transfer JWT from FE to BE. Cookies is a better way to do this, as it is handled by browser and JavaScript doesn't have access to. First we will test this in Integ and slowly move it to sandbox and production.
diff --git a/config/config.example.toml b/config/config.example.toml index 191f2ba7f8b..52b704e1adc 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -403,6 +403,7 @@ two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should totp_issuer_name = "Hyperswitch" # Name of the issuer for TOTP base_url = "" # Base url used for user specific redirects and emails force_two_factor_auth = false # Whether to force two factor authentication for all users +force_cookies = true # Whether to use only cookies for JWT extraction and authentication #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 00a544dc565..0765591c63b 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -145,6 +145,7 @@ two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Integ" base_url = "https://integ.hyperswitch.io" force_two_factor_auth = false +force_cookies = true [frm] enabled = true diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 0fe9095d280..d9d3e852d1b 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -152,6 +152,7 @@ two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Production" base_url = "https://live.hyperswitch.io" force_two_factor_auth = true +force_cookies = false [frm] enabled = false diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 82c347ae389..b3b57e9d202 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -152,6 +152,7 @@ two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Sandbox" base_url = "https://app.hyperswitch.io" force_two_factor_auth = false +force_cookies = false [frm] enabled = true diff --git a/config/development.toml b/config/development.toml index ee6ea5dab0b..0c4d92fc519 100644 --- a/config/development.toml +++ b/config/development.toml @@ -329,6 +329,7 @@ two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Dev" base_url = "http://localhost:8080" force_two_factor_auth = false +force_cookies = true [bank_config.eps] stripe = { banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index ed0ede98d94..f1d02d30345 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -57,6 +57,7 @@ two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch" base_url = "http://localhost:8080" force_two_factor_auth = false +force_cookies = true [locker] host = "" diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 7b212ec6d1d..4e559a261b9 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -557,6 +557,7 @@ pub struct UserSettings { pub totp_issuer_name: String, pub base_url: String, pub force_two_factor_auth: bool, + pub force_cookies: bool, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index f01f6c5d749..c6501dac3bd 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -294,7 +294,7 @@ pub async fn connect_account( pub async fn signout( state: SessionState, - user_from_token: auth::UserFromToken, + user_from_token: auth::UserIdFromAuth, ) -> UserResponse<()> { tfa_utils::delete_totp_from_redis(&state, &user_from_token.user_id).await?; tfa_utils::delete_recovery_code_from_redis(&state, &user_from_token.user_id).await?; diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 068c2f30c79..8fc0dad452a 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -130,7 +130,7 @@ pub async fn signout(state: web::Data<AppState>, http_req: HttpRequest) -> HttpR &http_req, (), |state, user, _, _| user_core::signout(state, user), - &auth::DashboardNoPermissionAuth, + &auth::AnyPurposeOrLoginTokenAuth, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 2f5f55b8434..c05e4514aaa 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -871,6 +871,47 @@ where } } +#[cfg(feature = "olap")] +#[derive(Debug)] +pub struct AnyPurposeOrLoginTokenAuth; + +#[cfg(feature = "olap")] +#[async_trait] +impl<A> AuthenticateAndFetch<UserIdFromAuth, A> for AnyPurposeOrLoginTokenAuth +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(UserIdFromAuth, AuthenticationType)> { + let payload = + parse_jwt_payload::<A, SinglePurposeOrLoginToken>(request_headers, state).await?; + if payload.check_in_blacklist(state).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } + + let purpose_exists = payload.purpose.is_some(); + let role_id_exists = payload.role_id.is_some(); + + if purpose_exists ^ role_id_exists { + Ok(( + UserIdFromAuth { + user_id: payload.user_id.clone(), + }, + AuthenticationType::SinglePurposeOrLoginJwt { + user_id: payload.user_id, + purpose: payload.purpose, + role_id: payload.role_id, + }, + )) + } else { + Err(errors::ApiErrorResponse::InvalidJwtToken.into()) + } + } +} + #[derive(Debug, Default)] pub struct AdminApiAuth; @@ -2504,17 +2545,27 @@ where T: serde::de::DeserializeOwned, A: SessionStateInfo + Sync, { - let token = match get_cookie_from_header(headers).and_then(cookies::parse_cookie) { - Ok(cookies) => cookies, - Err(error) => { - let token = get_jwt_from_authorization_header(headers); - if token.is_err() { - logger::error!(?error); - } - token?.to_owned() - } + let cookie_token_result = get_cookie_from_header(headers).and_then(cookies::parse_cookie); + let auth_header_token_result = get_jwt_from_authorization_header(headers); + let force_cookie = state.conf().user.force_cookies; + + logger::info!( + user_agent = ?headers.get(headers::USER_AGENT), + header_names = ?headers.keys().collect::<Vec<_>>(), + is_token_equal = + auth_header_token_result.as_deref().ok() == cookie_token_result.as_deref().ok(), + cookie_error = ?cookie_token_result.as_ref().err(), + token_error = ?auth_header_token_result.as_ref().err(), + force_cookie, + ); + + let final_token = if force_cookie { + cookie_token_result? + } else { + auth_header_token_result?.to_owned() }; - decode_jwt(&token, state).await + + decode_jwt(&final_token, state).await } #[cfg(feature = "v1")] diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index dab85eb3cdd..a3ac1159ddb 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -36,6 +36,7 @@ password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch" force_two_factor_auth = false +force_cookies = true [locker] host = ""
2024-11-18T11:34:51Z
## Description <!-- Describe your changes in detail --> This PR will add logging for cookies and also make signout API accessible by any SPT. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> `config/config.example.toml` `config/deployments/integration_test.toml` `config/deployments/production.toml` `config/deployments/sandbox.toml` `config/development.toml` `config/docker_compose.toml` `loadtest/config/development.toml` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6598. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - This following behaviour applies only to integ and not for sandbox and prod. ``` curl --location 'http://localhost:8080/user' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNzJkNDU0YTAtM2I3YS00MzZiLTllNjMtMmU5ZDQ5YzI3NmZjIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzMxOTI4MDg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjEwMDg5MSwib3JnX2lkIjoib3JnX05qeWR3eXhpRW5OQjk2QldobjlwIiwicHJvZmlsZV9pZCI6InByb183bGVMTnpFakVtRWVha1ZKTlJSbSJ9.g7InEVOcYqKSh2zNPBrq20l6O5MppE3-wKqj2YYBkBM' ``` If cookie is not present even if the auth header is present, BE will throw the following error ``` { "error": { "type": "invalid_request", "message": "Invalid Cookie", "code": "IR_26" } } ``` - If cookie will be given priority if both are present.
ea81432e3eb72d9a2e139e26741a42cdd8d31202
- This following behaviour applies only to integ and not for sandbox and prod. ``` curl --location 'http://localhost:8080/user' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNzJkNDU0YTAtM2I3YS00MzZiLTllNjMtMmU5ZDQ5YzI3NmZjIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzMxOTI4MDg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjEwMDg5MSwib3JnX2lkIjoib3JnX05qeWR3eXhpRW5OQjk2QldobjlwIiwicHJvZmlsZV9pZCI6InByb183bGVMTnpFakVtRWVha1ZKTlJSbSJ9.g7InEVOcYqKSh2zNPBrq20l6O5MppE3-wKqj2YYBkBM' ``` If cookie is not present even if the auth header is present, BE will throw the following error ``` { "error": { "type": "invalid_request", "message": "Invalid Cookie", "code": "IR_26" } } ``` - If cookie will be given priority if both are present.
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/router/src/configs/settings.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/user.rs", "crates/router/src/services/authentication.rs", "loadtest/config/development.toml" ]
juspay/hyperswitch
juspay__hyperswitch-6592
Bug: refactor(users): Force 2FA in prod env Currently 2FA is not forced on prod, users have ability to skip it. For the PCI compliance, we have to force users to setup and use 2FA.
diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 73e5794f042..76f42085f92 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -149,7 +149,7 @@ password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Production" base_url = "https://live.hyperswitch.io" -force_two_factor_auth = false +force_two_factor_auth = true [frm] enabled = false
2024-11-18T11:01:56Z
## Description <!-- Describe your changes in detail --> This PR forces users to use 2FA in production. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> `config/deployments/production.toml` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6592. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This change will only affect production. 1. 2FA Status API - `is_skippable` field is added in the response. ``` curl --location 'http://localhost:8080/user/2fa/v2' \ --header 'Authorization: JWT' \ ``` ``` { "status": null, "is_skippable": true } ``` 2. Terminate 2FA API - This API will now not allow skip 2FA if the `force_two_factor_auth` ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: JWT' \ ``` ``` { "error": { "type": "invalid_request", "message": "Two factor auth required", "code": "UR_40" } } ```
d32397f060731f51a15634e221117a554b8b3721
This change will only affect production. 1. 2FA Status API - `is_skippable` field is added in the response. ``` curl --location 'http://localhost:8080/user/2fa/v2' \ --header 'Authorization: JWT' \ ``` ``` { "status": null, "is_skippable": true } ``` 2. Terminate 2FA API - This API will now not allow skip 2FA if the `force_two_factor_auth` ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: JWT' \ ``` ``` { "error": { "type": "invalid_request", "message": "Two factor auth required", "code": "UR_40" } } ```
[ "config/deployments/production.toml" ]
juspay/hyperswitch
juspay__hyperswitch-6594
Bug: fix(analytics): fix `authentication_type` and `card_last_4` fields serialization for payment_intent_filters There is a serialization issue for `card_last_4` and `authentication_type` fields when filters are getting applied for `PaymentIntentFilters`. - `card_last_4` was being processed as `card_last4` . - `auth_type` is being used to add the filters and not serialized into `Authentication_type`. Need to serialize the fields properly, before applying these filters in the query.
diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs index dd51c97d935..365abd71edc 100644 --- a/crates/api_models/src/analytics/payment_intents.rs +++ b/crates/api_models/src/analytics/payment_intents.rs @@ -63,11 +63,15 @@ pub enum PaymentIntentDimensions { Currency, ProfileId, Connector, + #[strum(serialize = "authentication_type")] + #[serde(rename = "authentication_type")] AuthType, PaymentMethod, PaymentMethodType, CardNetwork, MerchantId, + #[strum(serialize = "card_last_4")] + #[serde(rename = "card_last_4")] CardLast4, CardIssuer, ErrorReason,
2024-11-18T10:46:29Z
## Description <!-- Describe your changes in detail --> There is a serialization issue for `card_last_4` and `authentication_type` fields when filters are getting applied for `PaymentIntentFilters`. `card_last_4` was being processed as `card_last4` . `auth_type` is being used to add the filters and not serialized into `Authentication_type`. Made the changes to properly serialize `card_last_4` and `authentication_type` filters for `PaymentIntentFilters` now. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fix the filters issue for some fields for Payment Intents. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> `authentication_type`: Hit the curl for any metric of payment_intents (sessionized metrics): ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjA4NzM4Miwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.3bV2aTF7uFAtELFBuKe-_hIZHY35Zv5ij51F-slCYIg' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-14T18:30:00Z", "endTime": "2024-10-22T15:24:00Z" }, "groupByNames": [ "currency" ], "filters": { "auth_type": [ "no_three_ds" ] }, "timeSeries": { "granularity": "G_ONEDAY" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_payment_processed_amount" ] } ]' ``` You can see the `authentication_type` filter that is getting applied in the query. ![Screenshot 2024-11-18 at 4 18 39 PM](https://github.com/user-attachments/assets/76815e78-8e10-4fbd-bda5-d96dcae51a01) `card_last_4`: Hit the curl for any metric of payment_intents (sessionized metrics): ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjA4NzM4Miwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.3bV2aTF7uFAtELFBuKe-_hIZHY35Zv5ij51F-slCYIg' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-14T18:30:00Z", "endTime": "2024-10-22T15:24:00Z" }, "groupByNames": [ "currency" ], "filters": { "card_last_4": [ "4242" ] }, "timeSeries": { "granularity": "G_ONEDAY" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_payment_processed_amount" ] } ]' ``` You can see the `card_last_4` filter that is getting applied in the query. ![image](https://github.com/user-attachments/assets/8cd1f47b-0bb0-466a-8aac-632742c67612)
d32397f060731f51a15634e221117a554b8b3721
`authentication_type`: Hit the curl for any metric of payment_intents (sessionized metrics): ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjA4NzM4Miwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.3bV2aTF7uFAtELFBuKe-_hIZHY35Zv5ij51F-slCYIg' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-14T18:30:00Z", "endTime": "2024-10-22T15:24:00Z" }, "groupByNames": [ "currency" ], "filters": { "auth_type": [ "no_three_ds" ] }, "timeSeries": { "granularity": "G_ONEDAY" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_payment_processed_amount" ] } ]' ``` You can see the `authentication_type` filter that is getting applied in the query. ![Screenshot 2024-11-18 at 4 18 39 PM](https://github.com/user-attachments/assets/76815e78-8e10-4fbd-bda5-d96dcae51a01) `card_last_4`: Hit the curl for any metric of payment_intents (sessionized metrics): ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjA4NzM4Miwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.3bV2aTF7uFAtELFBuKe-_hIZHY35Zv5ij51F-slCYIg' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-14T18:30:00Z", "endTime": "2024-10-22T15:24:00Z" }, "groupByNames": [ "currency" ], "filters": { "card_last_4": [ "4242" ] }, "timeSeries": { "granularity": "G_ONEDAY" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_payment_processed_amount" ] } ]' ``` You can see the `card_last_4` filter that is getting applied in the query. ![image](https://github.com/user-attachments/assets/8cd1f47b-0bb0-466a-8aac-632742c67612)
[ "crates/api_models/src/analytics/payment_intents.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6597
Bug: [FEATURE] Xendit Template PR ### Feature Description Template code added for new connector Xendit https://developers.xendit.co/api-reference ### Possible Implementation Template code added for new connector Xendit https://developers.xendit.co/api-reference ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index d2fa50d8629..96c6a037ad3 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -18092,6 +18092,7 @@ "wise", "worldline", "worldpay", + "xendit", "zen", "plaid", "zsl" diff --git a/config/config.example.toml b/config/config.example.toml index 289087f4a33..08a32035c4b 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -271,6 +271,7 @@ wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" +xendit.base_url = "https://api.xendit.co" zsl.base_url = "https://api.sitoffalb.net/" zen.base_url = "https://api.zen-test.com/" zen.secondary_base_url = "https://secure.zen-test.com/" @@ -329,6 +330,7 @@ cards = [ "threedsecureio", "thunes", "worldpay", + "xendit", "zen", "zsl", ] diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 1c7a40ea539..e1ea99bc8d1 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -111,6 +111,7 @@ wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" +xendit.base_url = "https://api.xendit.co" zen.base_url = "https://api.zen-test.com/" zen.secondary_base_url = "https://secure.zen-test.com/" zsl.base_url = "https://api.sitoffalb.net/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 73e5794f042..434b20524f0 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -115,6 +115,7 @@ wellsfargopayout.base_url = "https://api.wellsfargo.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" +xendit.base_url = "https://api.xendit.co" zen.base_url = "https://api.zen.com/" zen.secondary_base_url = "https://secure.zen.com/" zsl.base_url = "https://apirh.prodoffalb.net/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 98e1e7e00d9..4421d1b1e96 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -115,6 +115,7 @@ wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" +xendit.base_url = "https://api.xendit.co" zen.base_url = "https://api.zen-test.com/" zen.secondary_base_url = "https://secure.zen-test.com/" zsl.base_url = "https://api.sitoffalb.net/" diff --git a/config/development.toml b/config/development.toml index b6638fe1d47..adad850c4d6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -169,6 +169,7 @@ cards = [ "wise", "worldline", "worldpay", + "xendit", "zen", "zsl", ] @@ -279,6 +280,7 @@ stripe.base_url_file_upload = "https://files.stripe.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" +xendit.base_url = "https://api.xendit.co" trustpay.base_url = "https://test-tpgw.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" volt.base_url = "https://api.sandbox.volt.io/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 7adeee8a376..445205c12fe 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -201,6 +201,7 @@ wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" wise.base_url = "https://api.sandbox.transferwise.tech/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" +xendit.base_url = "https://api.xendit.co" zen.base_url = "https://api.zen-test.com/" zen.secondary_base_url = "https://secure.zen-test.com/" zsl.base_url = "https://api.sitoffalb.net/" @@ -287,6 +288,7 @@ cards = [ "wise", "worldline", "worldpay", + "xendit", "zen", "zsl", ] diff --git a/crates/api_models/src/connector_enums.rs b/crates/api_models/src/connector_enums.rs index 77081f49957..11b38400920 100644 --- a/crates/api_models/src/connector_enums.rs +++ b/crates/api_models/src/connector_enums.rs @@ -129,6 +129,7 @@ pub enum Connector { Signifyd, Plaid, Riskified, + // Xendit, Zen, Zsl, } @@ -259,6 +260,7 @@ impl Connector { | Self::Wise | Self::Worldline | Self::Worldpay + // | Self::Xendit | Self::Zen | Self::Zsl | Self::Signifyd diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 9beaed75960..e75a4038c07 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -123,6 +123,7 @@ pub enum RoutableConnectors { Wise, Worldline, Worldpay, + Xendit, Zen, Plaid, Zsl, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 3634fe730ca..b1cf0bd9f9c 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -231,6 +231,7 @@ pub struct ConnectorConfig { pub wise_payout: Option<ConnectorTomlConfig>, pub worldline: Option<ConnectorTomlConfig>, pub worldpay: Option<ConnectorTomlConfig>, + pub xendit: Option<ConnectorTomlConfig>, pub square: Option<ConnectorTomlConfig>, pub stax: Option<ConnectorTomlConfig>, pub dummy_connector: Option<ConnectorTomlConfig>, diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 2bc82450096..b764ab5b441 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -36,6 +36,7 @@ pub mod tsys; pub mod volt; pub mod worldline; pub mod worldpay; +pub mod xendit; pub mod zen; pub mod zsl; @@ -48,5 +49,5 @@ pub use self::{ nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, novalnet::Novalnet, payeezy::Payeezy, payu::Payu, powertranz::Powertranz, razorpay::Razorpay, shift4::Shift4, square::Square, stax::Stax, taxjar::Taxjar, thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline, - worldpay::Worldpay, zen::Zen, zsl::Zsl, + worldpay::Worldpay, xendit::Xendit, zen::Zen, zsl::Zsl, }; diff --git a/crates/hyperswitch_connectors/src/connectors/xendit.rs b/crates/hyperswitch_connectors/src/connectors/xendit.rs new file mode 100644 index 00000000000..c3f75a7673e --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/xendit.rs @@ -0,0 +1,563 @@ +pub mod transformers; + +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{ExposeInterface, Mask}; +use transformers as xendit; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Xendit { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Xendit { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Xendit {} +impl api::PaymentSession for Xendit {} +impl api::ConnectorAccessToken for Xendit {} +impl api::MandateSetup for Xendit {} +impl api::PaymentAuthorize for Xendit {} +impl api::PaymentSync for Xendit {} +impl api::PaymentCapture for Xendit {} +impl api::PaymentVoid for Xendit {} +impl api::Refund for Xendit {} +impl api::RefundExecute for Xendit {} +impl api::RefundSync for Xendit {} +impl api::PaymentToken for Xendit {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Xendit +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Xendit +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Xendit { + fn id(&self) -> &'static str { + "xendit" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + // TODO! Check connector documentation, on which unit they are processing the currency. + // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, + // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.xendit.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = xendit::XenditAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![( + headers::AUTHORIZATION.to_string(), + auth.api_key.expose().into_masked(), + )]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: xendit::XenditErrorResponse = res + .response + .parse_struct("XenditErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.code, + message: response.message, + reason: response.reason, + attempt_status: None, + connector_transaction_id: None, + }) + } +} + +impl ConnectorValidation for Xendit { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Xendit { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Xendit {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Xendit {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Xendit { + fn get_headers( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + + let connector_router_data = xendit::XenditRouterData::from((amount, req)); + let connector_req = xendit::XenditPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: xendit::XenditPaymentsResponse = res + .response + .parse_struct("Xendit PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Xendit { + fn get_headers( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { + let response: xendit::XenditPaymentsResponse = res + .response + .parse_struct("xendit PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Xendit { + fn get_headers( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + let response: xendit::XenditPaymentsResponse = res + .response + .parse_struct("Xendit PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Xendit {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Xendit { + fn get_headers( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let refund_amount = utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + + let connector_router_data = xendit::XenditRouterData::from((refund_amount, req)); + let connector_req = xendit::XenditRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .set_body(types::RefundExecuteType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &RefundsRouterData<Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { + let response: xendit::RefundResponse = + res.response + .parse_struct("xendit RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Xendit { + fn get_headers( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { + let response: xendit::RefundResponse = res + .response + .parse_struct("xendit RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl webhooks::IncomingWebhook for Xendit { + fn get_webhook_object_reference_id( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs new file mode 100644 index 00000000000..c9d4cd2583c --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs @@ -0,0 +1,228 @@ +use common_enums::enums; +use common_utils::types::StringMinorUnit; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, RefundsRouterData}, +}; +use hyperswitch_interfaces::errors; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::PaymentsAuthorizeRequestData, +}; + +//TODO: Fill the struct with respective fields +pub struct XenditRouterData<T> { + pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(StringMinorUnit, T)> for XenditRouterData<T> { + fn from((amount, item): (StringMinorUnit, T)) -> Self { + //Todo : use utils to convert the amount to the type of amount that a connector accepts + Self { + amount, + router_data: item, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, PartialEq)] +pub struct XenditPaymentsRequest { + amount: StringMinorUnit, + card: XenditCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct XenditCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&XenditRouterData<&PaymentsAuthorizeRouterData>> for XenditPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &XenditRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = XenditCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.clone(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct XenditAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for XenditAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum XenditPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<XenditPaymentStatus> for common_enums::AttemptStatus { + fn from(item: XenditPaymentStatus) -> Self { + match item { + XenditPaymentStatus::Succeeded => Self::Charged, + XenditPaymentStatus::Failed => Self::Failure, + XenditPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct XenditPaymentsResponse { + status: XenditPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, XenditPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, XenditPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: common_enums::AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct XenditRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&XenditRouterData<&RefundsRouterData<F>>> for XenditRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &XenditRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, + //TODO: Review mapping + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct XenditErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 6ee8926f8df..bc86e713501 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -126,6 +126,7 @@ default_imp_for_authorize_session_token!( connectors::Tsys, connectors::Worldline, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -182,6 +183,7 @@ default_imp_for_calculate_tax!( connectors::Volt, connectors::Worldline, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -234,6 +236,7 @@ default_imp_for_session_update!( connectors::Globepay, connectors::Worldline, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::Powertranz, @@ -291,6 +294,7 @@ default_imp_for_post_session_tokens!( connectors::Globepay, connectors::Worldline, connectors::Worldpay, + connectors::Xendit, connectors::Powertranz, connectors::Thunes, connectors::Tsys, @@ -346,6 +350,7 @@ default_imp_for_complete_authorize!( connectors::Tsys, connectors::Worldline, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -404,6 +409,7 @@ default_imp_for_incremental_authorization!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -461,6 +467,7 @@ default_imp_for_create_customer!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -515,6 +522,7 @@ default_imp_for_connector_redirect_response!( connectors::Tsys, connectors::Worldline, connectors::Volt, + connectors::Xendit, connectors::Zsl ); @@ -569,6 +577,7 @@ default_imp_for_pre_processing_steps!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -627,6 +636,7 @@ default_imp_for_post_processing_steps!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -685,6 +695,7 @@ default_imp_for_approve!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -743,6 +754,7 @@ default_imp_for_reject!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -801,6 +813,7 @@ default_imp_for_webhook_source_verification!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -860,6 +873,7 @@ default_imp_for_accept_dispute!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -918,6 +932,7 @@ default_imp_for_submit_evidence!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -976,6 +991,7 @@ default_imp_for_defend_dispute!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1043,6 +1059,7 @@ default_imp_for_file_upload!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1093,6 +1110,7 @@ default_imp_for_payouts!( connectors::Volt, connectors::Worldline, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1153,6 +1171,7 @@ default_imp_for_payouts_create!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1213,6 +1232,7 @@ default_imp_for_payouts_retrieve!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1273,6 +1293,7 @@ default_imp_for_payouts_eligibility!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1333,6 +1354,7 @@ default_imp_for_payouts_fulfill!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1393,6 +1415,7 @@ default_imp_for_payouts_cancel!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1453,6 +1476,7 @@ default_imp_for_payouts_quote!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1513,6 +1537,7 @@ default_imp_for_payouts_recipient!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1573,6 +1598,7 @@ default_imp_for_payouts_recipient_account!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1633,6 +1659,7 @@ default_imp_for_frm_sale!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1693,6 +1720,7 @@ default_imp_for_frm_checkout!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1753,6 +1781,7 @@ default_imp_for_frm_transaction!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1813,6 +1842,7 @@ default_imp_for_frm_fulfillment!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1873,6 +1903,7 @@ default_imp_for_frm_record_return!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1930,6 +1961,7 @@ default_imp_for_revoking_mandates!( connectors::Worldline, connectors::Worldpay, connectors::Volt, + connectors::Xendit, connectors::Zen, connectors::Zsl ); diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index d747d65d73a..75cbf192e55 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -243,6 +243,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -302,6 +303,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -356,6 +358,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -416,6 +419,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -475,6 +479,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -534,6 +539,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -603,6 +609,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -664,6 +671,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -725,6 +733,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -786,6 +795,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -847,6 +857,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -908,6 +919,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -969,6 +981,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1030,6 +1043,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1091,6 +1105,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1150,6 +1165,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1211,6 +1227,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1272,6 +1289,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1333,6 +1351,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1394,6 +1413,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1455,6 +1475,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); @@ -1513,6 +1534,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Worldline, connectors::Volt, connectors::Worldpay, + connectors::Xendit, connectors::Zen, connectors::Zsl ); diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs index 58810a0cb34..5e5eeea31b3 100644 --- a/crates/hyperswitch_interfaces/src/configs.rs +++ b/crates/hyperswitch_interfaces/src/configs.rs @@ -92,6 +92,7 @@ pub struct Connectors { pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, + pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 7913d6543c8..e98730d006d 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -57,7 +57,7 @@ pub use hyperswitch_connectors::connectors::{ powertranz::Powertranz, razorpay, razorpay::Razorpay, shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, - zen, zen::Zen, zsl, zsl::Zsl, + xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, }; #[cfg(feature = "dummy_connector")] diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index b432c57c5d1..f7909a97195 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -496,6 +496,9 @@ impl ConnectorData { 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()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index c97084a2297..6d11dbfeb2e 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -303,6 +303,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { 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")] diff --git a/crates/router/tests/connectors/xendit.rs b/crates/router/tests/connectors/xendit.rs new file mode 100644 index 00000000000..452f22a1122 --- /dev/null +++ b/crates/router/tests/connectors/xendit.rs @@ -0,0 +1,402 @@ +use masking::Secret; +use router::{ + types::{self, api, storage::enums, +}}; + +use crate::utils::{self, ConnectorActions}; +use test_utils::connector_auth; + +#[derive(Clone, Copy)] +struct XenditTest; +impl ConnectorActions for XenditTest {} +impl utils::Connector for XenditTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Xendit; + api::ConnectorData { + connector: Box::new(Xendit::new()), + connector_name: types::Connector::Xendit, + get_token: types::api::GetToken::Connector, + merchant_connector_id: None, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .xendit + .expect("Missing connector authentication configuration").into(), + ) + } + + fn get_name(&self) -> String { + "xendit".to_string() + } +} + +static CONNECTOR: XenditTest = XenditTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: api::PaymentMethodData::Card(api::Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: api::PaymentMethodData::Card(api::Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index be02e5720fb..2b2dc143113 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -92,6 +92,7 @@ pub struct ConnectorAuthentication { // pub wellsfargopayout: Option<HeaderKey>, pub wise: Option<BodyKey>, pub worldpay: Option<BodyKey>, + pub xendit: Option<HeaderKey>, pub worldline: Option<SignatureKey>, pub zen: Option<HeaderKey>, pub zsl: Option<BodyKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 934b072f14a..a7ea6e43e86 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -166,6 +166,7 @@ wellsfargo.base_url = "https://apitest.cybersource.com/" wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" +xendit.base_url = "https://api.xendit.co" wise.base_url = "https://api.sandbox.transferwise.tech/" zen.base_url = "https://api.zen-test.com/" zen.secondary_base_url = "https://secure.zen-test.com/" @@ -253,6 +254,7 @@ cards = [ "wise", "worldline", "worldpay", + "xendit", "zen", "zsl", ] diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 0ed38e8ef5d..9f1992bfa44 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -6,7 +6,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # Add new connector to existing list and sort it - connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay itaubank jpmorgan klarna mifinity mollie multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1") + connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay itaubank jpmorgan klarna mifinity mollie multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res="$(echo ${sorted[@]})" sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2024-11-18T10:24:16Z
## Description Template code added for new connector Xendit https://developers.xendit.co/api-reference ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/6597 ## How did you test it? Since this is template PR, no testing is required.
d32397f060731f51a15634e221117a554b8b3721
Since this is template PR, no testing is required.
[ "api-reference-v2/openapi_spec.json", "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/connector_enums.rs", "crates/common_enums/src/connector_enums.rs", "crates/connector_configs/src/connector.rs", "crates/hyperswitch_connectors/src/connectors.rs", "crates/hyperswitch_connectors/src/connectors/xendit.rs", "crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs", "crates/hyperswitch_connectors/src/default_implementations.rs", "crates/hyperswitch_connectors/src/default_implementations_v2.rs", "crates/hyperswitch_interfaces/src/configs.rs", "crates/router/src/connector.rs", "crates/router/src/types/api.rs", "crates/router/src/types/transformers.rs", "crates/router/tests/connectors/xendit.rs", "crates/test_utils/src/connector_auth.rs", "loadtest/config/development.toml", "scripts/add_connector.sh" ]
juspay/hyperswitch
juspay__hyperswitch-6524
Bug: [FEATURE] add permissions for operations in recon module ### Feature Description Reconciliation module in HyperSwitch provides various operations. Every operation needs to permitted for the end user to use it. As of today, recon has a single permission - which gives access to the entire recon module, this is not granular. Recon module's permission suite needs to be extended to be able to assign granular access for different operations. ### Possible Implementation Add permissions for below operations - Upload files - RW - Run recon - RW - View and update recon configs - RW - View and add file processing - RW - View Reports - R - View Analytics - R These are to be included in JWT in the response of `/recon/verify_token` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index c00afac6462..4af3f855d77 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -446,3 +446,20 @@ pub enum StripeChargeType { pub fn convert_frm_connector(connector_name: &str) -> Option<FrmConnectors> { FrmConnectors::from_str(connector_name).ok() } + +#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] +pub enum ReconPermissionScope { + #[serde(rename = "R")] + Read = 0, + #[serde(rename = "RW")] + Write = 1, +} + +impl From<PermissionScope> for ReconPermissionScope { + fn from(scope: PermissionScope) -> Self { + match scope { + PermissionScope::Read => Self::Read, + PermissionScope::Write => Self::Write, + } + } +} diff --git a/crates/api_models/src/events/recon.rs b/crates/api_models/src/events/recon.rs index aed648f4c86..596b0541282 100644 --- a/crates/api_models/src/events/recon.rs +++ b/crates/api_models/src/events/recon.rs @@ -1,6 +1,9 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; +use masking::PeekInterface; -use crate::recon::{ReconStatusResponse, ReconTokenResponse, ReconUpdateMerchantRequest}; +use crate::recon::{ + ReconStatusResponse, ReconTokenResponse, ReconUpdateMerchantRequest, VerifyTokenResponse, +}; impl ApiEventMetric for ReconUpdateMerchantRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { @@ -19,3 +22,11 @@ impl ApiEventMetric for ReconStatusResponse { Some(ApiEventsType::Recon) } } + +impl ApiEventMetric for VerifyTokenResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::User { + user_id: self.user_email.peek().to_string(), + }) + } +} diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 4dc2a1a301a..baac14e8afc 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -1,11 +1,7 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; -#[cfg(feature = "recon")] -use masking::PeekInterface; #[cfg(feature = "dummy_connector")] use crate::user::sample_data::SampleDataRequest; -#[cfg(feature = "recon")] -use crate::user::VerifyTokenResponse; use crate::user::{ dashboard_metadata::{ GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest, @@ -23,15 +19,6 @@ use crate::user::{ VerifyTotpRequest, }; -#[cfg(feature = "recon")] -impl ApiEventMetric for VerifyTokenResponse { - fn get_api_event_type(&self) -> Option<ApiEventsType> { - Some(ApiEventsType::User { - user_id: self.user_email.peek().to_string(), - }) - } -} - common_utils::impl_api_event_type!( Miscellaneous, ( diff --git a/crates/api_models/src/recon.rs b/crates/api_models/src/recon.rs index afee0fb5626..f73bcc5ae1f 100644 --- a/crates/api_models/src/recon.rs +++ b/crates/api_models/src/recon.rs @@ -1,4 +1,4 @@ -use common_utils::pii; +use common_utils::{id_type, pii}; use masking::Secret; use crate::enums; @@ -18,3 +18,11 @@ pub struct ReconTokenResponse { pub struct ReconStatusResponse { pub recon_status: enums::ReconStatus, } + +#[derive(serde::Serialize, Debug)] +pub struct VerifyTokenResponse { + pub merchant_id: id_type::MerchantId, + pub user_email: pii::Email, + #[serde(skip_serializing_if = "Option::is_none")] + pub acl: Option<String>, +} diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 089426c68ba..9c70ea895ad 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -167,13 +167,6 @@ pub struct SendVerifyEmailRequest { pub email: pii::Email, } -#[cfg(feature = "recon")] -#[derive(serde::Serialize, Debug)] -pub struct VerifyTokenResponse { - pub merchant_id: id_type::MerchantId, - pub user_email: pii::Email, -} - #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateUserAccountDetailsRequest { pub name: Option<Secret<String>>, diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 781b5e3710a..cb4281ee45c 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2819,9 +2819,15 @@ pub enum PermissionGroup { MerchantDetailsManage, // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, - ReconOps, AccountView, AccountManage, + ReconReportsView, + ReconReportsManage, + ReconOpsView, + // Alias is added for backward compatibility with database + // TODO: Remove alias post migration + #[serde(alias = "recon_ops")] + ReconOpsManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] @@ -2831,7 +2837,8 @@ pub enum ParentGroup { Workflows, Analytics, Users, - Recon, + ReconOps, + ReconReports, Account, } @@ -2854,7 +2861,13 @@ pub enum Resource { WebhookEvent, Payout, Report, - Recon, + ReconToken, + ReconFiles, + ReconAndSettlementAnalytics, + ReconUpload, + ReconReports, + RunRecon, + ReconConfig, } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs index 521c978e3c2..13cf4c488ec 100644 --- a/crates/router/src/core/recon.rs +++ b/crates/router/src/core/recon.rs @@ -1,100 +1,113 @@ use api_models::recon as recon_api; +#[cfg(feature = "email")] use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; +#[cfg(feature = "email")] use masking::{ExposeInterface, PeekInterface, Secret}; +#[cfg(feature = "email")] +use crate::{consts, services::email::types as email_types, types::domain}; use crate::{ - consts, - core::errors::{self, RouterResponse, UserErrors}, - services::{api as service_api, authentication, email::types as email_types}, + core::errors::{self, RouterResponse, UserErrors, UserResponse}, + services::{api as service_api, authentication}, types::{ api::{self as api_types, enums}, - domain, storage, + storage, transformers::ForeignTryFrom, }, SessionState, }; +#[allow(unused_variables)] pub async fn send_recon_request( state: SessionState, auth_data: authentication::AuthenticationDataWithUser, ) -> RouterResponse<recon_api::ReconStatusResponse> { - let user_in_db = &auth_data.user; - let merchant_id = auth_data.merchant_account.get_id().clone(); - - let user_email = user_in_db.email.clone(); - let email_contents = email_types::ProFeatureRequest { - feature_name: consts::RECON_FEATURE_TAG.to_string(), - merchant_id: merchant_id.clone(), - user_name: domain::UserName::new(user_in_db.name.clone()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to form username")?, - user_email: domain::UserEmail::from_pii_email(user_email.clone()) + #[cfg(not(feature = "email"))] + return Ok(service_api::ApplicationResponse::Json( + recon_api::ReconStatusResponse { + recon_status: enums::ReconStatus::NotRequested, + }, + )); + + #[cfg(feature = "email")] + { + let user_in_db = &auth_data.user; + let merchant_id = auth_data.merchant_account.get_id().clone(); + + let user_email = user_in_db.email.clone(); + let email_contents = email_types::ProFeatureRequest { + feature_name: consts::RECON_FEATURE_TAG.to_string(), + merchant_id: merchant_id.clone(), + user_name: domain::UserName::new(user_in_db.name.clone()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to form username")?, + user_email: domain::UserEmail::from_pii_email(user_email.clone()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert recipient's email to UserEmail")?, + recipient_email: domain::UserEmail::from_pii_email( + state.conf.email.recon_recipient_email.clone(), + ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert recipient's email to UserEmail")?, - recipient_email: domain::UserEmail::from_pii_email( - state.conf.email.recon_recipient_email.clone(), - ) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to convert recipient's email to UserEmail")?, - settings: state.conf.clone(), - subject: format!( - "{} {}", - consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST, - user_email.expose().peek() - ), - }; + subject: format!( + "{} {}", + consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST, + user_email.expose().peek() + ), + }; + state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to compose and send email for ProFeatureRequest [Recon]") + .async_and_then(|_| async { + let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { + recon_status: enums::ReconStatus::Requested, + }; + let db = &*state.store; + let key_manager_state = &(&state).into(); - state - .email_client - .compose_and_send_email( - Box::new(email_contents), - state.conf.proxy.https_url.as_ref(), - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to compose and send email for ProFeatureRequest [Recon]") - .async_and_then(|_| async { - let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { - recon_status: enums::ReconStatus::Requested, - }; - let db = &*state.store; - let key_manager_state = &(&state).into(); - - let response = db - .update_merchant( - key_manager_state, - auth_data.merchant_account, - updated_merchant_account, - &auth_data.key_store, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| { - format!("Failed while updating merchant's recon status: {merchant_id:?}") - })?; - - Ok(service_api::ApplicationResponse::Json( - recon_api::ReconStatusResponse { - recon_status: response.recon_status, - }, - )) - }) - .await + let response = db + .update_merchant( + key_manager_state, + auth_data.merchant_account, + updated_merchant_account, + &auth_data.key_store, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!("Failed while updating merchant's recon status: {merchant_id:?}") + })?; + + Ok(service_api::ApplicationResponse::Json( + recon_api::ReconStatusResponse { + recon_status: response.recon_status, + }, + )) + }) + .await + } } pub async fn generate_recon_token( state: SessionState, - user: authentication::UserFromToken, + user_with_role: authentication::UserFromTokenWithRoleInfo, ) -> RouterResponse<recon_api::ReconTokenResponse> { - let token = authentication::AuthToken::new_token( + let user = user_with_role.user; + let token = authentication::ReconToken::new_token( user.user_id.clone(), user.merchant_id.clone(), - user.role_id.clone(), &state.conf, user.org_id.clone(), user.profile_id.clone(), user.tenant_id, + user_with_role.role_info, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -138,29 +151,37 @@ pub async fn recon_merchant_account_update( format!("Failed while updating merchant's recon status: {merchant_id:?}") })?; - let user_email = &req.user_email.clone(); - let email_contents = email_types::ReconActivation { - recipient_email: domain::UserEmail::from_pii_email(user_email.clone()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to convert recipient's email to UserEmail from pii::Email")?, - user_name: domain::UserName::new(Secret::new("HyperSwitch User".to_string())) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to form username")?, - settings: state.conf.clone(), - subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST, - }; - - if req.recon_status == enums::ReconStatus::Active { - let _ = state - .email_client - .compose_and_send_email( - Box::new(email_contents), - state.conf.proxy.https_url.as_ref(), - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to compose and send email for ReconActivation") - .is_ok(); + #[cfg(feature = "email")] + { + let user_email = &req.user_email.clone(); + let email_contents = email_types::ReconActivation { + recipient_email: domain::UserEmail::from_pii_email(user_email.clone()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to convert recipient's email to UserEmail from pii::Email", + )?, + user_name: domain::UserName::new(Secret::new("HyperSwitch User".to_string())) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to form username")?, + subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST, + }; + if req.recon_status == enums::ReconStatus::Active { + let _ = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await + .inspect_err(|err| { + router_env::logger::error!( + "Failed to compose and send email notifying them of recon activation: {}", + err + ) + }) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to compose and send email for ReconActivation"); + } } Ok(service_api::ApplicationResponse::Json( @@ -170,3 +191,34 @@ pub async fn recon_merchant_account_update( })?, )) } + +pub async fn verify_recon_token( + state: SessionState, + user_with_role: authentication::UserFromTokenWithRoleInfo, +) -> UserResponse<recon_api::VerifyTokenResponse> { + let user = user_with_role.user; + let user_in_db = user + .get_user_from_db(&state) + .await + .attach_printable_lazy(|| { + format!( + "Failed to fetch the user from DB for user_id - {}", + user.user_id + ) + })?; + + let acl = user_with_role.role_info.get_recon_acl(); + let optional_acl_str = serde_json::to_string(&acl) + .inspect_err(|err| router_env::logger::error!("Failed to serialize acl to string: {}", err)) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to serialize acl to string. Using empty ACL") + .ok(); + + Ok(service_api::ApplicationResponse::Json( + recon_api::VerifyTokenResponse { + merchant_id: user.merchant_id.to_owned(), + user_email: user_in_db.0.email, + acl: optional_acl_str, + }, + )) +} diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 039e891e422..7ca4a127e85 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1593,27 +1593,6 @@ pub async fn send_verification_mail( Ok(ApplicationResponse::StatusOk) } -#[cfg(feature = "recon")] -pub async fn verify_token( - state: SessionState, - user: auth::UserFromToken, -) -> UserResponse<user_api::VerifyTokenResponse> { - let user_in_db = user - .get_user_from_db(&state) - .await - .attach_printable_lazy(|| { - format!( - "Failed to fetch the user from DB for user_id - {}", - user.user_id - ) - })?; - - Ok(ApplicationResponse::Json(user_api::VerifyTokenResponse { - merchant_id: user.merchant_id.to_owned(), - user_email: user_in_db.0.email, - })) -} - pub async fn update_user_details( state: SessionState, user_token: auth::UserFromToken, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index bb8d0d4f2bd..3d1474ee81a 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1216,7 +1216,10 @@ impl Recon { .service( web::resource("/request").route(web::post().to(recon_routes::request_for_recon)), ) - .service(web::resource("/verify_token").route(web::get().to(user::verify_recon_token))) + .service( + web::resource("/verify_token") + .route(web::get().to(recon_routes::verify_recon_token)), + ) } } diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs index cdc2ae758e9..cfd076c7100 100644 --- a/crates/router/src/routes/recon.rs +++ b/crates/router/src/routes/recon.rs @@ -38,7 +38,7 @@ pub async fn request_for_recon(state: web::Data<AppState>, http_req: HttpRequest (), |state, user, _, _| recon::send_recon_request(state, user), &authentication::JWTAuth { - permission: Permission::MerchantReconWrite, + permission: Permission::MerchantAccountWrite, }, api_locking::LockAction::NotApplicable, )) @@ -54,7 +54,24 @@ pub async fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> Ht (), |state, user, _, _| recon::generate_recon_token(state, user), &authentication::JWTAuth { - permission: Permission::MerchantReconWrite, + permission: Permission::MerchantReconTokenRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(feature = "recon")] +pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse { + let flow = Flow::ReconVerifyToken; + Box::pin(api::server_wrap( + flow, + state.clone(), + &http_req, + (), + |state, user, _req, _| recon::verify_recon_token(state, user), + &authentication::JWTAuth { + permission: Permission::MerchantReconTokenRead, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 8fc0dad452a..af55f7f3055 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -487,23 +487,6 @@ pub async fn verify_email_request( .await } -#[cfg(feature = "recon")] -pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse { - let flow = Flow::ReconVerifyToken; - Box::pin(api::server_wrap( - flow, - state.clone(), - &http_req, - (), - |state, user, _req, _| user_core::verify_token(state, user), - &auth::JWTAuth { - permission: Permission::MerchantReconWrite, - }, - api_locking::LockAction::NotApplicable, - )) - .await -} - pub async fn update_user_account_details( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 1967eafd180..58253684a27 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -90,6 +90,12 @@ pub struct AuthenticationDataWithUser { pub profile_id: id_type::ProfileId, } +#[derive(Clone)] +pub struct UserFromTokenWithRoleInfo { + pub user: UserFromToken, + pub role_info: authorization::roles::RoleInfo, +} + #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde( tag = "api_auth_type", @@ -3228,3 +3234,91 @@ where Ok((auth, auth_type)) } } + +#[cfg(feature = "recon")] +#[async_trait] +impl<A> AuthenticateAndFetch<UserFromTokenWithRoleInfo, A> for JWTAuth +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(UserFromTokenWithRoleInfo, AuthenticationType)> { + let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if payload.check_in_blacklist(state).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.permission, &role_info)?; + + let user = UserFromToken { + user_id: payload.user_id.clone(), + merchant_id: payload.merchant_id.clone(), + org_id: payload.org_id, + role_id: payload.role_id, + profile_id: payload.profile_id, + tenant_id: payload.tenant_id, + }; + + Ok(( + UserFromTokenWithRoleInfo { user, role_info }, + AuthenticationType::MerchantJwt { + merchant_id: payload.merchant_id, + user_id: Some(payload.user_id), + }, + )) + } +} + +#[cfg(feature = "recon")] +#[derive(serde::Serialize, serde::Deserialize)] +pub struct ReconToken { + pub user_id: String, + pub merchant_id: id_type::MerchantId, + pub role_id: String, + pub exp: u64, + pub org_id: id_type::OrganizationId, + pub profile_id: id_type::ProfileId, + pub tenant_id: Option<id_type::TenantId>, + #[serde(skip_serializing_if = "Option::is_none")] + pub acl: Option<String>, +} + +#[cfg(all(feature = "olap", feature = "recon"))] +impl ReconToken { + pub async fn new_token( + user_id: String, + merchant_id: id_type::MerchantId, + settings: &Settings, + org_id: id_type::OrganizationId, + profile_id: id_type::ProfileId, + tenant_id: Option<id_type::TenantId>, + role_info: authorization::roles::RoleInfo, + ) -> UserResult<String> { + let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); + let exp = jwt::generate_exp(exp_duration)?.as_secs(); + let acl = role_info.get_recon_acl(); + let optional_acl_str = serde_json::to_string(&acl) + .inspect_err(|err| logger::error!("Failed to serialize acl to string: {}", err)) + .change_context(errors::UserErrors::InternalServerError) + .attach_printable("Failed to serialize acl to string. Using empty ACL") + .ok(); + let token_payload = Self { + user_id, + merchant_id, + role_id: role_info.get_role_id().to_string(), + exp, + org_id, + profile_id, + tenant_id, + acl: optional_acl_str, + }; + jwt::generate_jwt(&token_payload, settings).await + } +} diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index bd987e2fe9a..2d808a4377a 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -40,7 +40,10 @@ fn get_group_description(group: PermissionGroup) -> &'static str { PermissionGroup::MerchantDetailsView | PermissionGroup::AccountView => "View Merchant Details", PermissionGroup::MerchantDetailsManage | PermissionGroup::AccountManage => "Create, modify and delete Merchant Details like api keys, webhooks, etc", PermissionGroup::OrganizationManage => "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc", - PermissionGroup::ReconOps => "View and manage reconciliation reports", + PermissionGroup::ReconReportsView => "View and access reconciliation reports and analytics", + PermissionGroup::ReconReportsManage => "Manage reconciliation reports", + PermissionGroup::ReconOpsView => "View and access reconciliation operations", + PermissionGroup::ReconOpsManage => "Manage reconciliation operations", } } @@ -52,6 +55,7 @@ pub fn get_parent_group_description(group: ParentGroup) -> &'static str { ParentGroup::Analytics => "View Analytics", ParentGroup::Users => "Manage and invite Users to the Team", ParentGroup::Account => "Create, modify and delete Merchant Details like api keys, webhooks, etc", - ParentGroup::Recon => "View and manage reconciliation reports", + ParentGroup::ReconOps => "View, manage reconciliation operations like upload and process files, run reconciliation etc", + ParentGroup::ReconReports => "View, manage reconciliation reports and analytics", } } diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs index 57c385565a8..7ca8442c1ce 100644 --- a/crates/router/src/services/authorization/permission_groups.rs +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -21,7 +21,9 @@ impl PermissionGroupExt for PermissionGroup { | Self::AnalyticsView | Self::UsersView | Self::MerchantDetailsView - | Self::AccountView => PermissionScope::Read, + | Self::AccountView + | Self::ReconOpsView + | Self::ReconReportsView => PermissionScope::Read, Self::OperationsManage | Self::ConnectorsManage @@ -29,8 +31,9 @@ impl PermissionGroupExt for PermissionGroup { | Self::UsersManage | Self::MerchantDetailsManage | Self::OrganizationManage - | Self::ReconOps - | Self::AccountManage => PermissionScope::Write, + | Self::AccountManage + | Self::ReconOpsManage + | Self::ReconReportsManage => PermissionScope::Write, } } @@ -41,12 +44,13 @@ impl PermissionGroupExt for PermissionGroup { Self::WorkflowsView | Self::WorkflowsManage => ParentGroup::Workflows, Self::AnalyticsView => ParentGroup::Analytics, Self::UsersView | Self::UsersManage => ParentGroup::Users, - Self::ReconOps => ParentGroup::Recon, Self::MerchantDetailsView | Self::OrganizationManage | Self::MerchantDetailsManage | Self::AccountView | Self::AccountManage => ParentGroup::Account, + Self::ReconOpsView | Self::ReconOpsManage => ParentGroup::ReconOps, + Self::ReconReportsView | Self::ReconReportsManage => ParentGroup::ReconReports, } } @@ -76,7 +80,11 @@ impl PermissionGroupExt for PermissionGroup { vec![Self::UsersView, Self::UsersManage] } - Self::ReconOps => vec![Self::ReconOps], + Self::ReconOpsView => vec![Self::ReconOpsView], + Self::ReconOpsManage => vec![Self::ReconOpsView, Self::ReconOpsManage], + + Self::ReconReportsView => vec![Self::ReconReportsView], + Self::ReconReportsManage => vec![Self::ReconReportsView, Self::ReconReportsManage], Self::MerchantDetailsView => vec![Self::MerchantDetailsView], Self::MerchantDetailsManage => { @@ -108,7 +116,8 @@ impl ParentGroupExt for ParentGroup { Self::Analytics => ANALYTICS.to_vec(), Self::Users => USERS.to_vec(), Self::Account => ACCOUNT.to_vec(), - Self::Recon => RECON.to_vec(), + Self::ReconOps => RECON_OPS.to_vec(), + Self::ReconReports => RECON_REPORTS.to_vec(), } } @@ -167,4 +176,18 @@ pub static USERS: [Resource; 2] = [Resource::User, Resource::Account]; pub static ACCOUNT: [Resource; 3] = [Resource::Account, Resource::ApiKey, Resource::WebhookEvent]; -pub static RECON: [Resource; 1] = [Resource::Recon]; +pub static RECON_OPS: [Resource; 7] = [ + Resource::ReconToken, + Resource::ReconFiles, + Resource::ReconUpload, + Resource::RunRecon, + Resource::ReconConfig, + Resource::ReconAndSettlementAnalytics, + Resource::ReconReports, +]; + +pub static RECON_REPORTS: [Resource; 3] = [ + Resource::ReconToken, + Resource::ReconAndSettlementAnalytics, + Resource::ReconReports, +]; diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 6e472d55623..6f612007425 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -67,8 +67,32 @@ generate_permissions! { scopes: [Read, Write], entities: [Merchant] }, - Recon: { - scopes: [Write], + ReconToken: { + scopes: [Read], + entities: [Merchant] + }, + ReconFiles: { + scopes: [Read, Write], + entities: [Merchant] + }, + ReconAndSettlementAnalytics: { + scopes: [Read], + entities: [Merchant] + }, + ReconUpload: { + scopes: [Read, Write], + entities: [Merchant] + }, + ReconReports: { + scopes: [Read, Write], + entities: [Merchant] + }, + RunRecon: { + scopes: [Read, Write], + entities: [Merchant] + }, + ReconConfig: { + scopes: [Read, Write], entities: [Merchant] }, ] @@ -91,7 +115,13 @@ pub fn get_resource_name(resource: &Resource, entity_type: &EntityType) -> &'sta (Resource::Report, _) => "Operation Reports", (Resource::User, _) => "Users", (Resource::WebhookEvent, _) => "Webhook Events", - (Resource::Recon, _) => "Reconciliation Reports", + (Resource::ReconUpload, _) => "Reconciliation File Upload", + (Resource::RunRecon, _) => "Run Reconciliation Process", + (Resource::ReconConfig, _) => "Reconciliation Configurations", + (Resource::ReconToken, _) => "Generate & Verify Reconciliation Token", + (Resource::ReconFiles, _) => "Reconciliation Process Manager", + (Resource::ReconReports, _) => "Reconciliation Reports", + (Resource::ReconAndSettlementAnalytics, _) => "Reconciliation Analytics", (Resource::Account, EntityType::Profile) => "Business Profile Account", (Resource::Account, EntityType::Merchant) => "Merchant Account", (Resource::Account, EntityType::Organization) => "Organization Account", diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs index bf66eb92466..f6c4f4b9ef2 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -1,8 +1,14 @@ +#[cfg(feature = "recon")] +use std::collections::HashMap; use std::collections::HashSet; +#[cfg(feature = "recon")] +use api_models::enums::ReconPermissionScope; use common_enums::{EntityType, PermissionGroup, Resource, RoleScope}; use common_utils::{errors::CustomResult, id_type}; +#[cfg(feature = "recon")] +use super::permission_groups::{RECON_OPS, RECON_REPORTS}; use super::{permission_groups::PermissionGroupExt, permissions::Permission}; use crate::{core::errors, routes::SessionState}; @@ -78,6 +84,38 @@ impl RoleInfo { }) } + #[cfg(feature = "recon")] + pub fn get_recon_acl(&self) -> HashMap<Resource, ReconPermissionScope> { + let mut acl: HashMap<Resource, ReconPermissionScope> = HashMap::new(); + let mut recon_resources = RECON_OPS.to_vec(); + recon_resources.extend(RECON_REPORTS); + let recon_internal_resources = [Resource::ReconToken]; + self.get_permission_groups() + .iter() + .for_each(|permission_group| { + permission_group.resources().iter().for_each(|resource| { + if recon_resources.contains(resource) + && !recon_internal_resources.contains(resource) + { + let scope = match resource { + Resource::ReconAndSettlementAnalytics => ReconPermissionScope::Read, + _ => ReconPermissionScope::from(permission_group.scope()), + }; + acl.entry(*resource) + .and_modify(|curr_scope| { + *curr_scope = if (*curr_scope) < scope { + scope + } else { + *curr_scope + } + }) + .or_insert(scope); + } + }) + }); + acl + } + pub async fn from_role_id_in_merchant_scope( state: &SessionState, role_id: &str, diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs index 39f6d47f824..9c67c12f527 100644 --- a/crates/router/src/services/authorization/roles/predefined_roles.rs +++ b/crates/router/src/services/authorization/roles/predefined_roles.rs @@ -28,7 +28,10 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsManage, PermissionGroup::AccountManage, PermissionGroup::OrganizationManage, - PermissionGroup::ReconOps, + PermissionGroup::ReconOpsView, + PermissionGroup::ReconOpsManage, + PermissionGroup::ReconReportsView, + PermissionGroup::ReconReportsManage, ], role_id: common_utils::consts::ROLE_ID_INTERNAL_ADMIN.to_string(), role_name: "internal_admin".to_string(), @@ -51,6 +54,8 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, PermissionGroup::AccountView, + PermissionGroup::ReconOpsView, + PermissionGroup::ReconReportsView, ], role_id: common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(), role_name: "internal_view_only".to_string(), @@ -82,7 +87,10 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsManage, PermissionGroup::AccountManage, PermissionGroup::OrganizationManage, - PermissionGroup::ReconOps, + PermissionGroup::ReconOpsView, + PermissionGroup::ReconOpsManage, + PermissionGroup::ReconReportsView, + PermissionGroup::ReconReportsManage, ], role_id: common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), role_name: "organization_admin".to_string(), @@ -113,7 +121,10 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::AccountView, PermissionGroup::MerchantDetailsManage, PermissionGroup::AccountManage, - PermissionGroup::ReconOps, + PermissionGroup::ReconOpsView, + PermissionGroup::ReconOpsManage, + PermissionGroup::ReconReportsView, + PermissionGroup::ReconReportsManage, ], role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), role_name: "merchant_admin".to_string(), @@ -136,6 +147,8 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, PermissionGroup::AccountView, + PermissionGroup::ReconOpsView, + PermissionGroup::ReconReportsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(), role_name: "merchant_view_only".to_string(), @@ -180,6 +193,8 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::AccountView, PermissionGroup::MerchantDetailsManage, PermissionGroup::AccountManage, + PermissionGroup::ReconOpsView, + PermissionGroup::ReconReportsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(), role_name: "merchant_developer".to_string(), @@ -203,6 +218,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, PermissionGroup::AccountView, + PermissionGroup::ReconOpsView, + PermissionGroup::ReconOpsManage, + PermissionGroup::ReconReportsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(), role_name: "merchant_operator".to_string(), @@ -223,6 +241,8 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, PermissionGroup::AccountView, + PermissionGroup::ReconOpsView, + PermissionGroup::ReconReportsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(), role_name: "customer_support".to_string(), diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 8c966d79d80..66e730f0824 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -383,7 +383,6 @@ impl EmailData for InviteUser { pub struct ReconActivation { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, - pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, } @@ -458,7 +457,6 @@ pub struct ProFeatureRequest { pub merchant_id: common_utils::id_type::MerchantId, pub user_name: domain::UserName, pub user_email: domain::UserEmail, - pub settings: std::sync::Arc<configs::Settings>, pub subject: String, }
2024-11-18T06:24:02Z
## Description Described in #6524 This PR includes below changes - Extending resources enum (for specifying the resource being consumed from the dashboard) - Extending granular permission groups for recon - Populating `acl` field in the recon token ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Helps maintain and configure permissions for recon module granularly. ## How did you test it? - Verify the generated recon token has `acl` - `GET /verify_token` response to have `acl` <details> <summary>Check /verify_token response</summary> cURL curl --location --request GET 'http://localhost:8080/recon/verify_token' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZGJjMzJmMmYtYmI5Ni00MDI0LTliYTUtNjhkOTc3MzM0N2U5IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzMxOTk2NjQ4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjE4MzU4Miwib3JnX2lkIjoib3JnX0htMmY5dERZM2lGN0ZRckZUYUxKIiwicHJvZmlsZV9pZCI6InByb19GY0NaN1c4MllZVmNXMU1DSjZIOCIsInRlbmFudF9pZCI6InB1YmxpYyIsImFjbCI6IntcInJlY29uX2ZpbGVzXCI6XCJSV1wiLFwicmVjb25fY29uZmlnXCI6XCJSV1wiLFwicmVjb25fdG9rZW5cIjpcIlJXXCIsXCJyZWNvbl9yZXBvcnRzXCI6XCJSV1wiLFwicmVjb25fdXBsb2FkXCI6XCJSV1wiLFwicnVuX3JlY29uXCI6XCJSV1wiLFwicmVjb25fYW5kX3NldHRsZW1lbnRfYW5hbHl0aWNzXCI6XCJSXCJ9In0.wvS97F0dXwY7Y5uKSk8PEqHOhoAAPlR0coX_kIGyM2I' Response { "merchant_id": "merchant_1731996648", "user_email": "kashif2@juspay.in", "acl": "{\"recon_reports\":\"RW\",\"recon_files\":\"RW\",\"run_recon\":\"RW\",\"recon_and_settlement_analytics\":\"R\",\"recon_token\":\"RW\",\"recon_upload\":\"RW\",\"recon_config\":\"RW\"}" } </details>
79a75ce65418f21da7250e1538d0990047ba52d9
- Verify the generated recon token has `acl` - `GET /verify_token` response to have `acl` <details> <summary>Check /verify_token response</summary> cURL curl --location --request GET 'http://localhost:8080/recon/verify_token' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZGJjMzJmMmYtYmI5Ni00MDI0LTliYTUtNjhkOTc3MzM0N2U5IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzMxOTk2NjQ4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjE4MzU4Miwib3JnX2lkIjoib3JnX0htMmY5dERZM2lGN0ZRckZUYUxKIiwicHJvZmlsZV9pZCI6InByb19GY0NaN1c4MllZVmNXMU1DSjZIOCIsInRlbmFudF9pZCI6InB1YmxpYyIsImFjbCI6IntcInJlY29uX2ZpbGVzXCI6XCJSV1wiLFwicmVjb25fY29uZmlnXCI6XCJSV1wiLFwicmVjb25fdG9rZW5cIjpcIlJXXCIsXCJyZWNvbl9yZXBvcnRzXCI6XCJSV1wiLFwicmVjb25fdXBsb2FkXCI6XCJSV1wiLFwicnVuX3JlY29uXCI6XCJSV1wiLFwicmVjb25fYW5kX3NldHRsZW1lbnRfYW5hbHl0aWNzXCI6XCJSXCJ9In0.wvS97F0dXwY7Y5uKSk8PEqHOhoAAPlR0coX_kIGyM2I' Response { "merchant_id": "merchant_1731996648", "user_email": "kashif2@juspay.in", "acl": "{\"recon_reports\":\"RW\",\"recon_files\":\"RW\",\"run_recon\":\"RW\",\"recon_and_settlement_analytics\":\"R\",\"recon_token\":\"RW\",\"recon_upload\":\"RW\",\"recon_config\":\"RW\"}" } </details>
[ "crates/api_models/src/enums.rs", "crates/api_models/src/events/recon.rs", "crates/api_models/src/events/user.rs", "crates/api_models/src/recon.rs", "crates/api_models/src/user.rs", "crates/common_enums/src/enums.rs", "crates/router/src/core/recon.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/recon.rs", "crates/router/src/routes/user.rs", "crates/router/src/services/authentication.rs", "crates/router/src/services/authorization/info.rs", "crates/router/src/services/authorization/permission_groups.rs", "crates/router/src/services/authorization/permissions.rs", "crates/router/src/services/authorization/roles.rs", "crates/router/src/services/authorization/roles/predefined_roles.rs", "crates/router/src/services/email/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6645
Bug: [FEAT] Multiple credential support for a connector in Cypress ## Requirement Execute cypress tests for a connector having **multiple credentials** which can be used for different scenarios (one api key for `cards`, another for `bank redirects` and etc.,). ## Implementation ### Introduce new format for `creds.json` `creds.json` should include both the formats. if a connector requires us passing **multiple credentials**, then that connector api key object **should** include multiple `connector_account_details` object all named under a generic name `connector_<number>` where `number` is an `integer`. Refer example given below for more clarity: ```json // connector having multiple credentials <connector_name_1>: { "connector_1": { "connector_account_details": { "auth_type": "KeyType", "api_key": "", "api_secret": "", "key1": "", "key2": "" }, "metadata": {} }, "connector_2": { "connector_account_details": { "auth_type": "KeyType", "api_key": "", "api_secret": "", "key1": "", "key2": "" }, "metadata": {} }, }, // connector with a single credential <connector_name_2>: { "connector_account_details": { "auth_type": "KeyType", "api_key": "", "api_secret": "", "key1": "", "key2": "" } } ``` ### Introduce new `object` (`Configs`) for `connector.js` Within `connector.js`, introduce new object called as `Configs` alongside to `Request` and `Response` where user can define `flags` to achieve granular control over what test is being run. An example implementation given below for reference: ```js getCustomExchange({ Configs: { TRIGGER_SKIP: true, // skips redirection flow from running. takes in a boolean DELAY: { STATUS: true, // flag to turn delay feature on or off. takes in a boolean TIMEOUT: 5000, // timeout in milliseconds }, CONNECTOR_CREDENTIAL: connector_1 / connector_2 // flag to route tests to a specific profile // etc., }, Requst: {}, Response: {} }), ``` ### Modify `getValueByKey` function in `Utils.js` Validate if `connector_account_details` dot exist within `<connector>` object in creds. If it does not, start a loop and see if `connector_account_details` exist within every object. If true, return the `connector_account_details` while setting an object as a Cypress environment flag (`MULTIPLE_CONNECTORS`) with status `true` and length. If any validation fails, directly return the object (`data[key]`). An example implementation given below for reference: ```js if (data && typeof data === "object" && key in data) { // Connector object has multiple keys if (typeof data[key].connector_account_details === "undefined") { const keys = Object.keys(data[key]); for (let i = 0; i < keys.length; i++) { const currentItem = data[key][keys[i]]; if (currentItem.hasOwnProperty("connector_account_details")) { Cypress.env("MULTIPLE_CONNECTORS", { status: true, count: keys.length, }); return currentItem; } } } return data[key]; } else { return null; } ``` ### Add a new test to MCA create call If `MULTIPLE_CONNECTORS.status` is `TRUE`. Check `MULTIPLE_CONNECTORS.count` and create `profile` and `mca` beneath that `profile` based on the number of `count`. An example of possible implementation given below for reference: ```js if (Cypress.env("MULTIPLE_CONNECTORS")?.status) { for (let i = 0; i < Cypress.env("MULTIPLE_CONNECTORS").count; i++) { cy.createBusinessProfileTest( createBusinessProfileBody, globalState, "profile" + i // new optional fields ); cy.createConnectorCallTest( "payment_processor", createConnectorBody, payment_methods_enabled, globalState, "profile" + i, // new optional fields "merchantConnector" + i // new optional fields ); } } ``` Store these created `profile_id`s and `mca`s in `globalState` for future usage. Pass `CONNECTOR_CREDENTIAL` value as `connector_1` or `connector_2` in `<connector>.js` In `commands.js`, `execute` these configs before a `request` has been made. `execute` here means to make these configs work. Preferably, make this execution of configs a function and pass the values accordingly along with trace to find from where the function has been called. ## Limitations - Cypress cannot call itself unless a wrapper around Cypress is written (`Rustpress`?) - This stops us from running the entire test suite against every credentials - One possible work around for this is to have multiple keys (`cybersource_1`, `cybersource_2`) but this will result in a lot of confusion - Current implementation **requires** the user to mandatorily pass a `CONNECTOR_CREDENTIAL` config to pass a different `profileId` - Hence, the tests will only run once but, specific tests like `incremental auth` will be forced to run against different credential - `00025-IncrementalAuth.cy.js` can be stopped from execution based on `MULTIPLE_CONNECTORS` environment variable as it is set during run time and the file is read asynchronously when the execution starts (to address this, we will have to make a function call to see if it is set during run time and it is, then skip)
2024-11-17T07:12:09Z
## Description <!-- Describe your changes in detail --> This PR introduces 2 new features: - Multiple credentials for a connector - Configuration flags closes #6645 (check this issue for detailed documentation / flow / explanation) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - We need to run tests against multiple connector api keys for a single connector - We also need configuration flag support to selectively grant a test certain features / options ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Only Cybersource with `multiple creds` (takes only from first `connector_1`): <img width="594" alt="image" src="https://github.com/user-attachments/assets/7c05742c-6331-417a-8699-731285463560"> Cybersource with `multiple creds` (along with `incremental auth`): <img width="554" alt="image" src="https://github.com/user-attachments/assets/664defa0-2fa4-4189-82f1-987421a48374"> (incremental auth fails from the connector's end and hence 4 failures) Stripe: <img width="676" alt="image" src="https://github.com/user-attachments/assets/cc1f2c16-bc9d-417e-94da-18870d9399cd"> Wise: <img width="567" alt="image" src="https://github.com/user-attachments/assets/512e8bbc-c979-4791-8263-3253e61e193c"> PML: <img width="549" alt="image" src="https://github.com/user-attachments/assets/e53a72e0-fddc-4351-8557-07058e223be8"> have disabled incremental auth from executing: <img width="680" alt="image" src="https://github.com/user-attachments/assets/e2cd2e96-326e-422a-a9c4-21bd5a2b86c2"> trustpay refunds (multiple creds): <img width="675" alt="image" src="https://github.com/user-attachments/assets/7fcb908f-de34-4d28-ac10-e4082ad3d54c"> i commented iDEAL redirections to check, error is being thrown from connector's end and there's nothing much i can do: <img width="607" alt="image" src="https://github.com/user-attachments/assets/689979c8-d044-4b5f-a5a8-9ea8e15860e1"> <img width="1364" alt="image" src="https://github.com/user-attachments/assets/b0261af6-68c7-445f-af79-5e9d16bdc7fa"> <img width="555" alt="image" src="https://github.com/user-attachments/assets/fae0d997-695b-4db2-8f3e-0afad44c9c3e">
797a0db7733c5b387564fb1bbc106d054c8dffa6
Only Cybersource with `multiple creds` (takes only from first `connector_1`): <img width="594" alt="image" src="https://github.com/user-attachments/assets/7c05742c-6331-417a-8699-731285463560"> Cybersource with `multiple creds` (along with `incremental auth`): <img width="554" alt="image" src="https://github.com/user-attachments/assets/664defa0-2fa4-4189-82f1-987421a48374"> (incremental auth fails from the connector's end and hence 4 failures) Stripe: <img width="676" alt="image" src="https://github.com/user-attachments/assets/cc1f2c16-bc9d-417e-94da-18870d9399cd"> Wise: <img width="567" alt="image" src="https://github.com/user-attachments/assets/512e8bbc-c979-4791-8263-3253e61e193c"> PML: <img width="549" alt="image" src="https://github.com/user-attachments/assets/e53a72e0-fddc-4351-8557-07058e223be8"> have disabled incremental auth from executing: <img width="680" alt="image" src="https://github.com/user-attachments/assets/e2cd2e96-326e-422a-a9c4-21bd5a2b86c2"> trustpay refunds (multiple creds): <img width="675" alt="image" src="https://github.com/user-attachments/assets/7fcb908f-de34-4d28-ac10-e4082ad3d54c"> i commented iDEAL redirections to check, error is being thrown from connector's end and there's nothing much i can do: <img width="607" alt="image" src="https://github.com/user-attachments/assets/689979c8-d044-4b5f-a5a8-9ea8e15860e1"> <img width="1364" alt="image" src="https://github.com/user-attachments/assets/b0261af6-68c7-445f-af79-5e9d16bdc7fa"> <img width="555" alt="image" src="https://github.com/user-attachments/assets/fae0d997-695b-4db2-8f3e-0afad44c9c3e">
[]
juspay/hyperswitch
juspay__hyperswitch-6577
Bug: [BUG] FATAL: role "root" does not exist ### Bug Description Whenever hyperswitch-pg-1 sever running in docker-compose, it though an error " role "root" does not exist" ### Expected Behavior Error should not come. ### Actual Behavior ![Screenshot from 2024-11-14 19-27-00](https://github.com/user-attachments/assets/fc92e35a-8b2f-4023-b155-73e28ae8cf98) ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Open Docker Desktop 2. Run hyperswitch-pg-1 server 3. After some time, you will see the error ### Context For The Bug While setting hyperswitch on my local machine, I came across this error. ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: Ubuntu 24.04 2. Rust version (output of `rustc --version`): ``: rustc 1.82.0 (f6e511eec 2024-10-15) 3. App version (output of `cargo r --features vergen -- --version`): `` NA ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/docker-compose-development.yml b/docker-compose-development.yml index 07a2131c6d4..d7a0e365c36 100644 --- a/docker-compose-development.yml +++ b/docker-compose-development.yml @@ -26,7 +26,7 @@ services: - POSTGRES_PASSWORD=db_pass - POSTGRES_DB=hyperswitch_db healthcheck: - test: ["CMD-SHELL", "pg_isready"] + test: ["CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}"] interval: 5s retries: 3 start_period: 5s diff --git a/docker-compose.yml b/docker-compose.yml index f766ff91053..7450a650119 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -21,7 +21,7 @@ services: - POSTGRES_PASSWORD=db_pass - POSTGRES_DB=hyperswitch_db healthcheck: - test: ["CMD-SHELL", "pg_isready"] + test: ["CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}"] interval: 5s retries: 3 start_period: 5s
2024-11-15T08:47:23Z
## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #6577. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
0805a937b1bc12ac1dfb23922036733ed971a87a
[ "docker-compose-development.yml", "docker-compose.yml" ]
juspay/hyperswitch
juspay__hyperswitch-6580
Bug: chore(infra): SDK Table schema sanity Editing SDK Tables schema in the codebase for end to end ( ingestion to querying on dashboard ) sanity
diff --git a/crates/analytics/docs/clickhouse/scripts/sdk_events.sql b/crates/analytics/docs/clickhouse/scripts/sdk_events.sql index bfe6401cacc..c5c70cc9e66 100644 --- a/crates/analytics/docs/clickhouse/scripts/sdk_events.sql +++ b/crates/analytics/docs/clickhouse/scripts/sdk_events.sql @@ -6,7 +6,7 @@ CREATE TABLE sdk_events_queue ( `event_name` LowCardinality(Nullable(String)), `first_event` LowCardinality(Nullable(String)), `latency` Nullable(UInt32), - `timestamp` String, + `timestamp` DateTime64(3), `browser_name` LowCardinality(Nullable(String)), `browser_version` Nullable(String), `platform` LowCardinality(Nullable(String)), @@ -115,7 +115,8 @@ CREATE TABLE sdk_events_audit ( `remote_ip` Nullable(String), `log_type` LowCardinality(Nullable(String)), `event_name` LowCardinality(Nullable(String)), - `first_event` Bool DEFAULT 1, + `first_event` Bool, + `latency` Nullable(UInt32), `browser_name` LowCardinality(Nullable(String)), `browser_version` Nullable(String), `platform` LowCardinality(Nullable(String)), @@ -125,10 +126,10 @@ CREATE TABLE sdk_events_audit ( `value` Nullable(String), `component` LowCardinality(Nullable(String)), `payment_method` LowCardinality(Nullable(String)), - `payment_experience` LowCardinality(Nullable(String)) DEFAULT '', - `created_at` DateTime64(3) DEFAULT now64() CODEC(T64, LZ4), - `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), - `latency` Nullable(UInt32) DEFAULT 0 + `payment_experience` LowCardinality(Nullable(String)), + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `created_at_precise` DateTime64(3), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4) ) ENGINE = MergeTree PARTITION BY merchant_id ORDER BY (merchant_id, payment_id) @@ -156,7 +157,7 @@ WHERE length(_error) > 0; CREATE MATERIALIZED VIEW sdk_events_audit_mv TO sdk_events_audit ( - `payment_id` Nullable(String), + `payment_id` String, `merchant_id` String, `remote_ip` Nullable(String), `log_type` LowCardinality(Nullable(String)),
2024-11-14T16:36:06Z
## Description <!-- Describe your changes in detail --> Updating SDK table schema ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> crates/analytics/docs/clickhouse/scripts/sdk_events.sql ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This resolves the issue people face for SDK Events table API on dashboard is using the sdk_events_audit table ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Schema structure changes for sdk table. Nothing to test.
15f873bd1296169149987041f4008b0afe2ac2aa
Schema structure changes for sdk table. Nothing to test.
[ "crates/analytics/docs/clickhouse/scripts/sdk_events.sql" ]
juspay/hyperswitch
juspay__hyperswitch-6574
Bug: feat(analytics): add `smart_retries` only metrics ## Proposed changes There should be fields in PaymentDistribution, for the case where we only want to extract metric for Subsequent smart retried attempts. For example, we have `success_rate` and `success_rate_without_retries` Now missing field is `success_rate_with_only_smart_retries`. This change should be extended to all fields
diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs index 651eeb0bcfe..c4e48300d07 100644 --- a/crates/analytics/src/payments/accumulator.rs +++ b/crates/analytics/src/payments/accumulator.rs @@ -76,8 +76,11 @@ pub struct PaymentsDistributionAccumulator { pub failed: u32, pub total: u32, pub success_without_retries: u32, + pub success_with_only_retries: u32, pub failed_without_retries: u32, + pub failed_with_only_retries: u32, pub total_without_retries: u32, + pub total_with_only_retries: u32, } pub trait PaymentMetricAccumulator { @@ -181,7 +184,14 @@ impl PaymentMetricAccumulator for SuccessRateAccumulator { } impl PaymentMetricAccumulator for PaymentsDistributionAccumulator { - type MetricOutput = (Option<f64>, Option<f64>, Option<f64>, Option<f64>); + type MetricOutput = ( + Option<f64>, + Option<f64>, + Option<f64>, + Option<f64>, + Option<f64>, + Option<f64>, + ); fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { if let Some(ref status) = metrics.status { @@ -193,6 +203,8 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator { self.success += success; if metrics.first_attempt.unwrap_or(false) { self.success_without_retries += success; + } else { + self.success_with_only_retries += success; } } } @@ -201,6 +213,8 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator { self.failed += failed; if metrics.first_attempt.unwrap_or(false) { self.failed_without_retries += failed; + } else { + self.failed_with_only_retries += failed; } } } @@ -208,6 +222,8 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator { self.total += total; if metrics.first_attempt.unwrap_or(false) { self.total_without_retries += total; + } else { + self.total_with_only_retries += total; } } } @@ -215,14 +231,17 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator { fn collect(self) -> Self::MetricOutput { if self.total == 0 { - (None, None, None, None) + (None, None, None, None, None, None) } else { let success = Some(self.success); let success_without_retries = Some(self.success_without_retries); + let success_with_only_retries = Some(self.success_with_only_retries); let failed = Some(self.failed); + let failed_with_only_retries = Some(self.failed_with_only_retries); let failed_without_retries = Some(self.failed_without_retries); let total = Some(self.total); let total_without_retries = Some(self.total_without_retries); + let total_with_only_retries = Some(self.total_with_only_retries); let success_rate = match (success, total) { (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), @@ -235,6 +254,12 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator { _ => None, }; + let success_rate_with_only_retries = + match (success_with_only_retries, total_with_only_retries) { + (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + let failed_rate = match (failed, total) { (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, @@ -245,11 +270,19 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator { (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, }; + + let failed_rate_with_only_retries = + match (failed_with_only_retries, total_with_only_retries) { + (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; ( success_rate, success_rate_without_retries, + success_rate_with_only_retries, failed_rate, failed_rate_without_retries, + failed_rate_with_only_retries, ) } } @@ -393,8 +426,10 @@ impl PaymentMetricsAccumulator { let ( payments_success_rate_distribution, payments_success_rate_distribution_without_smart_retries, + payments_success_rate_distribution_with_only_retries, payments_failure_rate_distribution, payments_failure_rate_distribution_without_smart_retries, + payments_failure_rate_distribution_with_only_retries, ) = self.payments_distribution.collect(); let (failure_reason_count, failure_reason_count_without_smart_retries) = self.failure_reasons_distribution.collect(); @@ -413,8 +448,10 @@ impl PaymentMetricsAccumulator { connector_success_rate: self.connector_success_rate.collect(), payments_success_rate_distribution, payments_success_rate_distribution_without_smart_retries, + payments_success_rate_distribution_with_only_retries, payments_failure_rate_distribution, payments_failure_rate_distribution_without_smart_retries, + payments_failure_rate_distribution_with_only_retries, failure_reason_count, failure_reason_count_without_smart_retries, payment_processed_amount_usd, diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs index 1faba79eb37..70b1da62bea 100644 --- a/crates/api_models/src/analytics/payments.rs +++ b/crates/api_models/src/analytics/payments.rs @@ -283,8 +283,10 @@ pub struct PaymentMetricsBucketValue { pub connector_success_rate: Option<f64>, pub payments_success_rate_distribution: Option<f64>, pub payments_success_rate_distribution_without_smart_retries: Option<f64>, + pub payments_success_rate_distribution_with_only_retries: Option<f64>, pub payments_failure_rate_distribution: Option<f64>, pub payments_failure_rate_distribution_without_smart_retries: Option<f64>, + pub payments_failure_rate_distribution_with_only_retries: Option<f64>, pub failure_reason_count: Option<u64>, pub failure_reason_count_without_smart_retries: Option<u64>, }
2024-11-14T13:37:40Z
## Description <!-- Describe your changes in detail --> Added support for calculating new metrics based on smart retries for Analytics v2 dashboard. The 2 metrics are: - Payment Processed Amount and Count for smart retries - Payments Success Rate and Failure Rate distribution for Smart Retries `Payment Processed Amount and Count for Smart Retries` can be calculated with the existing metrics, with just a subtraction of `payment_processed_amount_without_smart_retries` from `payment_processed_amount`, hence doesn't require a separate metric. In the `PaymentDistributionAccumulator`, I added another field variant with the signature `<field_name>_with_only_smart_retries`. Where `field_name` can be anything from `success_rate`, `failure_rate`. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #6574 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### Request - Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStat' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTY1MTcyMCwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.gtctUL339INfdj6CVmZLW2NDMNcseMTCPX0uxSsOD1c' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-07T01:30:00Z", "endTime": "2024-11-09T23:30:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "payments_distribution" ], "delta": true } ]' ``` ### Response ```json { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_amount_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": 66.66666666666667, "payments_success_rate_distribution_without_smart_retries": 57.142857142857146, "payments_success_rate_distribution_with_only_retries": 100.0, "payments_failure_rate_distribution": 33.333333333333336, "payments_failure_rate_distribution_without_smart_retries": 42.857142857142854, "payments_failure_rate_distribution_with_only_retries": 0.0, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": null, "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-07T01:30:00.000Z", "end_time": "2024-11-09T23:30:00.000Z" }, "time_bucket": "2024-11-07 01:30:00" } ], "metaData": [ { "total_payment_processed_amount": 0, "total_payment_processed_amount_usd": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 0, "total_failure_reasons_count_without_smart_retries": 0 } ] } ``` Fields that are required to be checked: `queryData`: ```json "payments_success_rate_distribution_with_only_retries": 100.0, "payments_failure_rate_distribution_with_only_retries": 0.0, ```
8cc5d3db9afb120b00115c6714be2e362951cc94
### Request - Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStat' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTY1MTcyMCwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.gtctUL339INfdj6CVmZLW2NDMNcseMTCPX0uxSsOD1c' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-07T01:30:00Z", "endTime": "2024-11-09T23:30:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "payments_distribution" ], "delta": true } ]' ``` ### Response ```json { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_amount_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": 66.66666666666667, "payments_success_rate_distribution_without_smart_retries": 57.142857142857146, "payments_success_rate_distribution_with_only_retries": 100.0, "payments_failure_rate_distribution": 33.333333333333336, "payments_failure_rate_distribution_without_smart_retries": 42.857142857142854, "payments_failure_rate_distribution_with_only_retries": 0.0, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": null, "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-07T01:30:00.000Z", "end_time": "2024-11-09T23:30:00.000Z" }, "time_bucket": "2024-11-07 01:30:00" } ], "metaData": [ { "total_payment_processed_amount": 0, "total_payment_processed_amount_usd": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 0, "total_failure_reasons_count_without_smart_retries": 0 } ] } ``` Fields that are required to be checked: `queryData`: ```json "payments_success_rate_distribution_with_only_retries": 100.0, "payments_failure_rate_distribution_with_only_retries": 0.0, ```
[ "crates/analytics/src/payments/accumulator.rs", "crates/api_models/src/analytics/payments.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6572
Bug: feat(analytics): add `sessionized_metrics` for disputes (backwards compatibility) ## Current Behaviour - There is no `sessionized_metrics` module for disputes like there is for `payments` and `payment_intents` ## Proposed Changes - create `sessionized_metrics` module for disputes
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index 546b57f99af..f56e875f720 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -139,6 +139,9 @@ impl AnalyticsDataSource for ClickhouseClient { | AnalyticsCollection::Dispute => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } } + AnalyticsCollection::DisputeSessionized => { + TableEngine::CollapsingMergeTree { sign: "sign_flag" } + } AnalyticsCollection::SdkEvents | AnalyticsCollection::SdkEventsAnalytics | AnalyticsCollection::ApiEvents @@ -439,6 +442,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection { Self::ConnectorEvents => Ok("connector_events_audit".to_string()), Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), Self::Dispute => Ok("dispute".to_string()), + Self::DisputeSessionized => Ok("sessionizer_dispute".to_string()), Self::ActivePaymentsAnalytics => Ok("active_payments".to_string()), } } diff --git a/crates/analytics/src/disputes/accumulators.rs b/crates/analytics/src/disputes/accumulators.rs index 1997d75d323..41bd3beebdb 100644 --- a/crates/analytics/src/disputes/accumulators.rs +++ b/crates/analytics/src/disputes/accumulators.rs @@ -5,8 +5,8 @@ use super::metrics::DisputeMetricRow; #[derive(Debug, Default)] pub struct DisputeMetricsAccumulator { pub disputes_status_rate: RateAccumulator, - pub total_amount_disputed: SumAccumulator, - pub total_dispute_lost_amount: SumAccumulator, + pub disputed_amount: DisputedAmountAccumulator, + pub dispute_lost_amount: DisputedAmountAccumulator, } #[derive(Debug, Default)] pub struct RateAccumulator { @@ -17,7 +17,7 @@ pub struct RateAccumulator { } #[derive(Debug, Default)] #[repr(transparent)] -pub struct SumAccumulator { +pub struct DisputedAmountAccumulator { pub total: Option<i64>, } @@ -29,7 +29,7 @@ pub trait DisputeMetricAccumulator { fn collect(self) -> Self::MetricOutput; } -impl DisputeMetricAccumulator for SumAccumulator { +impl DisputeMetricAccumulator for DisputedAmountAccumulator { type MetricOutput = Option<u64>; #[inline] fn add_metrics_bucket(&mut self, metrics: &DisputeMetricRow) { @@ -92,8 +92,8 @@ impl DisputeMetricsAccumulator { disputes_challenged: challenge_rate, disputes_won: won_rate, disputes_lost: lost_rate, - total_amount_disputed: self.total_amount_disputed.collect(), - total_dispute_lost_amount: self.total_dispute_lost_amount.collect(), + disputed_amount: self.disputed_amount.collect(), + dispute_lost_amount: self.dispute_lost_amount.collect(), total_dispute, } } diff --git a/crates/analytics/src/disputes/core.rs b/crates/analytics/src/disputes/core.rs index b8b44a757de..85d1a62a1d9 100644 --- a/crates/analytics/src/disputes/core.rs +++ b/crates/analytics/src/disputes/core.rs @@ -5,8 +5,8 @@ use api_models::analytics::{ DisputeDimensions, DisputeMetrics, DisputeMetricsBucketIdentifier, DisputeMetricsBucketResponse, }, - AnalyticsMetadata, DisputeFilterValue, DisputeFiltersResponse, GetDisputeFilterRequest, - GetDisputeMetricRequest, MetricsResponse, + DisputeFilterValue, DisputeFiltersResponse, DisputesAnalyticsMetadata, DisputesMetricsResponse, + GetDisputeFilterRequest, GetDisputeMetricRequest, }; use error_stack::ResultExt; use router_env::{ @@ -30,7 +30,7 @@ pub async fn get_metrics( pool: &AnalyticsProvider, auth: &AuthInfo, req: GetDisputeMetricRequest, -) -> AnalyticsResult<MetricsResponse<DisputeMetricsBucketResponse>> { +) -> AnalyticsResult<DisputesMetricsResponse<DisputeMetricsBucketResponse>> { let mut metrics_accumulator: HashMap< DisputeMetricsBucketIdentifier, DisputeMetricsAccumulator, @@ -87,14 +87,17 @@ pub async fn get_metrics( logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}"); let metrics_builder = metrics_accumulator.entry(id).or_default(); match metric { - DisputeMetrics::DisputeStatusMetric => metrics_builder + DisputeMetrics::DisputeStatusMetric + | DisputeMetrics::SessionizedDisputeStatusMetric => metrics_builder .disputes_status_rate .add_metrics_bucket(&value), - DisputeMetrics::TotalAmountDisputed => metrics_builder - .total_amount_disputed - .add_metrics_bucket(&value), - DisputeMetrics::TotalDisputeLostAmount => metrics_builder - .total_dispute_lost_amount + DisputeMetrics::TotalAmountDisputed + | DisputeMetrics::SessionizedTotalAmountDisputed => { + metrics_builder.disputed_amount.add_metrics_bucket(&value) + } + DisputeMetrics::TotalDisputeLostAmount + | DisputeMetrics::SessionizedTotalDisputeLostAmount => metrics_builder + .dispute_lost_amount .add_metrics_bucket(&value), } } @@ -105,18 +108,31 @@ pub async fn get_metrics( metrics_accumulator ); } + let mut total_disputed_amount = 0; + let mut total_dispute_lost_amount = 0; let query_data: Vec<DisputeMetricsBucketResponse> = metrics_accumulator .into_iter() - .map(|(id, val)| DisputeMetricsBucketResponse { - values: val.collect(), - dimensions: id, + .map(|(id, val)| { + let collected_values = val.collect(); + if let Some(amount) = collected_values.disputed_amount { + total_disputed_amount += amount; + } + if let Some(amount) = collected_values.dispute_lost_amount { + total_dispute_lost_amount += amount; + } + + DisputeMetricsBucketResponse { + values: collected_values, + dimensions: id, + } }) .collect(); - Ok(MetricsResponse { + Ok(DisputesMetricsResponse { query_data, - meta_data: [AnalyticsMetadata { - current_time_range: req.time_range, + meta_data: [DisputesAnalyticsMetadata { + total_disputed_amount: Some(total_disputed_amount), + total_dispute_lost_amount: Some(total_dispute_lost_amount), }], }) } diff --git a/crates/analytics/src/disputes/metrics.rs b/crates/analytics/src/disputes/metrics.rs index dd1aa3c1bbd..ad7ed81aaee 100644 --- a/crates/analytics/src/disputes/metrics.rs +++ b/crates/analytics/src/disputes/metrics.rs @@ -1,4 +1,5 @@ mod dispute_status_metric; +mod sessionized_metrics; mod total_amount_disputed; mod total_dispute_lost_amount; @@ -92,6 +93,21 @@ where .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } + Self::SessionizedTotalAmountDisputed => { + sessionized_metrics::TotalAmountDisputed::default() + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedDisputeStatusMetric => { + sessionized_metrics::DisputeStatusMetric::default() + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedTotalDisputeLostAmount => { + sessionized_metrics::TotalDisputeLostAmount::default() + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } } } } diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs new file mode 100644 index 00000000000..c5c0b91a173 --- /dev/null +++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs @@ -0,0 +1,120 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::DisputeMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; +#[derive(Default)] +pub(crate) struct DisputeStatusMetric {} + +#[async_trait::async_trait] +impl<T> super::DisputeMetric<T> for DisputeStatusMetric +where + T: AnalyticsDataSource + super::DisputeMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[DisputeDimensions], + auth: &AuthInfo, + filters: &DisputeFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> + where + T: AnalyticsDataSource + super::DisputeMetricAnalytics, + { + let mut query_builder = QueryBuilder::new(AnalyticsCollection::DisputeSessionized); + + for dim in dimensions { + query_builder.add_select_column(dim).switch()?; + } + + query_builder.add_select_column("dispute_status").switch()?; + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range.set_filter_clause(&mut query_builder).switch()?; + + for dim in dimensions { + query_builder.add_group_by_clause(dim).switch()?; + } + + query_builder + .add_group_by_clause("dispute_status") + .switch()?; + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .switch()?; + } + + query_builder + .execute_query::<DisputeMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + DisputeMetricsBucketIdentifier::new( + i.dispute_stage.as_ref().map(|i| i.0), + i.connector.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics/mod.rs new file mode 100644 index 00000000000..4d41194634d --- /dev/null +++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/mod.rs @@ -0,0 +1,8 @@ +mod dispute_status_metric; +mod total_amount_disputed; +mod total_dispute_lost_amount; +pub(super) use dispute_status_metric::DisputeStatusMetric; +pub(super) use total_amount_disputed::TotalAmountDisputed; +pub(super) use total_dispute_lost_amount::TotalDisputeLostAmount; + +pub use super::{DisputeMetric, DisputeMetricAnalytics, DisputeMetricRow}; diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs new file mode 100644 index 00000000000..0767bdaf85d --- /dev/null +++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs @@ -0,0 +1,118 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::DisputeMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; +#[derive(Default)] +pub(crate) struct TotalAmountDisputed {} + +#[async_trait::async_trait] +impl<T> super::DisputeMetric<T> for TotalAmountDisputed +where + T: AnalyticsDataSource + super::DisputeMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[DisputeDimensions], + auth: &AuthInfo, + filters: &DisputeFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> + where + T: AnalyticsDataSource + super::DisputeMetricAnalytics, + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::DisputeSessionized); + + for dim in dimensions { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Sum { + field: "dispute_amount", + alias: Some("total"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder.add_group_by_clause(dim).switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .switch()?; + } + query_builder + .add_filter_clause("dispute_status", "dispute_won") + .switch()?; + + query_builder + .execute_query::<DisputeMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + DisputeMetricsBucketIdentifier::new( + i.dispute_stage.as_ref().map(|i| i.0), + i.connector.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs new file mode 100644 index 00000000000..f4f4d860862 --- /dev/null +++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs @@ -0,0 +1,119 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::DisputeMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; +#[derive(Default)] +pub(crate) struct TotalDisputeLostAmount {} + +#[async_trait::async_trait] +impl<T> super::DisputeMetric<T> for TotalDisputeLostAmount +where + T: AnalyticsDataSource + super::DisputeMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[DisputeDimensions], + auth: &AuthInfo, + filters: &DisputeFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> + where + T: AnalyticsDataSource + super::DisputeMetricAnalytics, + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::DisputeSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Sum { + field: "dispute_amount", + alias: Some("total"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder.add_group_by_clause(dim).switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .switch()?; + } + + query_builder + .add_filter_clause("dispute_status", "dispute_lost") + .switch()?; + + query_builder + .execute_query::<DisputeMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + DisputeMetricsBucketIdentifier::new( + i.dispute_stage.as_ref().map(|i| i.0), + i.connector.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 0a641fbc5f9..80fcaf8ad4e 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -927,6 +927,8 @@ impl ToSql<SqlxClient> for AnalyticsCollection { Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?, Self::Dispute => Ok("dispute".to_string()), + Self::DisputeSessionized => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("DisputeSessionized table is not implemented for Sqlx"))?, } } } diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 6bdd11fcd73..86056338106 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -38,6 +38,7 @@ pub enum AnalyticsCollection { ConnectorEvents, OutgoingWebhookEvent, Dispute, + DisputeSessionized, ApiEventsAnalytics, ActivePaymentsAnalytics, } diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 70c0e0e78dc..ee904652154 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -346,6 +346,11 @@ pub struct SdkEventFilterValue { pub values: Vec<String>, } +#[derive(Debug, serde::Serialize)] +pub struct DisputesAnalyticsMetadata { + pub total_disputed_amount: Option<u64>, + pub total_dispute_lost_amount: Option<u64>, +} #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct MetricsResponse<T> { @@ -373,6 +378,12 @@ pub struct RefundsMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [RefundsAnalyticsMetadata; 1], } +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DisputesMetricsResponse<T> { + pub query_data: Vec<T>, + pub meta_data: [DisputesAnalyticsMetadata; 1], +} #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetApiEventFiltersRequest { diff --git a/crates/api_models/src/analytics/disputes.rs b/crates/api_models/src/analytics/disputes.rs index edb85c129e6..2509d83e132 100644 --- a/crates/api_models/src/analytics/disputes.rs +++ b/crates/api_models/src/analytics/disputes.rs @@ -24,6 +24,9 @@ pub enum DisputeMetrics { DisputeStatusMetric, TotalAmountDisputed, TotalDisputeLostAmount, + SessionizedDisputeStatusMetric, + SessionizedTotalAmountDisputed, + SessionizedTotalDisputeLostAmount, } #[derive( @@ -122,8 +125,8 @@ pub struct DisputeMetricsBucketValue { pub disputes_challenged: Option<u64>, pub disputes_won: Option<u64>, pub disputes_lost: Option<u64>, - pub total_amount_disputed: Option<u64>, - pub total_dispute_lost_amount: Option<u64>, + pub disputed_amount: Option<u64>, + pub dispute_lost_amount: Option<u64>, pub total_dispute: Option<u64>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 77d8cb117ef..541c59e1adc 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -173,6 +173,12 @@ impl<T> ApiEventMetric for RefundsMetricsResponse<T> { Some(ApiEventsType::Miscellaneous) } } + +impl<T> ApiEventMetric for DisputesMetricsResponse<T> { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Miscellaneous) + } +} #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl ApiEventMetric for PaymentMethodIntentConfirmInternal { fn get_api_event_type(&self) -> Option<ApiEventsType> {
2024-11-14T12:49:06Z
## Description <!-- Describe your changes in detail --> - Add sessionized metrics module and implement backwards compatibility. - Add the `sessionizer_dispute` table support for Sessionized metrics. ### Fixes #6572 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - Dispute metrics didn't have a `sessionized_metrics` module and implementation as were there in payments and payment_intents metrics ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/disputes' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStat' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTY1MTcyMCwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.gtctUL339INfdj6CVmZLW2NDMNcseMTCPX0uxSsOD1c' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-06T18:30:00Z", "endTime": "2024-11-14T10:51:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "dispute_status_metric", "total_amount_disputed", "total_dispute_lost_amount" ], "delta": true } ]' ``` ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/disputes' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStat' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTY1MTcyMCwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.gtctUL339INfdj6CVmZLW2NDMNcseMTCPX0uxSsOD1c' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-06T18:30:00Z", "endTime": "2024-11-14T10:51:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_dispute_status_metric", "sessionized_total_amount_disputed", "sessionized_total_dispute_lost_amount" ], "delta": true } ]' ``` <img width="1289" alt="Screenshot 2024-11-14 at 6 14 32 PM" src="https://github.com/user-attachments/assets/ce8b0aeb-6f4f-4242-a329-4183a97ea8b3"> <img width="1289" alt="Screenshot 2024-11-14 at 6 14 32 PM" src="https://github.com/user-attachments/assets/ce8b0aeb-6f4f-4242-a329-4183a97ea8b3"> ### Result: Earlier it used to throw `5xx` for sessionized metrics but here it's giving us `200` for both metrics.
8cc5d3db9afb120b00115c6714be2e362951cc94
```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/disputes' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStat' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTY1MTcyMCwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.gtctUL339INfdj6CVmZLW2NDMNcseMTCPX0uxSsOD1c' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-06T18:30:00Z", "endTime": "2024-11-14T10:51:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "dispute_status_metric", "total_amount_disputed", "total_dispute_lost_amount" ], "delta": true } ]' ``` ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/disputes' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStat' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTY1MTcyMCwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.gtctUL339INfdj6CVmZLW2NDMNcseMTCPX0uxSsOD1c' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-06T18:30:00Z", "endTime": "2024-11-14T10:51:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_dispute_status_metric", "sessionized_total_amount_disputed", "sessionized_total_dispute_lost_amount" ], "delta": true } ]' ``` <img width="1289" alt="Screenshot 2024-11-14 at 6 14 32 PM" src="https://github.com/user-attachments/assets/ce8b0aeb-6f4f-4242-a329-4183a97ea8b3"> <img width="1289" alt="Screenshot 2024-11-14 at 6 14 32 PM" src="https://github.com/user-attachments/assets/ce8b0aeb-6f4f-4242-a329-4183a97ea8b3"> ### Result: Earlier it used to throw `5xx` for sessionized metrics but here it's giving us `200` for both metrics.
[ "crates/analytics/src/clickhouse.rs", "crates/analytics/src/disputes/accumulators.rs", "crates/analytics/src/disputes/core.rs", "crates/analytics/src/disputes/metrics.rs", "crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs", "crates/analytics/src/disputes/metrics/sessionized_metrics/mod.rs", "crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs", "crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs", "crates/analytics/src/sqlx.rs", "crates/analytics/src/types.rs", "crates/api_models/src/analytics.rs", "crates/api_models/src/analytics/disputes.rs", "crates/api_models/src/events.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6561
Bug: Create toggle and update endpoints for ER
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 1494908c5fc..68631872aa7 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -1278,7 +1278,7 @@ ], "summary": "Routing - Create", "description": "Create a routing algorithm", - "operationId": "Create a routing algprithm", + "operationId": "Create a routing algorithm", "requestBody": { "content": { "application/json": { diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs index ffa5e008f0a..87e7fa27885 100644 --- a/crates/api_models/src/events/routing.rs +++ b/crates/api_models/src/events/routing.rs @@ -6,7 +6,7 @@ use crate::routing::{ RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper, SuccessBasedRoutingUpdateConfigQuery, - ToggleSuccessBasedRoutingQuery, ToggleSuccessBasedRoutingWrapper, + ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper, }; impl ApiEventMetric for RoutingKind { @@ -79,7 +79,7 @@ impl ApiEventMetric for RoutingRetrieveLinkQueryWrapper { } } -impl ApiEventMetric for ToggleSuccessBasedRoutingQuery { +impl ApiEventMetric for ToggleDynamicRoutingQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } @@ -97,7 +97,7 @@ impl ApiEventMetric for SuccessBasedRoutingPayloadWrapper { } } -impl ApiEventMetric for ToggleSuccessBasedRoutingWrapper { +impl ApiEventMetric for ToggleDynamicRoutingWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 389af3dab7b..3b09dc8eb3b 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -523,6 +523,92 @@ pub struct DynamicAlgorithmWithTimestamp<T> { #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicRoutingAlgorithmRef { pub success_based_algorithm: Option<SuccessBasedAlgorithm>, + pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>, +} + +pub trait DynamicRoutingAlgoAccessor { + fn get_algorithm_id_with_timestamp( + self, + ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>; + fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures; +} + +impl DynamicRoutingAlgoAccessor for SuccessBasedAlgorithm { + fn get_algorithm_id_with_timestamp( + self, + ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { + self.algorithm_id_with_timestamp + } + fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { + &mut self.enabled_feature + } +} + +impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm { + fn get_algorithm_id_with_timestamp( + self, + ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { + self.algorithm_id_with_timestamp + } + fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { + &mut self.enabled_feature + } +} + +impl EliminationRoutingAlgorithm { + pub fn new( + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< + common_utils::id_type::RoutingId, + >, + ) -> Self { + Self { + algorithm_id_with_timestamp, + enabled_feature: DynamicRoutingFeatures::None, + } + } +} + +impl SuccessBasedAlgorithm { + pub fn new( + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< + common_utils::id_type::RoutingId, + >, + ) -> Self { + Self { + algorithm_id_with_timestamp, + enabled_feature: DynamicRoutingFeatures::None, + } + } +} + +impl DynamicRoutingAlgorithmRef { + pub fn update(&mut self, new: Self) { + if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm { + self.elimination_routing_algorithm = Some(elimination_routing_algorithm) + } + if let Some(success_based_algorithm) = new.success_based_algorithm { + self.success_based_algorithm = Some(success_based_algorithm) + } + } + + pub fn update_specific_ref( + &mut self, + algo_type: DynamicRoutingType, + feature_to_enable: DynamicRoutingFeatures, + ) { + match algo_type { + DynamicRoutingType::SuccessRateBasedRouting => { + self.success_based_algorithm + .as_mut() + .map(|algo| algo.enabled_feature = feature_to_enable); + } + DynamicRoutingType::EliminationRouting => { + self.elimination_routing_algorithm + .as_mut() + .map(|algo| algo.enabled_feature = feature_to_enable); + } + } + } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -530,11 +616,25 @@ pub struct SuccessBasedAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] - pub enabled_feature: SuccessBasedRoutingFeatures, + pub enabled_feature: DynamicRoutingFeatures, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct EliminationRoutingAlgorithm { + pub algorithm_id_with_timestamp: + DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, + #[serde(default)] + pub enabled_feature: DynamicRoutingFeatures, +} + +impl EliminationRoutingAlgorithm { + pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { + self.enabled_feature = feature_to_enable + } } impl SuccessBasedAlgorithm { - pub fn update_enabled_features(&mut self, feature_to_enable: SuccessBasedRoutingFeatures) { + pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } } @@ -543,26 +643,40 @@ impl DynamicRoutingAlgorithmRef { pub fn update_algorithm_id( &mut self, new_id: common_utils::id_type::RoutingId, - enabled_feature: SuccessBasedRoutingFeatures, + enabled_feature: DynamicRoutingFeatures, + dynamic_routing_type: DynamicRoutingType, ) { - self.success_based_algorithm = Some(SuccessBasedAlgorithm { - algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp { - algorithm_id: Some(new_id), - timestamp: common_utils::date_time::now_unix_timestamp(), - }, - enabled_feature, - }) + match dynamic_routing_type { + DynamicRoutingType::SuccessRateBasedRouting => { + self.success_based_algorithm = Some(SuccessBasedAlgorithm { + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp { + algorithm_id: Some(new_id), + timestamp: common_utils::date_time::now_unix_timestamp(), + }, + enabled_feature, + }) + } + DynamicRoutingType::EliminationRouting => { + self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp { + algorithm_id: Some(new_id), + timestamp: common_utils::date_time::now_unix_timestamp(), + }, + enabled_feature, + }) + } + }; } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] -pub struct ToggleSuccessBasedRoutingQuery { - pub enable: SuccessBasedRoutingFeatures, +pub struct ToggleDynamicRoutingQuery { + pub enable: DynamicRoutingFeatures, } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] #[serde(rename_all = "snake_case")] -pub enum SuccessBasedRoutingFeatures { +pub enum DynamicRoutingFeatures { Metrics, DynamicConnectorSelection, #[default] @@ -578,26 +692,52 @@ pub struct SuccessBasedRoutingUpdateConfigQuery { } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] -pub struct ToggleSuccessBasedRoutingWrapper { +pub struct ToggleDynamicRoutingWrapper { pub profile_id: common_utils::id_type::ProfileId, - pub feature_to_enable: SuccessBasedRoutingFeatures, + pub feature_to_enable: DynamicRoutingFeatures, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] -pub struct ToggleSuccessBasedRoutingPath { +pub struct ToggleDynamicRoutingPath { #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } + +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] +pub struct EliminationRoutingConfig { + pub params: Option<Vec<DynamicRoutingConfigParams>>, + // pub labels: Option<Vec<String>>, + pub elimination_analyser_config: Option<EliminationAnalyserConfig>, +} + +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] +pub struct EliminationAnalyserConfig { + pub bucket_size: Option<u32>, + pub bucket_ttl_in_mins: Option<f64>, +} + +impl Default for EliminationRoutingConfig { + fn default() -> Self { + Self { + params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), + elimination_analyser_config: Some(EliminationAnalyserConfig { + bucket_size: Some(5), + bucket_ttl_in_mins: Some(2.0), + }), + } + } +} + #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct SuccessBasedRoutingConfig { - pub params: Option<Vec<SuccessBasedRoutingConfigParams>>, + pub params: Option<Vec<DynamicRoutingConfigParams>>, pub config: Option<SuccessBasedRoutingConfigBody>, } impl Default for SuccessBasedRoutingConfig { fn default() -> Self { Self { - params: Some(vec![SuccessBasedRoutingConfigParams::PaymentMethod]), + params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), config: Some(SuccessBasedRoutingConfigBody { min_aggregates_size: Some(2), default_success_rate: Some(100.0), @@ -612,7 +752,7 @@ impl Default for SuccessBasedRoutingConfig { } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, strum::Display)] -pub enum SuccessBasedRoutingConfigParams { +pub enum DynamicRoutingConfigParams { PaymentMethod, PaymentMethodType, AuthenticationType, @@ -643,6 +783,12 @@ pub struct SuccessBasedRoutingPayloadWrapper { pub profile_id: common_utils::id_type::ProfileId, } +#[derive(Debug, Clone, strum::Display, serde::Serialize, serde::Deserialize)] +pub enum DynamicRoutingType { + SuccessRateBasedRouting, + EliminationRouting, +} + impl SuccessBasedRoutingConfig { pub fn update(&mut self, new: Self) { if let Some(params) = new.params { diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index ed6efea27f8..4ec1bb22b4b 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -575,7 +575,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::routing::RoutingDictionaryRecord, api_models::routing::RoutingKind, api_models::routing::RoutableConnectorChoice, - api_models::routing::SuccessBasedRoutingFeatures, + api_models::routing::DynamicRoutingFeatures, api_models::routing::LinkedRoutingConfigRetrieveResponse, api_models::routing::RoutingRetrieveResponse, api_models::routing::ProfileDefaultRoutingConfig, @@ -586,8 +586,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::routing::StraightThroughAlgorithm, api_models::routing::ConnectorVolumeSplit, api_models::routing::ConnectorSelection, - api_models::routing::ToggleSuccessBasedRoutingQuery, - api_models::routing::ToggleSuccessBasedRoutingPath, + api_models::routing::ToggleDynamicRoutingQuery, + api_models::routing::ToggleDynamicRoutingPath, api_models::routing::ast::RoutableChoiceKind, api_models::enums::RoutableConnectors, api_models::routing::ast::ProgramConnectorSelection, diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs index 67a22c2ca64..08d2e46a616 100644 --- a/crates/openapi/src/routes/routing.rs +++ b/crates/openapi/src/routes/routing.rs @@ -37,7 +37,7 @@ pub async fn routing_create_config() {} (status = 403, description = "Forbidden"), ), tag = "Routing", - operation_id = "Create a routing algprithm", + operation_id = "Create a routing algorithm", security(("api_key" = []), ("jwt_key" = [])) )] pub async fn routing_create_config() {} @@ -266,7 +266,7 @@ pub async fn routing_update_default_config_for_profile() {} params( ("account_id" = String, Path, description = "Merchant id"), ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"), - ("enable" = SuccessBasedRoutingFeatures, Query, description = "Feature to enable for success based routing"), + ("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for success based routing"), ), responses( (status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord), @@ -277,7 +277,33 @@ pub async fn routing_update_default_config_for_profile() {} (status = 403, description = "Forbidden"), ), tag = "Routing", - operation_id = "Toggle success based dynamic routing algprithm", + operation_id = "Toggle success based dynamic routing algorithm", security(("api_key" = []), ("jwt_key" = [])) )] pub async fn toggle_success_based_routing() {} + +#[cfg(feature = "v1")] +/// Routing - Toggle elimination routing for profile +/// +/// Create a elimination based dynamic routing algorithm +#[utoipa::path( + post, + path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/elimination/toggle", + params( + ("account_id" = String, Path, description = "Merchant id"), + ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"), + ("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for success based routing"), + ), + responses( + (status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord), + (status = 400, description = "Request body is malformed"), + (status = 500, description = "Internal server error"), + (status = 404, description = "Resource missing"), + (status = 422, description = "Unprocessable request"), + (status = 403, description = "Forbidden"), + ), + tag = "Routing", + operation_id = "Toggle elimination routing algorithm", + security(("api_key" = []), ("jwt_key" = [])) +)] +pub async fn toggle_elimination_routing() {} diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 28321529ef2..2fb49c37d22 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1263,7 +1263,7 @@ pub async fn perform_success_based_routing( )?; if success_based_algo_ref.enabled_feature - == api_routing::SuccessBasedRoutingFeatures::DynamicConnectorSelection + == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection { logger::debug!( "performing success_based_routing for profile {}", diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 348f5229b75..9318e0c5b9f 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -452,6 +452,16 @@ pub async fn link_routing_config( }, enabled_feature: _ }) if id == &algorithm_id + ) || matches!( + dynamic_routing_ref.elimination_routing_algorithm, + Some(routing::EliminationRoutingAlgorithm { + algorithm_id_with_timestamp: + routing_types::DynamicAlgorithmWithTimestamp { + algorithm_id: Some(ref id), + timestamp: _ + }, + enabled_feature: _ + }) if id == &algorithm_id ), || { Err(errors::ApiErrorResponse::PreconditionFailed { @@ -470,7 +480,9 @@ pub async fn link_routing_config( "missing success_based_algorithm in dynamic_algorithm_ref from business_profile table", )? .enabled_feature, + routing_types::DynamicRoutingType::SuccessRateBasedRouting, ); + helpers::update_business_profile_active_dynamic_algorithm_ref( db, key_manager_state, @@ -1185,13 +1197,16 @@ pub async fn update_default_routing_config_for_profile( )) } +// Toggle the specific routing type as well as add the default configs in RoutingAlgorithm table +// and update the same in business profile table. #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -pub async fn toggle_success_based_routing( +pub async fn toggle_specific_dynamic_routing( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, - feature_to_enable: routing::SuccessBasedRoutingFeatures, + feature_to_enable: routing::DynamicRoutingFeatures, profile_id: common_utils::id_type::ProfileId, + dynamic_routing_type: routing::DynamicRoutingType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add( &metrics::CONTEXT, @@ -1214,170 +1229,44 @@ pub async fn toggle_success_based_routing( id: profile_id.get_string_repr().to_owned(), })?; - let mut success_based_dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = - business_profile - .dynamic_routing_algorithm - .clone() - .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "unable to deserialize dynamic routing algorithm ref from business profile", - )? - .unwrap_or_default(); + let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile + .dynamic_routing_algorithm + .clone() + .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to deserialize dynamic routing algorithm ref from business profile", + )? + .unwrap_or_default(); match feature_to_enable { - routing::SuccessBasedRoutingFeatures::Metrics - | routing::SuccessBasedRoutingFeatures::DynamicConnectorSelection => { - if let Some(ref mut algo_with_timestamp) = - success_based_dynamic_routing_algo_ref.success_based_algorithm - { - match algo_with_timestamp - .algorithm_id_with_timestamp - .algorithm_id - .clone() - { - Some(algorithm_id) => { - // algorithm is already present in profile - if algo_with_timestamp.enabled_feature == feature_to_enable { - // algorithm already has the required feature - Err(errors::ApiErrorResponse::PreconditionFailed { - message: "Success rate based routing is already enabled" - .to_string(), - })? - } else { - // enable the requested feature for the algorithm - algo_with_timestamp.update_enabled_features(feature_to_enable); - let record = db - .find_routing_algorithm_by_profile_id_algorithm_id( - business_profile.get_id(), - &algorithm_id, - ) - .await - .to_not_found_response( - errors::ApiErrorResponse::ResourceIdNotFound, - )?; - let response = record.foreign_into(); - helpers::update_business_profile_active_dynamic_algorithm_ref( - db, - key_manager_state, - &key_store, - business_profile, - success_based_dynamic_routing_algo_ref, - ) - .await?; - - metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add( - &metrics::CONTEXT, - 1, - &add_attributes([( - "profile_id", - profile_id.get_string_repr().to_owned(), - )]), - ); - Ok(service_api::ApplicationResponse::Json(response)) - } - } - None => { - // algorithm isn't present in profile - helpers::default_success_based_routing_setup( - &state, - key_store, - business_profile, - feature_to_enable, - merchant_account.get_id().to_owned(), - success_based_dynamic_routing_algo_ref, - ) - .await - } - } - } else { - // algorithm isn't present in profile - helpers::default_success_based_routing_setup( - &state, - key_store, - business_profile, - feature_to_enable, - merchant_account.get_id().to_owned(), - success_based_dynamic_routing_algo_ref, - ) - .await - } + routing::DynamicRoutingFeatures::Metrics + | routing::DynamicRoutingFeatures::DynamicConnectorSelection => { + // occurs when algorithm is already present in the db + // 1. If present with same feature then return response as already enabled + // 2. Else update the feature and persist the same on db + // 3. If not present in db then create a new default entry + helpers::enable_dynamic_routing_algorithm( + &state, + key_store, + business_profile, + feature_to_enable, + dynamic_routing_algo_ref, + dynamic_routing_type, + ) + .await } - routing::SuccessBasedRoutingFeatures::None => { - // disable success based routing for the requested profile - let timestamp = common_utils::date_time::now_unix_timestamp(); - match success_based_dynamic_routing_algo_ref.success_based_algorithm { - Some(algorithm_ref) => { - if let Some(algorithm_id) = - algorithm_ref.algorithm_id_with_timestamp.algorithm_id - { - let dynamic_routing_algorithm = routing_types::DynamicRoutingAlgorithmRef { - success_based_algorithm: Some(routing::SuccessBasedAlgorithm { - algorithm_id_with_timestamp: - routing_types::DynamicAlgorithmWithTimestamp { - algorithm_id: None, - timestamp, - }, - enabled_feature: routing::SuccessBasedRoutingFeatures::None, - }), - }; - - // redact cache for success based routing configs - let cache_key = format!( - "{}_{}", - business_profile.get_id().get_string_repr(), - algorithm_id.get_string_repr() - ); - let cache_entries_to_redact = - vec![cache::CacheKind::SuccessBasedDynamicRoutingCache( - cache_key.into(), - )]; - let _ = cache::publish_into_redact_channel( - state.store.get_cache_store().as_ref(), - cache_entries_to_redact, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to publish into the redact channel for evicting the success based routing config cache")?; - - let record = db - .find_routing_algorithm_by_profile_id_algorithm_id( - business_profile.get_id(), - &algorithm_id, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; - let response = record.foreign_into(); - helpers::update_business_profile_active_dynamic_algorithm_ref( - db, - key_manager_state, - &key_store, - business_profile, - dynamic_routing_algorithm, - ) - .await?; - - metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add( - &metrics::CONTEXT, - 1, - &add_attributes([( - "profile_id", - profile_id.get_string_repr().to_owned(), - )]), - ); - - Ok(service_api::ApplicationResponse::Json(response)) - } else { - Err(errors::ApiErrorResponse::PreconditionFailed { - message: "Algorithm is already inactive".to_string(), - })? - } - } - None => Err(errors::ApiErrorResponse::PreconditionFailed { - message: "Success rate based routing is already disabled".to_string(), - })?, - } + routing::DynamicRoutingFeatures::None => { + // disable specific dynamic routing for the requested profile + helpers::disable_dynamic_routing_algorithm( + &state, + key_store, + business_profile, + dynamic_routing_algo_ref, + dynamic_routing_type, + ) + .await } } } diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 264328796c8..b445627446e 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -26,6 +26,8 @@ use router_env::{instrument, metrics::add_attributes, tracing}; use rustc_hash::FxHashSet; use storage_impl::redis::cache; +#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +use crate::db::errors::StorageErrorExt; #[cfg(feature = "v2")] use crate::types::domain::MerchantConnectorAccount; use crate::{ @@ -39,6 +41,8 @@ use crate::{ use crate::{core::metrics as core_metrics, routes::metrics, types::transformers::ForeignInto}; pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = "Success rate based dynamic routing algorithm"; +pub const ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = + "Elimination based dynamic routing algorithm"; /// Provides us with all the configured configs of the Merchant in the ascending time configured /// manner and chooses the first of them @@ -263,9 +267,9 @@ pub async fn update_business_profile_active_dynamic_algorithm_ref( key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_business_profile: domain::Profile, - dynamic_routing_algorithm: routing_types::DynamicRoutingAlgorithmRef, + dynamic_routing_algorithm_ref: routing_types::DynamicRoutingAlgorithmRef, ) -> RouterResult<()> { - let ref_val = dynamic_routing_algorithm + let ref_val = dynamic_routing_algorithm_ref .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert dynamic routing ref to value")?; @@ -662,7 +666,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("success_based_algorithm not found in dynamic_routing_algorithm from business_profile table")?; - if success_based_algo_ref.enabled_feature != routing_types::SuccessBasedRoutingFeatures::None { + if success_based_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None { let client = state .grpc_client .dynamic_routing @@ -912,34 +916,303 @@ pub fn generate_tenant_business_profile_id( format!("{}:{}", redis_key_prefix, business_profile_id) } -/// default config setup for success_based_routing +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub async fn disable_dynamic_routing_algorithm( + state: &SessionState, + key_store: domain::MerchantKeyStore, + business_profile: domain::Profile, + dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef, + dynamic_routing_type: routing_types::DynamicRoutingType, +) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> { + let db = state.store.as_ref(); + let key_manager_state = &state.into(); + let timestamp = common_utils::date_time::now_unix_timestamp(); + let profile_id = business_profile + .get_id() + .clone() + .get_string_repr() + .to_owned(); + let (algorithm_id, dynamic_routing_algorithm, cache_entries_to_redact) = + match dynamic_routing_type { + routing_types::DynamicRoutingType::SuccessRateBasedRouting => { + let Some(algorithm_ref) = dynamic_routing_algo_ref.success_based_algorithm else { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Success rate based routing is already disabled".to_string(), + })? + }; + let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id + else { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Algorithm is already inactive".to_string(), + })? + }; + + let cache_key = format!( + "{}_{}", + business_profile.get_id().get_string_repr(), + algorithm_id.get_string_repr() + ); + let cache_entries_to_redact = + vec![cache::CacheKind::SuccessBasedDynamicRoutingCache( + cache_key.into(), + )]; + ( + algorithm_id, + routing_types::DynamicRoutingAlgorithmRef { + success_based_algorithm: Some(routing_types::SuccessBasedAlgorithm { + algorithm_id_with_timestamp: + routing_types::DynamicAlgorithmWithTimestamp { + algorithm_id: None, + timestamp, + }, + enabled_feature: routing_types::DynamicRoutingFeatures::None, + }), + elimination_routing_algorithm: dynamic_routing_algo_ref + .elimination_routing_algorithm, + }, + cache_entries_to_redact, + ) + } + routing_types::DynamicRoutingType::EliminationRouting => { + let Some(algorithm_ref) = dynamic_routing_algo_ref.elimination_routing_algorithm + else { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Elimination routing is already disabled".to_string(), + })? + }; + let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id + else { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Algorithm is already inactive".to_string(), + })? + }; + let cache_key = format!( + "{}_{}", + business_profile.get_id().get_string_repr(), + algorithm_id.get_string_repr() + ); + let cache_entries_to_redact = + vec![cache::CacheKind::EliminationBasedDynamicRoutingCache( + cache_key.into(), + )]; + ( + algorithm_id, + routing_types::DynamicRoutingAlgorithmRef { + success_based_algorithm: dynamic_routing_algo_ref.success_based_algorithm, + elimination_routing_algorithm: Some( + routing_types::EliminationRoutingAlgorithm { + algorithm_id_with_timestamp: + routing_types::DynamicAlgorithmWithTimestamp { + algorithm_id: None, + timestamp, + }, + enabled_feature: routing_types::DynamicRoutingFeatures::None, + }, + ), + }, + cache_entries_to_redact, + ) + } + }; + + // redact cache for dynamic routing config + let _ = cache::publish_into_redact_channel( + state.store.get_cache_store().as_ref(), + cache_entries_to_redact, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to publish into the redact channel for evicting the dynamic routing config cache", + )?; + + let record = db + .find_routing_algorithm_by_profile_id_algorithm_id(business_profile.get_id(), &algorithm_id) + .await + .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; + let response = record.foreign_into(); + update_business_profile_active_dynamic_algorithm_ref( + db, + key_manager_state, + &key_store, + business_profile, + dynamic_routing_algorithm, + ) + .await?; + + core_metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add( + &metrics::CONTEXT, + 1, + &add_attributes([("profile_id", profile_id)]), + ); + + Ok(ApplicationResponse::Json(response)) +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub async fn enable_dynamic_routing_algorithm( + state: &SessionState, + key_store: domain::MerchantKeyStore, + business_profile: domain::Profile, + feature_to_enable: routing_types::DynamicRoutingFeatures, + dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef, + dynamic_routing_type: routing_types::DynamicRoutingType, +) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> { + let dynamic_routing = dynamic_routing_algo_ref.clone(); + match dynamic_routing_type { + routing_types::DynamicRoutingType::SuccessRateBasedRouting => { + enable_specific_routing_algorithm( + state, + key_store, + business_profile, + feature_to_enable, + dynamic_routing_algo_ref, + dynamic_routing_type, + dynamic_routing.success_based_algorithm, + ) + .await + } + routing_types::DynamicRoutingType::EliminationRouting => { + enable_specific_routing_algorithm( + state, + key_store, + business_profile, + feature_to_enable, + dynamic_routing_algo_ref, + dynamic_routing_type, + dynamic_routing.elimination_routing_algorithm, + ) + .await + } + } +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub async fn enable_specific_routing_algorithm<A>( + state: &SessionState, + key_store: domain::MerchantKeyStore, + business_profile: domain::Profile, + feature_to_enable: routing_types::DynamicRoutingFeatures, + mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef, + dynamic_routing_type: routing_types::DynamicRoutingType, + algo_type: Option<A>, +) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> +where + A: routing_types::DynamicRoutingAlgoAccessor + Clone + std::fmt::Debug, +{ + // Algorithm wasn't created yet + let Some(mut algo_type) = algo_type else { + return default_specific_dynamic_routing_setup( + state, + key_store, + business_profile, + feature_to_enable, + dynamic_routing_algo_ref, + dynamic_routing_type, + ) + .await; + }; + + // Algorithm was in disabled state + let Some(algo_type_algorithm_id) = algo_type + .clone() + .get_algorithm_id_with_timestamp() + .algorithm_id + else { + return default_specific_dynamic_routing_setup( + state, + key_store, + business_profile, + feature_to_enable, + dynamic_routing_algo_ref, + dynamic_routing_type, + ) + .await; + }; + let db = state.store.as_ref(); + let profile_id = business_profile.get_id().clone(); + let algo_type_enabled_features = algo_type.get_enabled_features(); + if *algo_type_enabled_features == feature_to_enable { + // algorithm already has the required feature + return Err(errors::ApiErrorResponse::PreconditionFailed { + message: format!("{} is already enabled", dynamic_routing_type), + } + .into()); + }; + *algo_type_enabled_features = feature_to_enable.clone(); + dynamic_routing_algo_ref + .update_specific_ref(dynamic_routing_type.clone(), feature_to_enable.clone()); + update_business_profile_active_dynamic_algorithm_ref( + db, + &state.into(), + &key_store, + business_profile, + dynamic_routing_algo_ref.clone(), + ) + .await?; + + let routing_algorithm = db + .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algo_type_algorithm_id) + .await + .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; + let updated_routing_record = routing_algorithm.foreign_into(); + core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add( + &metrics::CONTEXT, + 1, + &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]), + ); + Ok(ApplicationResponse::Json(updated_routing_record)) +} + #[cfg(feature = "v1")] #[instrument(skip_all)] -pub async fn default_success_based_routing_setup( +pub async fn default_specific_dynamic_routing_setup( state: &SessionState, key_store: domain::MerchantKeyStore, business_profile: domain::Profile, - feature_to_enable: routing_types::SuccessBasedRoutingFeatures, - merchant_id: id_type::MerchantId, - mut success_based_dynamic_routing_algo: routing_types::DynamicRoutingAlgorithmRef, + feature_to_enable: routing_types::DynamicRoutingFeatures, + mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef, + dynamic_routing_type: routing_types::DynamicRoutingType, ) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> { let db = state.store.as_ref(); let key_manager_state = &state.into(); - let profile_id = business_profile.get_id().to_owned(); - let default_success_based_routing_config = routing_types::SuccessBasedRoutingConfig::default(); + let profile_id = business_profile.get_id().clone(); + let merchant_id = business_profile.merchant_id.clone(); let algorithm_id = common_utils::generate_routing_id_of_default_length(); let timestamp = common_utils::date_time::now(); - let algo = routing_algorithm::RoutingAlgorithm { - algorithm_id: algorithm_id.clone(), - profile_id: profile_id.clone(), - merchant_id, - name: SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(), - description: None, - kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic, - algorithm_data: serde_json::json!(default_success_based_routing_config), - created_at: timestamp, - modified_at: timestamp, - algorithm_for: common_enums::TransactionType::Payment, + let algo = match dynamic_routing_type { + routing_types::DynamicRoutingType::SuccessRateBasedRouting => { + let default_success_based_routing_config = + routing_types::SuccessBasedRoutingConfig::default(); + routing_algorithm::RoutingAlgorithm { + algorithm_id: algorithm_id.clone(), + profile_id: profile_id.clone(), + merchant_id, + name: SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(), + description: None, + kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic, + algorithm_data: serde_json::json!(default_success_based_routing_config), + created_at: timestamp, + modified_at: timestamp, + algorithm_for: common_enums::TransactionType::Payment, + } + } + routing_types::DynamicRoutingType::EliminationRouting => { + let default_elimination_routing_config = + routing_types::EliminationRoutingConfig::default(); + routing_algorithm::RoutingAlgorithm { + algorithm_id: algorithm_id.clone(), + profile_id: profile_id.clone(), + merchant_id, + name: ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(), + description: None, + kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic, + algorithm_data: serde_json::json!(default_elimination_routing_config), + created_at: timestamp, + modified_at: timestamp, + algorithm_for: common_enums::TransactionType::Payment, + } + } }; let record = db @@ -948,13 +1221,17 @@ pub async fn default_success_based_routing_setup( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to insert record in routing algorithm table")?; - success_based_dynamic_routing_algo.update_algorithm_id(algorithm_id, feature_to_enable); + dynamic_routing_algo_ref.update_algorithm_id( + algorithm_id, + feature_to_enable, + dynamic_routing_type, + ); update_business_profile_active_dynamic_algorithm_ref( db, key_manager_state, &key_store, business_profile, - success_based_dynamic_routing_algo, + dynamic_routing_algo_ref, ) .await?; @@ -1001,35 +1278,35 @@ impl SuccessBasedRoutingConfigParamsInterpolator { pub fn get_string_val( &self, - params: &Vec<routing_types::SuccessBasedRoutingConfigParams>, + params: &Vec<routing_types::DynamicRoutingConfigParams>, ) -> String { let mut parts: Vec<String> = Vec::new(); for param in params { let val = match param { - routing_types::SuccessBasedRoutingConfigParams::PaymentMethod => self + routing_types::DynamicRoutingConfigParams::PaymentMethod => self .payment_method .as_ref() .map_or(String::new(), |pm| pm.to_string()), - routing_types::SuccessBasedRoutingConfigParams::PaymentMethodType => self + routing_types::DynamicRoutingConfigParams::PaymentMethodType => self .payment_method_type .as_ref() .map_or(String::new(), |pmt| pmt.to_string()), - routing_types::SuccessBasedRoutingConfigParams::AuthenticationType => self + routing_types::DynamicRoutingConfigParams::AuthenticationType => self .authentication_type .as_ref() .map_or(String::new(), |at| at.to_string()), - routing_types::SuccessBasedRoutingConfigParams::Currency => self + routing_types::DynamicRoutingConfigParams::Currency => self .currency .as_ref() .map_or(String::new(), |cur| cur.to_string()), - routing_types::SuccessBasedRoutingConfigParams::Country => self + routing_types::DynamicRoutingConfigParams::Country => self .country .as_ref() .map_or(String::new(), |cn| cn.to_string()), - routing_types::SuccessBasedRoutingConfigParams::CardNetwork => { + routing_types::DynamicRoutingConfigParams::CardNetwork => { self.card_network.clone().unwrap_or_default() } - routing_types::SuccessBasedRoutingConfigParams::CardBin => { + routing_types::DynamicRoutingConfigParams::CardBin => { self.card_bin.clone().unwrap_or_default() } }; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 1584cfae2b9..432a46b4bda 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1752,9 +1752,9 @@ impl Profile { #[cfg(feature = "dynamic_routing")] { - route = - route.service( - web::scope("/{profile_id}/dynamic_routing").service( + route = route.service( + web::scope("/{profile_id}/dynamic_routing") + .service( web::scope("/success_based") .service( web::resource("/toggle") @@ -1767,8 +1767,14 @@ impl Profile { ) }), )), + ) + .service( + web::scope("/elimination").service( + web::resource("/toggle") + .route(web::post().to(routing::toggle_elimination_routing)), + ), ), - ); + ); } route = route.service( diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index cb7744f5200..d22c5e97490 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -1014,11 +1014,11 @@ pub async fn routing_update_default_config_for_profile( pub async fn toggle_success_based_routing( state: web::Data<AppState>, req: HttpRequest, - query: web::Query<api_models::routing::ToggleSuccessBasedRoutingQuery>, - path: web::Path<routing_types::ToggleSuccessBasedRoutingPath>, + query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>, + path: web::Path<routing_types::ToggleDynamicRoutingPath>, ) -> impl Responder { let flow = Flow::ToggleDynamicRouting; - let wrapper = routing_types::ToggleSuccessBasedRoutingWrapper { + let wrapper = routing_types::ToggleDynamicRoutingWrapper { feature_to_enable: query.into_inner().enable, profile_id: path.into_inner().profile_id, }; @@ -1029,14 +1029,15 @@ pub async fn toggle_success_based_routing( wrapper.clone(), |state, auth: auth::AuthenticationData, - wrapper: routing_types::ToggleSuccessBasedRoutingWrapper, + wrapper: routing_types::ToggleDynamicRoutingWrapper, _| { - routing::toggle_success_based_routing( + routing::toggle_specific_dynamic_routing( state, auth.merchant_account, auth.key_store, wrapper.feature_to_enable, wrapper.profile_id, + api_models::routing::DynamicRoutingType::SuccessRateBasedRouting, ) }, auth::auth_type( @@ -1085,3 +1086,46 @@ pub async fn success_based_routing_update_configs( )) .await } +#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] +pub async fn toggle_elimination_routing( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>, + path: web::Path<routing_types::ToggleDynamicRoutingPath>, +) -> impl Responder { + let flow = Flow::ToggleDynamicRouting; + let wrapper = routing_types::ToggleDynamicRoutingWrapper { + feature_to_enable: query.into_inner().enable, + profile_id: path.into_inner().profile_id, + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + wrapper.clone(), + |state, + auth: auth::AuthenticationData, + wrapper: routing_types::ToggleDynamicRoutingWrapper, + _| { + routing::toggle_specific_dynamic_routing( + state, + auth.merchant_account, + auth.key_store, + wrapper.feature_to_enable, + wrapper.profile_id, + api_models::routing::DynamicRoutingType::EliminationRouting, + ) + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::JWTAuthProfileFromRoute { + profile_id: wrapper.profile_id, + required_permission: Permission::ProfileRoutingWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index 69931057959..7a452106b2b 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -72,7 +72,7 @@ pub static PM_FILTERS_CGRAPH_CACHE: Lazy<Cache> = Lazy::new(|| { ) }); -/// Dynamic Algorithm Cache +/// Success based Dynamic Algorithm Cache pub static SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| { Cache::new( "SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE", @@ -82,6 +82,16 @@ pub static SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| { ) }); +/// Elimination based Dynamic Algorithm Cache +pub static ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| { + Cache::new( + "ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE", + CACHE_TTL, + CACHE_TTI, + Some(MAX_CAPACITY), + ) +}); + /// Trait which defines the behaviour of types that's gonna be stored in Cache pub trait Cacheable: Any + Send + Sync + DynClone { fn as_any(&self) -> &dyn Any; @@ -102,6 +112,7 @@ pub enum CacheKind<'a> { Surcharge(Cow<'a, str>), CGraph(Cow<'a, str>), SuccessBasedDynamicRoutingCache(Cow<'a, str>), + EliminationBasedDynamicRoutingCache(Cow<'a, str>), PmFiltersCGraph(Cow<'a, str>), All(Cow<'a, str>), } diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs index 6a2012f9b26..42ad2ae0795 100644 --- a/crates/storage_impl/src/redis/pub_sub.rs +++ b/crates/storage_impl/src/redis/pub_sub.rs @@ -6,8 +6,8 @@ use router_env::{logger, tracing::Instrument}; use crate::redis::cache::{ CacheKey, CacheKind, CacheRedact, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, - DECISION_MANAGER_CACHE, PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE, - SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE, + DECISION_MANAGER_CACHE, ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, PM_FILTERS_CGRAPH_CACHE, + ROUTING_CACHE, SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE, }; #[async_trait::async_trait] @@ -138,6 +138,15 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> { .await; key } + CacheKind::EliminationBasedDynamicRoutingCache(key) => { + ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: message.tenant.clone(), + }) + .await; + key + } CacheKind::SuccessBasedDynamicRoutingCache(key) => { SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { @@ -205,6 +214,12 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> { prefix: message.tenant.clone(), }) .await; + ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: message.tenant.clone(), + }) + .await; ROUTING_CACHE .remove(CacheKey { key: key.to_string(),
2024-11-14T08:21:23Z
## Description <!-- Describe your changes in detail --> This PR will add route to enable Elimination based dynamic routing for specific profiles. ``` curl --location --request POST 'http://localhost:8080/account/MERCHANT_ID/business_profile/PROFILE_ID/dynamic_routing/elimination/toggle?enable=none' \ --header 'api-key: API_KEY' ``` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Testing Scenarios: 1. enable elimination routing and check Profile table for the following value: ``` dynamic_routing_algorithm | {"success_based_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":"routing_2hS6Dn3XRjICecmNZg5s","timestamp":1732569416},"enabled_feature":"metrics"},"elimination_routing_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":"routing_nkajfnkjanf131231","timestamp":1732569427},"enabled_feature":"metrics"}} ``` can be enabled by this curl: ``` curl --location --request POST 'http://localhost:8080/account/MERCHANT_ID/business_profile/PROFILE_ID/dynamic_routing/elimination/toggle?enable=metrics' \ --header 'api-key: API_KEY' ``` 2. disable elimination routing and check profile table(can be disabled by passing enable as none), Note: SR shouldn't be removed. ``` dynamic_routing_algorithm | {"success_based_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":"routing_2hS6Dn3XRjICecmNZg5s","timestamp":1732569416},"enabled_feature":"metrics"},"elimination_routing_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":null,"timestamp":1732569427},"enabled_feature":"none"}} ``` can be disabled by this curl: ``` curl --location --request POST 'http://localhost:8080/account/MERCHANT_ID/business_profile/PROFILE_ID/dynamic_routing/elimination/toggle?enable=none' \ --header 'api-key: API_KEY' ```
d4b482c21cf57b022c7bbadc1a3a9c9d9e5d4f03
Testing Scenarios: 1. enable elimination routing and check Profile table for the following value: ``` dynamic_routing_algorithm | {"success_based_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":"routing_2hS6Dn3XRjICecmNZg5s","timestamp":1732569416},"enabled_feature":"metrics"},"elimination_routing_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":"routing_nkajfnkjanf131231","timestamp":1732569427},"enabled_feature":"metrics"}} ``` can be enabled by this curl: ``` curl --location --request POST 'http://localhost:8080/account/MERCHANT_ID/business_profile/PROFILE_ID/dynamic_routing/elimination/toggle?enable=metrics' \ --header 'api-key: API_KEY' ``` 2. disable elimination routing and check profile table(can be disabled by passing enable as none), Note: SR shouldn't be removed. ``` dynamic_routing_algorithm | {"success_based_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":"routing_2hS6Dn3XRjICecmNZg5s","timestamp":1732569416},"enabled_feature":"metrics"},"elimination_routing_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":null,"timestamp":1732569427},"enabled_feature":"none"}} ``` can be disabled by this curl: ``` curl --location --request POST 'http://localhost:8080/account/MERCHANT_ID/business_profile/PROFILE_ID/dynamic_routing/elimination/toggle?enable=none' \ --header 'api-key: API_KEY' ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/events/routing.rs", "crates/api_models/src/routing.rs", "crates/openapi/src/openapi.rs", "crates/openapi/src/routes/routing.rs", "crates/router/src/core/payments/routing.rs", "crates/router/src/core/routing.rs", "crates/router/src/core/routing/helpers.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/routing.rs", "crates/storage_impl/src/redis/cache.rs", "crates/storage_impl/src/redis/pub_sub.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6287
Bug: Add cypress test case for `network_transaction_id_and_card_details` recurring details MIT Test cases should be added to `network_transaction_id_and_card_details` based recurring MIT flow
2024-11-14T06:06:56Z
## Description <!-- Describe your changes in detail --> [Reference pr](https://github.com/juspay/hyperswitch/pull/6245) Add test cases MIT flow using the recurring_details of type `network_transaction_id_and_card_details`. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Cypress tests <img width="442" alt="image" src="https://github.com/user-attachments/assets/c871d675-1d44-49f9-9dd9-94cc3b58b9c0">
f24578310f44adf75c993ba42225554377399961
Cypress tests <img width="442" alt="image" src="https://github.com/user-attachments/assets/c871d675-1d44-49f9-9dd9-94cc3b58b9c0">
[]
juspay/hyperswitch
juspay__hyperswitch-5893
Bug: [CYPRESS] : Add Checkout Connector **Description:** This task involves adding a payment connector for the checkout functionality in Cypress. For reference, similar connectors have already been implemented in the repository. You can refer to the existing connectors here: https://github.com/juspay/hyperswitch/tree/main/cypress-tests/cypress/e2e/PaymentUtils **Pre-requisites:** - Cypress is the testing framework that Hyperswitch is using to run automated tests. Having good grip on Javascript to work on Cypress is a must. - Please follow the [README](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/readme.md) for guidelines on file structure, formatting and instructions on how to set up and run Cypress. **Steps:** 1. Add the checkout connector .js files under the PaymentUtils directory: [PaymentUtils Directory](https://github.com/juspay/hyperswitch/tree/main/cypress-tests/cypress/e2e/PaymentUtils) 2. Add the card details and corresponding test case functions for checkout, following the format used in the [Cybersource.js connector](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js). 3. In the checkout connector, map the test cases and statuses properly. To do this, use the below dashboard credentials where checkout is already configured, test the flows, and then assign the correct statuses. URL: https://integ.hyperswitch.io Username, Password: Please drop a comment requesting credentials. The Creds are only shared on request **Test Cases:** - Add test cases only for card payments. **Postman collection for reference** https://www.postman.com/altimetry-participant-63653904/hyperswitch Note: - Test cases for other payment methods should be skipped. - The test cases are already written under PaymentTest: - [PaymentTest Directory](https://github.com/juspay/hyperswitch/tree/main/cypress-tests/cypress/e2e/PaymentTest).Just map the test cases and their statuses in the config.js file. ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
2024-11-13T13:36:29Z
## Description Add Checkout Connector for Cypress Automation ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Checkout connector was not available in the cypress automation ## How did you test it? Cypress Tests - Checkout <img width="710" alt="image" src="https://github.com/user-attachments/assets/75bc70aa-8bc5-43f6-ad28-ac33c7bcf6de"> - NMI <img width="710" alt="image" src="https://github.com/user-attachments/assets/cb4b4b21-8a93-4a88-8e67-5172d0847ca4">
600cf44684912192f0bf1b9566fd0a7daae9f54c
Cypress Tests - Checkout <img width="710" alt="image" src="https://github.com/user-attachments/assets/75bc70aa-8bc5-43f6-ad28-ac33c7bcf6de"> - NMI <img width="710" alt="image" src="https://github.com/user-attachments/assets/cb4b4b21-8a93-4a88-8e67-5172d0847ca4">
[]
juspay/hyperswitch
juspay__hyperswitch-6548
Bug: refactor(core): add profile_id for default_fallback api ## Description This will refactor the route routing/default/profile into /default/profile/{profile_id}, Previously the output for this route was the default fallback connectors from all the profiles, After this refactor it will have the fallback connectors only for the mentioned profile.
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 0bd38918ee7..94eb9bd741e 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -909,26 +909,30 @@ pub async fn retrieve_default_fallback_algorithm_for_profile( } #[cfg(feature = "v1")] - pub async fn retrieve_default_routing_config( state: SessionState, + profile_id: Option<common_utils::id_type::ProfileId>, merchant_account: domain::MerchantAccount, transaction_type: &enums::TransactionType, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(&metrics::CONTEXT, 1, &[]); let db = state.store.as_ref(); + let id = profile_id + .map(|profile_id| profile_id.get_string_repr().to_owned()) + .unwrap_or_else(|| merchant_account.get_id().get_string_repr().to_string()); - helpers::get_merchant_default_config( - db, - merchant_account.get_id().get_string_repr(), - transaction_type, - ) - .await - .map(|conn_choice| { - metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]); - service_api::ApplicationResponse::Json(conn_choice) - }) + helpers::get_merchant_default_config(db, &id, transaction_type) + .await + .map(|conn_choice| { + metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add( + &metrics::CONTEXT, + 1, + &[], + ); + service_api::ApplicationResponse::Json(conn_choice) + }) } + #[cfg(feature = "v2")] pub async fn retrieve_routing_config_under_profile( state: SessionState, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index ee6bd68ac2f..8a12f8a8fdc 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -759,22 +759,14 @@ impl Routing { }, ))) .service( - web::resource("/default") - .route(web::get().to(|state, req| { - routing::routing_retrieve_default_config( - state, - req, - &TransactionType::Payment, - ) - })) - .route(web::post().to(|state, req, payload| { - routing::routing_update_default_config( - state, - req, - payload, - &TransactionType::Payment, - ) - })), + web::resource("/default").route(web::post().to(|state, req, payload| { + routing::routing_update_default_config( + state, + req, + payload, + &TransactionType::Payment, + ) + })), ) .service( web::resource("/deactivate").route(web::post().to(|state, req, payload| { @@ -808,11 +800,7 @@ impl Routing { ) .service( web::resource("/default/profile").route(web::get().to(|state, req| { - routing::routing_retrieve_default_config_for_profiles( - state, - req, - &TransactionType::Payment, - ) + routing::routing_retrieve_default_config(state, req, &TransactionType::Payment) })), ); diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index f0269bd029a..b861b54b5b5 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -565,17 +565,13 @@ pub async fn routing_retrieve_default_config( &req, (), |state, auth: auth::AuthenticationData, _, _| { - routing::retrieve_default_routing_config(state, auth.merchant_account, transaction_type) + routing::retrieve_default_routing_config( + state, + auth.profile_id, + auth.merchant_account, + transaction_type, + ) }, - #[cfg(not(feature = "release"))] - auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth { - permission: Permission::ProfileRoutingRead, - }, - req.headers(), - ), - #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileRoutingRead, },
2024-11-12T13:46:03Z
## Description <!-- Describe your changes in detail --> This will refactor the route `routing/default/profile` Previously the output for this route was the default fallback connectors from all the profiles, After this refactor it will have the fallback connectors only for the mentioned profile. If the `profile_id` is provided by the authentication layer, if not it will behave as previous by taking the `merchant_id` from auth layer. Moreover we have removed 2 routes from backed as these were not being used(Dahboard as well as internal apis), hence were redundant. GET `routing/default` POST `routing/default` ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Required by our Dashboard to move the api's under profile level ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://127.0.0.1:8080/routing/default/profile' \ --header 'Authorization: Bearer token ``` This should have the connectors from the mentioned profile only. ``` [ { "connector": "bankofamerica", "merchant_connector_id": "mca_ADICIF9zh09TjnpUgusU" } ] ```
6808272de305c685b7cf948060f006d39cbac60b
``` curl --location 'http://127.0.0.1:8080/routing/default/profile' \ --header 'Authorization: Bearer token ``` This should have the connectors from the mentioned profile only. ``` [ { "connector": "bankofamerica", "merchant_connector_id": "mca_ADICIF9zh09TjnpUgusU" } ] ```
[ "crates/router/src/core/routing.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/routing.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6542
Bug: ci: run cybersource along with stripe ci: run cybersource along with stripe
2024-11-12T09:40:28Z
## Description <!-- Describe your changes in detail --> Run Cybersource in parallel along with Stripe. closes #6542 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> NA ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Let the CI check pass: https://github.com/juspay/hyperswitch/actions/runs/11794582778/job/32975411512?pr=6541
20a3a1c2d6bb93fb4dae7f7eb669ebd85e631c96
Let the CI check pass: https://github.com/juspay/hyperswitch/actions/runs/11794582778/job/32975411512?pr=6541
[]
juspay/hyperswitch
juspay__hyperswitch-6534
Bug: refactor(users): Make `profile_id` in the JWT non-optional - We kept the `profile_id` in the JWT optional for backwards compatibility. - Now we have `profile_id` in all the JWT and this field no longer needs to be optional in JWT.
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index 2496d22447e..ed018cc2381 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -87,7 +87,7 @@ impl UserRole { user_id: String, org_id: id_type::OrganizationId, merchant_id: id_type::MerchantId, - profile_id: Option<id_type::ProfileId>, + profile_id: id_type::ProfileId, version: UserRoleVersion, ) -> StorageResult<Self> { // Checking in user roles, for a user in token hierarchy, only one of the relation will be true, either org level, merchant level or profile level @@ -103,7 +103,6 @@ impl UserRole { .or(dsl::org_id.eq(org_id).and( dsl::merchant_id .eq(merchant_id) - //TODO: In case of None, profile_id = NULL its unexpected behaviour, after V1 profile id will not be option .and(dsl::profile_id.eq(profile_id)), )); @@ -137,7 +136,6 @@ impl UserRole { .or(dsl::org_id.eq(org_id).and( dsl::merchant_id .eq(merchant_id) - //TODO: In case of None, profile_id = NULL its unexpected behaviour, after V1 profile id will not be option .and(dsl::profile_id.eq(profile_id)), )); @@ -160,7 +158,7 @@ impl UserRole { user_id: String, org_id: id_type::OrganizationId, merchant_id: id_type::MerchantId, - profile_id: Option<id_type::ProfileId>, + profile_id: id_type::ProfileId, version: UserRoleVersion, ) -> StorageResult<Self> { // Checking in user roles, for a user in token hierarchy, only one of the relation will be true, either org level, merchant level or profile level @@ -176,7 +174,6 @@ impl UserRole { .or(dsl::org_id.eq(org_id).and( dsl::merchant_id .eq(merchant_id) - //TODO: In case of None, profile_id = NULL its unexpected behaviour, after V1 profile id will not be option .and(dsl::profile_id.eq(profile_id)), )); diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index aad2537c3d9..4eb4cf5ed2e 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -119,9 +119,7 @@ pub async fn get_user_details( org_id: user_from_token.org_id, is_two_factor_auth_setup: user.get_totp_status() == TotpStatus::Set, recovery_codes_left: user.get_recovery_codes().map(|codes| codes.len()), - profile_id: user_from_token - .profile_id - .ok_or(UserErrors::JwtProfileIdMissing)?, + profile_id: user_from_token.profile_id, entity_type: role_info.get_entity_type(), }, )) @@ -603,7 +601,7 @@ async fn handle_existing_user_invitation( invitee_user_from_db.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - user_from_token.profile_id.as_ref(), + &user_from_token.profile_id, UserRoleVersion::V1, ) .await @@ -619,7 +617,7 @@ async fn handle_existing_user_invitation( invitee_user_from_db.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - user_from_token.profile_id.as_ref(), + &user_from_token.profile_id, UserRoleVersion::V2, ) .await @@ -673,10 +671,6 @@ async fn handle_existing_user_invitation( .await? } EntityType::Profile => { - let profile_id = user_from_token - .profile_id - .clone() - .ok_or(UserErrors::InternalServerError)?; user_role .add_entity(domain::ProfileLevel { tenant_id: user_from_token @@ -685,7 +679,7 @@ async fn handle_existing_user_invitation( .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), - profile_id: profile_id.clone(), + profile_id: user_from_token.profile_id.clone(), }) .insert_in_v2(state) .await? @@ -705,16 +699,10 @@ async fn handle_existing_user_invitation( entity_id: user_from_token.merchant_id.get_string_repr().to_owned(), entity_type: EntityType::Merchant, }, - EntityType::Profile => { - let profile_id = user_from_token - .profile_id - .clone() - .ok_or(UserErrors::InternalServerError)?; - email_types::Entity { - entity_id: profile_id.get_string_repr().to_owned(), - entity_type: EntityType::Profile, - } - } + EntityType::Profile => email_types::Entity { + entity_id: user_from_token.profile_id.get_string_repr().to_owned(), + entity_type: EntityType::Profile, + }, }; let email_contents = email_types::InviteUser { @@ -812,10 +800,6 @@ async fn handle_new_user_invitation( .await? } EntityType::Profile => { - let profile_id = user_from_token - .profile_id - .clone() - .ok_or(UserErrors::InternalServerError)?; user_role .add_entity(domain::ProfileLevel { tenant_id: user_from_token @@ -824,7 +808,7 @@ async fn handle_new_user_invitation( .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), - profile_id: profile_id.clone(), + profile_id: user_from_token.profile_id.clone(), }) .insert_in_v2(state) .await? @@ -848,16 +832,10 @@ async fn handle_new_user_invitation( entity_id: user_from_token.merchant_id.get_string_repr().to_owned(), entity_type: EntityType::Merchant, }, - EntityType::Profile => { - let profile_id = user_from_token - .profile_id - .clone() - .ok_or(UserErrors::InternalServerError)?; - email_types::Entity { - entity_id: profile_id.get_string_repr().to_owned(), - entity_type: EntityType::Profile, - } - } + EntityType::Profile => email_types::Entity { + entity_id: user_from_token.profile_id.get_string_repr().to_owned(), + entity_type: EntityType::Profile, + }, }; let email_contents = email_types::InviteUser { @@ -887,7 +865,7 @@ async fn handle_new_user_invitation( merchant_id: user_from_token.merchant_id.clone(), org_id: user_from_token.org_id.clone(), role_id: request.role_id.clone(), - profile_id: None, + profile_id: user_from_token.profile_id.clone(), tenant_id: user_from_token.tenant_id.clone(), }; @@ -939,7 +917,7 @@ pub async fn resend_invite( user.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - user_from_token.profile_id.as_ref(), + &user_from_token.profile_id, UserRoleVersion::V2, ) .await @@ -962,7 +940,7 @@ pub async fn resend_invite( user.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - user_from_token.profile_id.as_ref(), + &user_from_token.profile_id, UserRoleVersion::V1, ) .await @@ -1235,10 +1213,7 @@ pub async fn list_user_roles_details( merchant_id: (requestor_role_info.get_entity_type() <= EntityType::Merchant) .then_some(&user_from_token.merchant_id), profile_id: (requestor_role_info.get_entity_type() <= EntityType::Profile) - .then_some(&user_from_token.profile_id) - .cloned() - .flatten() - .as_ref(), + .then_some(&user_from_token.profile_id), entity_id: None, version: None, status: None, @@ -2864,7 +2839,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant( request: user_api::SwitchProfileRequest, user_from_token: auth::UserFromToken, ) -> UserResponse<user_api::TokenResponse> { - if user_from_token.profile_id == Some(request.profile_id.clone()) { + if user_from_token.profile_id == request.profile_id { return Err(UserErrors::InvalidRoleOperationWithMessage( "User switching to same profile".to_string(), ) diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 95a8b7d51d1..6641e553fd8 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -161,7 +161,7 @@ pub async fn update_user_role( user_to_be_updated.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - user_from_token.profile_id.as_ref(), + &user_from_token.profile_id, UserRoleVersion::V2, ) .await @@ -215,7 +215,7 @@ pub async fn update_user_role( user_to_be_updated.get_user_id(), &user_from_token.org_id, Some(&user_from_token.merchant_id), - user_from_token.profile_id.as_ref(), + Some(&user_from_token.profile_id), UserRoleUpdate::UpdateRole { role_id: req.role_id.clone(), modified_by: user_from_token.user_id.clone(), @@ -234,7 +234,7 @@ pub async fn update_user_role( user_to_be_updated.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - user_from_token.profile_id.as_ref(), + &user_from_token.profile_id, UserRoleVersion::V1, ) .await @@ -288,7 +288,7 @@ pub async fn update_user_role( user_to_be_updated.get_user_id(), &user_from_token.org_id, Some(&user_from_token.merchant_id), - user_from_token.profile_id.as_ref(), + Some(&user_from_token.profile_id), UserRoleUpdate::UpdateRole { role_id: req.role_id.clone(), modified_by: user_from_token.user_id, @@ -475,7 +475,7 @@ pub async fn delete_user_role( user_from_db.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - user_from_token.profile_id.as_ref(), + &user_from_token.profile_id, UserRoleVersion::V2, ) .await @@ -522,7 +522,7 @@ pub async fn delete_user_role( user_from_db.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - user_from_token.profile_id.as_ref(), + &user_from_token.profile_id, UserRoleVersion::V2, ) .await @@ -537,7 +537,7 @@ pub async fn delete_user_role( user_from_db.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - user_from_token.profile_id.as_ref(), + &user_from_token.profile_id, UserRoleVersion::V1, ) .await @@ -584,7 +584,7 @@ pub async fn delete_user_role( user_from_db.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - user_from_token.profile_id.as_ref(), + &user_from_token.profile_id, UserRoleVersion::V1, ) .await @@ -676,17 +676,13 @@ pub async fn list_users_in_lineage( .await? } EntityType::Profile => { - let Some(profile_id) = user_from_token.profile_id.as_ref() else { - return Err(UserErrors::JwtProfileIdMissing.into()); - }; - utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, org_id: &user_from_token.org_id, merchant_id: Some(&user_from_token.merchant_id), - profile_id: Some(profile_id), + profile_id: Some(&user_from_token.profile_id), version: None, limit: None, }, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 4b99a9c8f3a..57343e66488 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3026,7 +3026,7 @@ impl UserRoleInterface for KafkaStore { user_id: &str, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, - profile_id: Option<&id_type::ProfileId>, + profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store @@ -3066,7 +3066,7 @@ impl UserRoleInterface for KafkaStore { user_id: &str, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, - profile_id: Option<&id_type::ProfileId>, + profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index 2d9a949879a..e4e564dc9a4 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -45,7 +45,7 @@ pub trait UserRoleInterface { user_id: &str, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, - profile_id: Option<&id_type::ProfileId>, + profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; @@ -64,7 +64,7 @@ pub trait UserRoleInterface { user_id: &str, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, - profile_id: Option<&id_type::ProfileId>, + profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; @@ -100,7 +100,7 @@ impl UserRoleInterface for Store { user_id: &str, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, - profile_id: Option<&id_type::ProfileId>, + profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -109,7 +109,7 @@ impl UserRoleInterface for Store { user_id.to_owned(), org_id.to_owned(), merchant_id.to_owned(), - profile_id.cloned(), + profile_id.to_owned(), version, ) .await @@ -146,7 +146,7 @@ impl UserRoleInterface for Store { user_id: &str, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, - profile_id: Option<&id_type::ProfileId>, + profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; @@ -155,7 +155,7 @@ impl UserRoleInterface for Store { user_id.to_owned(), org_id.to_owned(), merchant_id.to_owned(), - profile_id.cloned(), + profile_id.to_owned(), version, ) .await @@ -245,7 +245,7 @@ impl UserRoleInterface for MockDb { user_id: &str, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, - profile_id: Option<&id_type::ProfileId>, + profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let user_roles = self.user_roles.lock().await; @@ -261,7 +261,7 @@ impl UserRoleInterface for MockDb { let profile_level_check = user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == Some(merchant_id) - && user_role.profile_id.as_ref() == profile_id; + && user_role.profile_id.as_ref() == Some(profile_id); // Check if any condition matches and the version matches if user_role.user_id == user_id @@ -338,7 +338,7 @@ impl UserRoleInterface for MockDb { user_id: &str, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, - profile_id: Option<&id_type::ProfileId>, + profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; @@ -355,7 +355,7 @@ impl UserRoleInterface for MockDb { let profile_level_check = role.org_id.as_ref() == Some(org_id) && role.merchant_id.as_ref() == Some(merchant_id) - && role.profile_id.as_ref() == profile_id; + && role.profile_id.as_ref() == Some(profile_id); // Check if the user role matches the conditions and the version matches role.user_id == user_id diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index a22d6bf1df9..2caffd4d364 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -81,7 +81,7 @@ pub struct AuthenticationDataWithUser { pub merchant_account: domain::MerchantAccount, pub key_store: domain::MerchantKeyStore, pub user: storage::User, - pub profile_id: Option<id_type::ProfileId>, + pub profile_id: id_type::ProfileId, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] @@ -225,7 +225,7 @@ pub struct AuthToken { pub role_id: String, pub exp: u64, pub org_id: id_type::OrganizationId, - pub profile_id: Option<id_type::ProfileId>, + pub profile_id: id_type::ProfileId, pub tenant_id: Option<String>, } @@ -237,7 +237,7 @@ impl AuthToken { role_id: String, settings: &Settings, org_id: id_type::OrganizationId, - profile_id: Option<id_type::ProfileId>, + profile_id: id_type::ProfileId, tenant_id: Option<String>, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); @@ -261,7 +261,7 @@ pub struct UserFromToken { pub merchant_id: id_type::MerchantId, pub role_id: String, pub org_id: id_type::OrganizationId, - pub profile_id: Option<id_type::ProfileId>, + pub profile_id: id_type::ProfileId, pub tenant_id: Option<String>, } @@ -1734,7 +1734,7 @@ where let auth = AuthenticationData { merchant_account: merchant, key_store, - profile_id: payload.profile_id, + profile_id: Some(payload.profile_id), }; Ok(( @@ -1916,7 +1916,7 @@ where let auth = AuthenticationData { merchant_account: merchant, key_store, - profile_id: payload.profile_id, + profile_id: Some(payload.profile_id), }; Ok(( auth.clone(), @@ -2030,11 +2030,7 @@ where return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } - if payload - .profile_id - .as_ref() - .is_some_and(|profile_id| *profile_id != self.profile_id) - { + if payload.profile_id != self.profile_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } @@ -2067,7 +2063,7 @@ where let auth = AuthenticationData { merchant_account: merchant, key_store, - profile_id: payload.profile_id, + profile_id: Some(payload.profile_id), }; Ok(( auth.clone(), @@ -2131,30 +2127,14 @@ where .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; - if let Some(ref payload_profile_id) = payload.profile_id { - if *payload_profile_id != self.profile_id { - return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); - } else { - // if both of them are same then proceed with the profile id present in the request - let auth = AuthenticationData { - merchant_account: merchant, - key_store, - profile_id: Some(self.profile_id.clone()), - }; - Ok(( - auth.clone(), - AuthenticationType::MerchantJwt { - merchant_id: auth.merchant_account.get_id().clone(), - user_id: Some(payload.user_id), - }, - )) - } + if payload.profile_id != self.profile_id { + return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } else { - // if profile_id is not present in the auth_layer itself then no change in behaviour + // if both of them are same then proceed with the profile id present in the request let auth = AuthenticationData { merchant_account: merchant, key_store, - profile_id: payload.profile_id, + profile_id: Some(self.profile_id.clone()), }; Ok(( auth.clone(), @@ -2304,7 +2284,7 @@ where let auth = AuthenticationData { merchant_account: merchant, key_store, - profile_id: payload.profile_id, + profile_id: Some(payload.profile_id), }; Ok(( auth, @@ -2440,7 +2420,7 @@ where let auth = AuthenticationData { merchant_account: merchant, key_store, - profile_id: payload.profile_id, + profile_id: Some(payload.profile_id), }; Ok(( (auth.clone(), payload.user_id.clone()), @@ -2558,7 +2538,7 @@ where let auth = AuthenticationData { merchant_account: merchant, key_store, - profile_id: payload.profile_id, + profile_id: Some(payload.profile_id), }; Ok(( auth.clone(), diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index 86f10f1ceb7..634c781da7f 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -132,7 +132,7 @@ impl JWTFlow { .clone() .ok_or(report!(UserErrors::InternalServerError)) .attach_printable("org_id not found")?, - Some(profile_id), + profile_id, Some(user_role.tenant_id.clone()), ) .await diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index c4647907ff9..8a9daefb287 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -100,7 +100,7 @@ pub async fn generate_jwt_auth_token_with_attributes( role_id, &state.conf, org_id, - Some(profile_id), + profile_id, tenant_id, ) .await?;
2024-11-11T14:12:28Z
## Description <!-- Describe your changes in detail --> - Currently `profile_id` in the JWT is optional, this PR makes it non-optional. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6534. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This is a internal change and it should not affect any APIs.
98b141c6a00e6435385e1c513b1684d58567ecee
This is a internal change and it should not affect any APIs.
[ "crates/diesel_models/src/query/user_role.rs", "crates/router/src/core/user.rs", "crates/router/src/core/user_role.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/db/user_role.rs", "crates/router/src/services/authentication.rs", "crates/router/src/types/domain/user/decision_manager.rs", "crates/router/src/utils/user.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6536
Bug: refactor(routing): remove payment_id from dynamic_routing metrics
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 0250d00d1bb..aef89ea8ed9 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -733,7 +733,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( .label .to_string(); - let (first_success_based_connector, merchant_connector_id) = first_success_based_connector_label + let (first_success_based_connector, _) = first_success_based_connector_label .split_once(':') .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( @@ -753,17 +753,12 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( &add_attributes([ ("tenant", state.tenant.tenant_id.clone()), ( - "merchant_id", - payment_attempt.merchant_id.get_string_repr().to_string(), - ), - ( - "profile_id", - payment_attempt.profile_id.get_string_repr().to_string(), - ), - ("merchant_connector_id", merchant_connector_id.to_string()), - ( - "payment_id", - payment_attempt.payment_id.get_string_repr().to_string(), + "merchant_profile_id", + format!( + "{}:{}", + payment_attempt.merchant_id.get_string_repr(), + payment_attempt.profile_id.get_string_repr() + ), ), ( "success_based_routing_connector",
2024-11-11T13:52:51Z
## Description <!-- Describe your changes in detail --> This will remove payment_id from being pushed to dynamic_routing metrics ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This can be tested on SBX in the dynamic_routing Dashboard present on grafana dashboard, There shouldn't be payment_id and the merchant_id should be merged with profile_id
0a506b1729a27e47543cf24f64fbad08479d8dec
This can be tested on SBX in the dynamic_routing Dashboard present on grafana dashboard, There shouldn't be payment_id and the merchant_id should be merged with profile_id
[ "crates/router/src/core/routing/helpers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6532
Bug: feat(themes): Setup DB for themes There should a separate table for themes for storing the `theme_id`s for a particular lineage. This should be the schema: | org_id | merchant_id | profile_id | theme_id | | ------ | ----------- | ---------- | -------- | | o1 | m1 | p1 | t1 | | o1 | m1 | p2 | t2 | This will be used for changing theme automatically when user switches any entities.
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index ef7a4b847c4..f7cdfd3617b 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -3,6 +3,8 @@ pub mod keymanager; /// Enum for Authentication Level pub mod authentication; +/// Enum for Theme Lineage +pub mod theme; use std::{ borrow::Cow, diff --git a/crates/common_utils/src/types/theme.rs b/crates/common_utils/src/types/theme.rs new file mode 100644 index 00000000000..a2e6fe4b19c --- /dev/null +++ b/crates/common_utils/src/types/theme.rs @@ -0,0 +1,39 @@ +use crate::id_type; + +/// Enum for having all the required lineage for every level. +/// Currently being used for theme related APIs and queries. +#[derive(Debug)] +pub enum ThemeLineage { + /// Tenant lineage variant + Tenant { + /// tenant_id: String + tenant_id: String, + }, + /// Org lineage variant + Organization { + /// tenant_id: String + tenant_id: String, + /// org_id: OrganizationId + org_id: id_type::OrganizationId, + }, + /// Merchant lineage variant + Merchant { + /// tenant_id: String + tenant_id: String, + /// org_id: OrganizationId + org_id: id_type::OrganizationId, + /// merchant_id: MerchantId + merchant_id: id_type::MerchantId, + }, + /// Profile lineage variant + Profile { + /// tenant_id: String + tenant_id: String, + /// org_id: OrganizationId + org_id: id_type::OrganizationId, + /// merchant_id: MerchantId + merchant_id: id_type::MerchantId, + /// profile_id: ProfileId + profile_id: id_type::ProfileId, + }, +} diff --git a/crates/diesel_models/src/query/user.rs b/crates/diesel_models/src/query/user.rs index 2bd403a847b..1f6e16702fb 100644 --- a/crates/diesel_models/src/query/user.rs +++ b/crates/diesel_models/src/query/user.rs @@ -1,6 +1,8 @@ use common_utils::pii; use diesel::{associations::HasTable, ExpressionMethods}; + pub mod sample_data; +pub mod theme; use crate::{ query::generics, schema::users::dsl as users_dsl, user::*, PgPooledConn, StorageResult, diff --git a/crates/diesel_models/src/query/user/theme.rs b/crates/diesel_models/src/query/user/theme.rs new file mode 100644 index 00000000000..c021edca325 --- /dev/null +++ b/crates/diesel_models/src/query/user/theme.rs @@ -0,0 +1,95 @@ +use common_utils::types::theme::ThemeLineage; +use diesel::{ + associations::HasTable, + pg::Pg, + sql_types::{Bool, Nullable}, + BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, +}; + +use crate::{ + query::generics, + schema::themes::dsl, + user::theme::{Theme, ThemeNew}, + PgPooledConn, StorageResult, +}; + +impl ThemeNew { + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Theme> { + generics::generic_insert(conn, self).await + } +} + +impl Theme { + fn lineage_filter( + lineage: ThemeLineage, + ) -> Box< + dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>> + + 'static, + > { + match lineage { + ThemeLineage::Tenant { tenant_id } => Box::new( + dsl::tenant_id + .eq(tenant_id) + .and(dsl::org_id.is_null()) + .and(dsl::merchant_id.is_null()) + .and(dsl::profile_id.is_null()) + .nullable(), + ), + ThemeLineage::Organization { tenant_id, org_id } => Box::new( + dsl::tenant_id + .eq(tenant_id) + .and(dsl::org_id.eq(org_id)) + .and(dsl::merchant_id.is_null()) + .and(dsl::profile_id.is_null()), + ), + ThemeLineage::Merchant { + tenant_id, + org_id, + merchant_id, + } => Box::new( + dsl::tenant_id + .eq(tenant_id) + .and(dsl::org_id.eq(org_id)) + .and(dsl::merchant_id.eq(merchant_id)) + .and(dsl::profile_id.is_null()), + ), + ThemeLineage::Profile { + tenant_id, + org_id, + merchant_id, + profile_id, + } => Box::new( + dsl::tenant_id + .eq(tenant_id) + .and(dsl::org_id.eq(org_id)) + .and(dsl::merchant_id.eq(merchant_id)) + .and(dsl::profile_id.eq(profile_id)), + ), + } + } + + pub async fn find_by_lineage( + conn: &PgPooledConn, + lineage: ThemeLineage, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + Self::lineage_filter(lineage), + ) + .await + } + + pub async fn delete_by_theme_id_and_lineage( + conn: &PgPooledConn, + theme_id: String, + lineage: ThemeLineage, + ) -> StorageResult<Self> { + generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( + conn, + dsl::theme_id + .eq(theme_id) + .and(Self::lineage_filter(lineage)), + ) + .await + } +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index e2ab676b2d3..17de01b1862 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1262,6 +1262,26 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + themes (theme_id) { + #[max_length = 64] + theme_id -> Varchar, + #[max_length = 64] + tenant_id -> Varchar, + #[max_length = 64] + org_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Nullable<Varchar>, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + created_at -> Timestamp, + last_modified_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1406,6 +1426,7 @@ diesel::allow_tables_to_appear_in_same_query!( reverse_lookup, roles, routing_algorithm, + themes, unified_translations, user_authentication_methods, user_key_store, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 3bd31f5cbf3..7b4ccee2c4b 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1208,6 +1208,26 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + themes (theme_id) { + #[max_length = 64] + theme_id -> Varchar, + #[max_length = 64] + tenant_id -> Varchar, + #[max_length = 64] + org_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Nullable<Varchar>, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + created_at -> Timestamp, + last_modified_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1353,6 +1373,7 @@ diesel::allow_tables_to_appear_in_same_query!( reverse_lookup, roles, routing_algorithm, + themes, unified_translations, user_authentication_methods, user_key_store, diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs index 9f7b77dc5d6..cf584c09b12 100644 --- a/crates/diesel_models/src/user.rs +++ b/crates/diesel_models/src/user.rs @@ -6,8 +6,9 @@ use time::PrimitiveDateTime; use crate::{diesel_impl::OptionalDieselArray, enums::TotpStatus, schema::users}; pub mod dashboard_metadata; - pub mod sample_data; +pub mod theme; + #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = users, primary_key(user_id), check_for_backend(diesel::pg::Pg))] pub struct User { diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rs new file mode 100644 index 00000000000..0824ae71919 --- /dev/null +++ b/crates/diesel_models/src/user/theme.rs @@ -0,0 +1,29 @@ +use common_utils::id_type; +use diesel::{Identifiable, Insertable, Queryable, Selectable}; +use time::PrimitiveDateTime; + +use crate::schema::themes; + +#[derive(Clone, Debug, Identifiable, Queryable, Selectable)] +#[diesel(table_name = themes, primary_key(theme_id), check_for_backend(diesel::pg::Pg))] +pub struct Theme { + pub theme_id: String, + pub tenant_id: String, + pub org_id: Option<id_type::OrganizationId>, + pub merchant_id: Option<id_type::MerchantId>, + pub profile_id: Option<id_type::ProfileId>, + pub created_at: PrimitiveDateTime, + pub last_modified_at: PrimitiveDateTime, +} + +#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] +#[diesel(table_name = themes)] +pub struct ThemeNew { + pub theme_id: String, + pub tenant_id: String, + pub org_id: Option<id_type::OrganizationId>, + pub merchant_id: Option<id_type::MerchantId>, + pub profile_id: Option<id_type::ProfileId>, + pub created_at: PrimitiveDateTime, + pub last_modified_at: PrimitiveDateTime, +} diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 81319ae4c0b..377253e9735 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -145,6 +145,7 @@ pub trait GlobalStorageInterface: + dyn_clone::DynClone + user::UserInterface + user_key_store::UserKeyStoreInterface + + user::theme::ThemeInterface + 'static { } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 4b99a9c8f3a..d7d283819e5 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1,7 +1,11 @@ use std::sync::Arc; use common_enums::enums::MerchantStorageScheme; -use common_utils::{errors::CustomResult, id_type, pii, types::keymanager::KeyManagerState}; +use common_utils::{ + errors::CustomResult, + id_type, pii, + types::{keymanager::KeyManagerState, theme::ThemeLineage}, +}; use diesel_models::{ enums, enums::ProcessTrackerStatus, @@ -34,7 +38,7 @@ use time::PrimitiveDateTime; use super::{ dashboard_metadata::DashboardMetadataInterface, role::RoleInterface, - user::{sample_data::BatchSampleDataInterface, UserInterface}, + user::{sample_data::BatchSampleDataInterface, theme::ThemeInterface, UserInterface}, user_authentication_method::UserAuthenticationMethodInterface, user_key_store::UserKeyStoreInterface, user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload, UserRoleInterface}, @@ -3683,3 +3687,30 @@ impl UserAuthenticationMethodInterface for KafkaStore { .await } } + +#[async_trait::async_trait] +impl ThemeInterface for KafkaStore { + async fn insert_theme( + &self, + theme: storage::theme::ThemeNew, + ) -> CustomResult<storage::theme::Theme, errors::StorageError> { + self.diesel_store.insert_theme(theme).await + } + + async fn find_theme_by_lineage( + &self, + lineage: ThemeLineage, + ) -> CustomResult<storage::theme::Theme, errors::StorageError> { + self.diesel_store.find_theme_by_lineage(lineage).await + } + + async fn delete_theme_by_lineage_and_theme_id( + &self, + theme_id: String, + lineage: ThemeLineage, + ) -> CustomResult<storage::theme::Theme, errors::StorageError> { + self.diesel_store + .delete_theme_by_lineage_and_theme_id(theme_id, lineage) + .await + } +} diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index 3cf68551b52..14bed15fa45 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -11,6 +11,7 @@ use crate::{ services::Store, }; pub mod sample_data; +pub mod theme; #[async_trait::async_trait] pub trait UserInterface { diff --git a/crates/router/src/db/user/theme.rs b/crates/router/src/db/user/theme.rs new file mode 100644 index 00000000000..d71b82cdea4 --- /dev/null +++ b/crates/router/src/db/user/theme.rs @@ -0,0 +1,203 @@ +use common_utils::types::theme::ThemeLineage; +use diesel_models::user::theme as storage; +use error_stack::report; + +use super::MockDb; +use crate::{ + connection, + core::errors::{self, CustomResult}, + services::Store, +}; + +#[async_trait::async_trait] +pub trait ThemeInterface { + async fn insert_theme( + &self, + theme: storage::ThemeNew, + ) -> CustomResult<storage::Theme, errors::StorageError>; + + async fn find_theme_by_lineage( + &self, + lineage: ThemeLineage, + ) -> CustomResult<storage::Theme, errors::StorageError>; + + async fn delete_theme_by_lineage_and_theme_id( + &self, + theme_id: String, + lineage: ThemeLineage, + ) -> CustomResult<storage::Theme, errors::StorageError>; +} + +#[async_trait::async_trait] +impl ThemeInterface for Store { + async fn insert_theme( + &self, + theme: storage::ThemeNew, + ) -> CustomResult<storage::Theme, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + theme + .insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + async fn find_theme_by_lineage( + &self, + lineage: ThemeLineage, + ) -> CustomResult<storage::Theme, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::Theme::find_by_lineage(&conn, lineage) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + async fn delete_theme_by_lineage_and_theme_id( + &self, + theme_id: String, + lineage: ThemeLineage, + ) -> CustomResult<storage::Theme, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Theme::delete_by_theme_id_and_lineage(&conn, theme_id, lineage) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } +} + +fn check_theme_with_lineage(theme: &storage::Theme, lineage: &ThemeLineage) -> bool { + match lineage { + ThemeLineage::Tenant { tenant_id } => { + &theme.tenant_id == tenant_id + && theme.org_id.is_none() + && theme.merchant_id.is_none() + && theme.profile_id.is_none() + } + ThemeLineage::Organization { tenant_id, org_id } => { + &theme.tenant_id == tenant_id + && theme + .org_id + .as_ref() + .is_some_and(|org_id_inner| org_id_inner == org_id) + && theme.merchant_id.is_none() + && theme.profile_id.is_none() + } + ThemeLineage::Merchant { + tenant_id, + org_id, + merchant_id, + } => { + &theme.tenant_id == tenant_id + && theme + .org_id + .as_ref() + .is_some_and(|org_id_inner| org_id_inner == org_id) + && theme + .merchant_id + .as_ref() + .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) + && theme.profile_id.is_none() + } + ThemeLineage::Profile { + tenant_id, + org_id, + merchant_id, + profile_id, + } => { + &theme.tenant_id == tenant_id + && theme + .org_id + .as_ref() + .is_some_and(|org_id_inner| org_id_inner == org_id) + && theme + .merchant_id + .as_ref() + .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) + && theme + .profile_id + .as_ref() + .is_some_and(|profile_id_inner| profile_id_inner == profile_id) + } + } +} + +#[async_trait::async_trait] +impl ThemeInterface for MockDb { + async fn insert_theme( + &self, + new_theme: storage::ThemeNew, + ) -> CustomResult<storage::Theme, errors::StorageError> { + let mut themes = self.themes.lock().await; + for theme in themes.iter() { + if new_theme.theme_id == theme.theme_id { + return Err(errors::StorageError::DuplicateValue { + entity: "theme_id", + key: None, + } + .into()); + } + + if new_theme.tenant_id == theme.tenant_id + && new_theme.org_id == theme.org_id + && new_theme.merchant_id == theme.merchant_id + && new_theme.profile_id == theme.profile_id + { + return Err(errors::StorageError::DuplicateValue { + entity: "lineage", + key: None, + } + .into()); + } + } + + let theme = storage::Theme { + theme_id: new_theme.theme_id, + tenant_id: new_theme.tenant_id, + org_id: new_theme.org_id, + merchant_id: new_theme.merchant_id, + profile_id: new_theme.profile_id, + created_at: new_theme.created_at, + last_modified_at: new_theme.last_modified_at, + }; + themes.push(theme.clone()); + + Ok(theme) + } + + async fn find_theme_by_lineage( + &self, + lineage: ThemeLineage, + ) -> CustomResult<storage::Theme, errors::StorageError> { + let themes = self.themes.lock().await; + themes + .iter() + .find(|theme| check_theme_with_lineage(theme, &lineage)) + .cloned() + .ok_or( + errors::StorageError::ValueNotFound(format!( + "Theme with lineage {:?} not found", + lineage + )) + .into(), + ) + } + + async fn delete_theme_by_lineage_and_theme_id( + &self, + theme_id: String, + lineage: ThemeLineage, + ) -> CustomResult<storage::Theme, errors::StorageError> { + let mut themes = self.themes.lock().await; + let index = themes + .iter() + .position(|theme| { + theme.theme_id == theme_id && check_theme_with_lineage(theme, &lineage) + }) + .ok_or(errors::StorageError::ValueNotFound(format!( + "Theme with id {} and lineage {:?} not found", + theme_id, lineage + )))?; + + let theme = themes.remove(index); + + Ok(theme) + } +} diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index b3358d898b2..efcce567727 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -60,6 +60,7 @@ pub struct MockDb { pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>, pub user_authentication_methods: Arc<Mutex<Vec<store::user_authentication_method::UserAuthenticationMethod>>>, + pub themes: Arc<Mutex<Vec<store::user::theme::Theme>>>, } impl MockDb { @@ -105,6 +106,7 @@ impl MockDb { roles: Default::default(), user_key_store: Default::default(), user_authentication_methods: Default::default(), + themes: Default::default(), }) } } diff --git a/migrations/2024-11-06-121933_setup-themes-table/down.sql b/migrations/2024-11-06-121933_setup-themes-table/down.sql new file mode 100644 index 00000000000..4b590c34705 --- /dev/null +++ b/migrations/2024-11-06-121933_setup-themes-table/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +DROP INDEX IF EXISTS themes_index; +DROP TABLE IF EXISTS themes; diff --git a/migrations/2024-11-06-121933_setup-themes-table/up.sql b/migrations/2024-11-06-121933_setup-themes-table/up.sql new file mode 100644 index 00000000000..3d84fcd8140 --- /dev/null +++ b/migrations/2024-11-06-121933_setup-themes-table/up.sql @@ -0,0 +1,17 @@ +-- Your SQL goes here +CREATE TABLE IF NOT EXISTS themes ( + theme_id VARCHAR(64) PRIMARY KEY, + tenant_id VARCHAR(64) NOT NULL, + org_id VARCHAR(64), + merchant_id VARCHAR(64), + profile_id VARCHAR(64), + created_at TIMESTAMP NOT NULL, + last_modified_at TIMESTAMP NOT NULL +); + +CREATE UNIQUE INDEX IF NOT EXISTS themes_index ON themes ( + tenant_id, + COALESCE(org_id, '0'), + COALESCE(merchant_id, '0'), + COALESCE(profile_id, '0') +);
2024-11-11T12:08:51Z
## Description <!-- Describe your changes in detail --> This PR creates a new table named `themes` in the DB. This will be used to store the `theme_id` for any lineage of `tenant_id`, `org_id`, `merchant_id` and `profile_id`. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6532 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This is an internal change and there is no API to test this currently. I've tested the read query by creating a temporary API which uses the query created in this PR.
20a3a1c2d6bb93fb4dae7f7eb669ebd85e631c96
This is an internal change and there is no API to test this currently. I've tested the read query by creating a temporary API which uses the query created in this PR.
[ "crates/common_utils/src/types.rs", "crates/common_utils/src/types/theme.rs", "crates/diesel_models/src/query/user.rs", "crates/diesel_models/src/query/user/theme.rs", "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/schema_v2.rs", "crates/diesel_models/src/user.rs", "crates/diesel_models/src/user/theme.rs", "crates/router/src/db.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/db/user.rs", "crates/router/src/db/user/theme.rs", "crates/storage_impl/src/mock_db.rs", "migrations/2024-11-06-121933_setup-themes-table/down.sql", "migrations/2024-11-06-121933_setup-themes-table/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-6528
Bug: fix: trustpay eps redirection in cypress fix: trustpay eps redirection in cypress they changed it again
2024-11-11T10:19:51Z
## Description <!-- Describe your changes in detail --> Fix EPS Bank Redirect redirection in Cypress. Closes #6528 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> NIL ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="453" alt="image" src="https://github.com/user-attachments/assets/a712b6c3-74fa-4a41-8eae-3045bc41e3ac">
0a506b1729a27e47543cf24f64fbad08479d8dec
<img width="453" alt="image" src="https://github.com/user-attachments/assets/a712b6c3-74fa-4a41-8eae-3045bc41e3ac">
[]
juspay/hyperswitch
juspay__hyperswitch-6526
Bug: [FIX] fix response for migration api Currently there is inconsistent response due to no validations for request body fields for the migration api. Implementation - validations such as empty string check for network transaction id and empty object for connector mandate details should be enforced while evaluating the migration response.
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ad612ed6f3b..f07634060df 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -28,7 +28,7 @@ use common_utils::{ consts, crypto::{self, Encryptable}, encryption::Encryption, - ext_traits::{AsyncExt, BytesExt, Encode, StringExt, ValueExt}, + ext_traits::{AsyncExt, BytesExt, ConfigExt, Encode, StringExt, ValueExt}, generate_id, id_type, request::Request, type_name, @@ -55,6 +55,7 @@ use hyperswitch_domain_models::customer::CustomerUpdate; use kgraph_utils::transformers::IntoDirValue; use masking::Secret; use router_env::{instrument, metrics::add_attributes, tracing}; +use serde_json::json; use strum::IntoEnumIterator; use super::{ @@ -381,7 +382,7 @@ pub async fn migrate_payment_method( key_store: &domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodMigrateResponse> { let mut req = req; - let card_details = req.card.as_ref().get_required_value("card")?; + let card_details = &req.card.get_required_value("card")?; let card_number_validation_result = cards::CardNumber::from_str(card_details.card_number.peek()); @@ -780,17 +781,6 @@ pub async fn skip_locker_call_and_migrate_payment_method( let network_transaction_id = req.network_transaction_id.clone(); - migration_status.network_transaction_id_migrated(network_transaction_id.as_ref().map(|_| true)); - - migration_status.connector_mandate_details_migrated( - connector_mandate_details - .as_ref() - .map(|_| true) - .or_else(|| req.connector_mandate_details.as_ref().map(|_| false)), - ); - - migration_status.card_migrated(false); - let payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let current_time = common_utils::date_time::now(); @@ -810,11 +800,11 @@ pub async fn skip_locker_call_and_migrate_payment_method( scheme: req.card_network.clone().or(card.scheme.clone()), metadata: payment_method_metadata.map(Secret::new), payment_method_data: payment_method_data_encrypted.map(Into::into), - connector_mandate_details, + connector_mandate_details: connector_mandate_details.clone(), customer_acceptance: None, client_secret: None, status: enums::PaymentMethodStatus::Active, - network_transaction_id, + network_transaction_id: network_transaction_id.clone(), payment_method_issuer_code: None, accepted_currency: None, token: None, @@ -843,6 +833,21 @@ pub async fn skip_locker_call_and_migrate_payment_method( logger::debug!("Payment method inserted in db"); + migration_status.network_transaction_id_migrated( + network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)), + ); + + migration_status.connector_mandate_details_migrated( + connector_mandate_details + .clone() + .and_then(|val| if val == json!({}) { None } else { Some(true) }) + .or_else(|| { + req.connector_mandate_details + .clone() + .and_then(|val| (!val.0.is_empty()).then_some(false)) + }), + ); + if customer.default_payment_method_id.is_none() && req.payment_method.is_some() { let _ = set_default_payment_method( state, @@ -1166,10 +1171,14 @@ pub async fn get_client_secret_or_add_payment_method_for_migration( migration_status.connector_mandate_details_migrated( connector_mandate_details .clone() - .map(|_| true) - .or_else(|| req.connector_mandate_details.clone().map(|_| false)), + .and_then(|val| (val != json!({})).then_some(true)) + .or_else(|| { + req.connector_mandate_details + .clone() + .and_then(|val| (!val.0.is_empty()).then_some(false)) + }), ); - + //card is not migrated in this case migration_status.card_migrated(false); if res.status == enums::PaymentMethodStatus::AwaitingData { @@ -1722,15 +1731,6 @@ pub async fn save_migration_payment_method( let network_transaction_id = req.network_transaction_id.clone(); - migration_status.network_transaction_id_migrated(network_transaction_id.as_ref().map(|_| true)); - - migration_status.connector_mandate_details_migrated( - connector_mandate_details - .as_ref() - .map(|_| true) - .or_else(|| req.connector_mandate_details.as_ref().map(|_| false)), - ); - let response = match payment_method { #[cfg(feature = "payouts")] api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() { @@ -1940,8 +1940,8 @@ pub async fn save_migration_payment_method( pm_metadata.cloned(), None, locker_id, - connector_mandate_details, - network_transaction_id, + connector_mandate_details.clone(), + network_transaction_id.clone(), merchant_account.storage_scheme, payment_method_billing_address.map(Into::into), None, @@ -1954,6 +1954,20 @@ pub async fn save_migration_payment_method( } } + migration_status.card_migrated(true); + migration_status.network_transaction_id_migrated( + network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)), + ); + + migration_status.connector_mandate_details_migrated( + connector_mandate_details + .and_then(|val| if val == json!({}) { None } else { Some(true) }) + .or_else(|| { + req.connector_mandate_details + .and_then(|val| (!val.0.is_empty()).then_some(false)) + }), + ); + Ok(services::ApplicationResponse::Json(resp)) }
2024-11-11T10:06:16Z
## Description <!-- Describe your changes in detail --> #6300 has inconsistent response due to no validations for each field in migration api request body. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> test case - test migration api with empty fields. req - ``` curl --location 'http://localhost:8080/payment_methods/migrate' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data '{ "merchant_id": "merchant_id", "card": { "card_number": "card_number", "card_exp_month": "12", "card_exp_year": "21", "card_holder_name": "joseph Doe" }, "customer_id": "customer_id", "network_transaction_id": "", "payment_method": "card", "connector_mandate_details": {}, "network_token": { "network_token_data": { "network_token_number": " ", "network_token_exp_month": "12", "network_token_exp_year": "21" }, "network_token_requestor_ref_id": "" } }' ``` <img width="880" alt="Screenshot 2024-11-11 at 11 43 58 AM" src="https://github.com/user-attachments/assets/27b1f3b6-cfe9-4917-b3e5-db44342df845">
086115f47379b06185a1753979fc6dd9dc945afd
test case - test migration api with empty fields. req - ``` curl --location 'http://localhost:8080/payment_methods/migrate' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data '{ "merchant_id": "merchant_id", "card": { "card_number": "card_number", "card_exp_month": "12", "card_exp_year": "21", "card_holder_name": "joseph Doe" }, "customer_id": "customer_id", "network_transaction_id": "", "payment_method": "card", "connector_mandate_details": {}, "network_token": { "network_token_data": { "network_token_number": " ", "network_token_exp_month": "12", "network_token_exp_year": "21" }, "network_token_requestor_ref_id": "" } }' ``` <img width="880" alt="Screenshot 2024-11-11 at 11 43 58 AM" src="https://github.com/user-attachments/assets/27b1f3b6-cfe9-4917-b3e5-db44342df845">
[ "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4677
Bug: Add audit events for PaymentStatus update Created from #4525 This covers adding events for PaymentStatus operation This event should include the payment data similar to [PaymentCancel](https://github.com/juspay/hyperswitch/pull/4166) It should also include any metadata for the event e.g reason for payment rejection, error codes, rejection source etc ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 69f2d85d6a9..9aa905345c8 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -16,6 +16,7 @@ use crate::{ PaymentData, }, }, + events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ @@ -141,7 +142,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for async fn update_trackers<'b>( &'b self, _state: &'b SessionState, - _req_state: ReqState, + req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, @@ -156,6 +157,12 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for where F: 'b + Send, { + req_state + .event_context + .event(AuditEvent::new(AuditEventType::PaymentStatus)) + .with(payment_data.to_event()) + .emit(); + Ok((Box::new(self), payment_data)) } } @@ -167,7 +174,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequ async fn update_trackers<'b>( &'b self, _state: &'b SessionState, - _req_state: ReqState, + req_state: ReqState, payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: enums::MerchantStorageScheme, @@ -182,6 +189,12 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequ where F: 'b + Send, { + req_state + .event_context + .event(AuditEvent::new(AuditEventType::PaymentStatus)) + .with(payment_data.to_event()) + .emit(); + Ok((Box::new(self), payment_data)) } } diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs index c314fa8409f..a0f651b93c3 100644 --- a/crates/router/src/events/audit_events.rs +++ b/crates/router/src/events/audit_events.rs @@ -33,6 +33,7 @@ pub enum AuditEventType { }, PaymentApprove, PaymentCreate, + PaymentStatus, PaymentCompleteAuthorize, PaymentReject { error_code: Option<String>, @@ -79,6 +80,7 @@ impl Event for AuditEvent { AuditEventType::PaymentUpdate { .. } => "payment_update", AuditEventType::PaymentApprove { .. } => "payment_approve", AuditEventType::PaymentCreate { .. } => "payment_create", + AuditEventType::PaymentStatus { .. } => "payment_status", AuditEventType::PaymentCompleteAuthorize => "payment_complete_authorize", AuditEventType::PaymentReject { .. } => "payment_rejected", };
2024-11-08T12:48:57Z
## Description This PR adds an Audit event for the PaymentStatus operation. ### Additional Changes - [x] This PR modifies the files below - `crates/router/src/core/payments/operations/payment_status.rs` - `crates/router/src/events/audit_events.rs` ## Motivation and Context This PR fixes #4677 ## How did you test it - Hit the `Payments - Create` endpoint ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --data-raw '{ "amount": 10000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 10000, "customer_id": "StripeCustomer", "email": "test@test14.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "feature_metadata": { "search_tags": ["Bangalore", "Chennai"] }, "metadata": { "data2": "camel", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "profile_id": "pro_v5sFoHe80OeiUlIonocM" }' ``` - Response: ```json { "payment_id": "pay_JGFz7HS3yFZMtA7w82db", "merchant_id": "merchant_1726046328", "status": "succeeded", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000, "connector": "stripe_test", "client_secret": "pay_JGFz7HS3yFZMtA7w82db_secret_1zvdrFCjs1ZepqjgS4Vw", "created": "2024-12-16T07:12:44.627Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "test@test14.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "test@test14.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1734333164, "expires": 1734336764, "secret": "epk_44a2e5c540904c0dbd3e3cdff81c9180" }, "manual_retry_allowed": false, "connector_transaction_id": "pay_88KleFv1IFJndrZFwEgK", "frm_message": null, "metadata": { "data2": "camel", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": [ "1259195bb05bb44ea78ab60b26a54065183f91b3c5b3c2c074cadcf521305a79", "9bff7b14d0a57a00d98f5eb742418a50b3bdfe5993f16b4219bfa31989bdf80f" ] }, "reference_id": null, "payment_link": null, "profile_id": "pro_v5sFoHe80OeiUlIonocM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-12-16T07:27:44.627Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-12-16T07:12:45.719Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` - Now hit the `Payments - Retrieve` endpoint. ```bash curl --location 'http://localhost:8080/payments/pay_JGFz7HS3yFZMtA7w82db' \ --header 'Accept: application/json' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' ``` - Response: ```bash { "payment_id": "pay_JGFz7HS3yFZMtA7w82db", "merchant_id": "merchant_1726046328", "status": "succeeded", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000, "connector": "stripe_test", "client_secret": "pay_JGFz7HS3yFZMtA7w82db_secret_1zvdrFCjs1ZepqjgS4Vw", "created": "2024-12-16T07:12:44.627Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "test@test14.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "test@test14.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pay_88KleFv1IFJndrZFwEgK", "frm_message": null, "metadata": { "data2": "camel", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": [ "1259195bb05bb44ea78ab60b26a54065183f91b3c5b3c2c074cadcf521305a79", "9bff7b14d0a57a00d98f5eb742418a50b3bdfe5993f16b4219bfa31989bdf80f" ] }, "reference_id": null, "payment_link": null, "profile_id": "pro_v5sFoHe80OeiUlIonocM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-12-16T07:27:44.627Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-12-16T07:12:45.719Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` Audit log will get generated and can be viewed in hyperswitch-audit-events topic in kafka with `PaymentStatus` event-type. <img width="1092" alt="Screenshot 2024-12-16 at 12 44 57 PM" src="https://github.com/user-attachments/assets/964bbd78-93ff-41c1-87d6-3e47d7eb7c56" />
ed276ecc0017f7f98b6f8fa3841e6b8971f609f1
[ "crates/router/src/core/payments/operations/payment_status.rs", "crates/router/src/events/audit_events.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6513
Bug: docs(analytics): Instructions to set up `currency_conversion` (third party dependency API) ## Requirements After the changes by [this](#6418) PR, we need to update the documentation for `analytics` crate setup process. ## Reason Due to the third party dependency on `currency_conversion` crate, we need to ensure the proper setup of this service as well.
diff --git a/crates/analytics/docs/README.md b/crates/analytics/docs/README.md index 96218fc231c..eb5c26a6ba3 100644 --- a/crates/analytics/docs/README.md +++ b/crates/analytics/docs/README.md @@ -91,6 +91,44 @@ source = "kafka" After making this change, save the file and restart your application for the changes to take effect. +## Setting up Forex APIs + +To use Forex services, you need to sign up and get your API keys from the following providers: + +1. Primary Service + - Sign up for a free account and get your Primary API key [here](https://openexchangerates.org/). + - It will be in dashboard, labeled as `app_id`. + +2. Fallback Service + - Sign up for a free account and get your Fallback API key [here](https://apilayer.com/marketplace/exchangerate_host-api). + - It will be in dashboard, labeled as `access key`. + +### Configuring Forex APIs + +To configure the Forex APIs, update the `config/development.toml` or `config/docker_compose.toml` file with your API keys: + +```toml +[forex_api] +api_key = "YOUR API KEY HERE" # Replace the placeholder with your Primary API Key +fallback_api_key = "YOUR API KEY HERE" # Replace the placeholder with your Fallback API Key +``` +### Important Note +```bash +ERROR router::services::api: error: {"error":{"type":"api","message":"Failed to fetch currency exchange rate","code":"HE_00"}} +│ +├─▶ Failed to fetch currency exchange rate +│ +╰─▶ Could not acquire the lock for cache entry +``` + +_If you get the above error after setting up, simply remove the `redis` key `"{forex_cache}_lock"` by running this in shell_ + +```bash +redis-cli del "{forex_cache}_lock" +``` + +After making these changes, save the file and restart your application for the changes to take effect. + ## Enabling Data Features in Dashboard To check the data features in the dashboard, you need to enable them in the `config/dashboard.toml` configuration file.
2024-11-08T08:27:21Z
## Description <!-- Describe your changes in detail --> Now that `analytics` depends on `currency_conversion` crate after this [PR](#6418), we need to include instructions in `analytics` documentation to set up this service. ## Fixes #6513 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This is related to the PR #6418 and documents the necessary prerequisite setup info. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
a5ac69d1a77e772e430df8c4187942de44f23079
[ "crates/analytics/docs/README.md" ]
juspay/hyperswitch
juspay__hyperswitch-6518
Bug: get apple pay certificates only from metadata during the session call Currently we have apple pay certificates being stored in the `metadata` as well as `connector_wallet_details` when a merchant connector account is created. During the session call we try to get the certificates from the `connector_wallet_details` if it fails we try to get it from `metadata`. Currently when apple pay certificates are being updated with the merchant connector update call only the metadata is being updated. Because of this `connector_wallet_details` will still have the old data using which we make the session call. In order to fix it, this pr contains the changes to get the `apple pay certificates` from the `metadata` only as it will have the latest updated data. In subsequent pr mca update inconsistency will be handled.
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index ba8054696a1..545d05e776f 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -189,20 +189,11 @@ async fn create_applepay_session_token( ) } else { // Get the apple pay metadata - let connector_apple_pay_wallet_details = - helpers::get_applepay_metadata(router_data.connector_wallets_details.clone()) - .map_err(|error| { - logger::debug!( - "Apple pay connector wallets details parsing failed in create_applepay_session_token {:?}", - error - ) - }) - .ok(); - - let apple_pay_metadata = match connector_apple_pay_wallet_details { - Some(apple_pay_wallet_details) => apple_pay_wallet_details, - None => helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?, - }; + let apple_pay_metadata = + helpers::get_applepay_metadata(router_data.connector_meta_data.clone()) + .attach_printable( + "Failed to to fetch apple pay certificates during session call", + )?; // Get payment request data , apple pay session request and merchant keys let ( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 5a8bc5cd12b..acaccccbb17 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4788,32 +4788,17 @@ pub fn validate_customer_access( pub fn is_apple_pay_simplified_flow( connector_metadata: Option<pii::SecretSerdeValue>, - connector_wallets_details: Option<pii::SecretSerdeValue>, connector_name: Option<&String>, ) -> CustomResult<bool, errors::ApiErrorResponse> { - let connector_apple_pay_wallet_details = - get_applepay_metadata(connector_wallets_details) - .map_err(|error| { - logger::debug!( - "Apple pay connector wallets details parsing failed for {:?} in is_apple_pay_simplified_flow {:?}", - connector_name, - error - ) - }) - .ok(); - - let option_apple_pay_metadata = match connector_apple_pay_wallet_details { - Some(apple_pay_wallet_details) => Some(apple_pay_wallet_details), - None => get_applepay_metadata(connector_metadata) - .map_err(|error| { - logger::debug!( - "Apple pay metadata parsing failed for {:?} in is_apple_pay_simplified_flow {:?}", + let option_apple_pay_metadata = get_applepay_metadata(connector_metadata) + .map_err(|error| { + logger::info!( + "Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}", connector_name, error ) - }) - .ok(), - }; + }) + .ok(); // return true only if the apple flow type is simplified Ok(matches!( @@ -4999,7 +4984,6 @@ where let connector_data_list = if is_apple_pay_simplified_flow( merchant_connector_account_type.get_metadata(), - merchant_connector_account_type.get_connector_wallets_details(), merchant_connector_account_type .get_connector_name() .as_ref(), @@ -5027,10 +5011,6 @@ where for merchant_connector_account in profile_specific_merchant_connector_account_list { if is_apple_pay_simplified_flow( merchant_connector_account.metadata.clone(), - merchant_connector_account - .connector_wallets_details - .as_deref() - .cloned(), Some(&merchant_connector_account.connector_name), )? { let connector_data = api::ConnectorData::get_connector_by_name(
2024-11-08T07:44:48Z
## Description <!-- Describe your changes in detail --> Currently we have apple pay certificates being stored in the `metadata` as well as `connector_wallet_details` when a merchant connector account is created. During the session call we try to get the certificates from the `connector_wallet_details` if it fails we try to get it from `metadata`. Currently when apple pay certificates are being updated with the merchant connector update call only the metadata is being updated. Because of this `connector_wallet_details` will still have the old data using which we make the session call. In order to fix it, this pr contains the changes to get the `apple pay certificates` from the `metadata` only as it will have the latest updated data. In subsequent pr mca update inconsistency will be handled. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create merchant connector account with apple pay enabled (pass the certificates only in the metadata) -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_1mlXU5snhPhX9lzhh489Hafi6psrvNuTYGqgB7IWO10tUN81hYwfxqr54iHN9LqM' \ --data-raw '{ "amount": 6100, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "amount_to_capture": 6100, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } } }' ``` ``` { "payment_id": "pay_13yS6rPTfz2flIVwTdOD", "merchant_id": "merchant_1731058139", "status": "requires_payment_method", "amount": 6100, "net_amount": 6100, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_13yS6rPTfz2flIVwTdOD_secret_LDRqGrN0l1Oepne0sswI", "created": "2024-11-08T09:29:43.101Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": null, "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_qk2Nf6soRabKK4PTZPI7", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-08T09:44:43.101Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-11-08T09:29:43.156Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Make a session call ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_8f588c72e93146fd85d7888b57813cae' \ --data '{ "payment_id": "pay_13yS6rPTfz2flIVwTdOD", "wallets": [], "client_secret": "pay_13yS6rPTfz2flIVwTdOD_secret_LDRqGrN0l1Oepne0sswI" }' ``` ``` { "payment_id": "pay_9dkYqqMjqhB6HVEdmtH8", "client_secret": "pay_9dkYqqMjqhB6HVEdmtH8_secret_yLYrfUXwlbhz1WTcwAZ0", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "61.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-9dkYqqMjqhB6HVEdmtH8", "merchant": { "name": "Hyperswitch", "url": null, "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "61.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "session_token_data": { "epoch_timestamp": 1731058299555, "expires_at": 1731061899555, "merchant_session_identifier": "SSH56D7E29D55C14575B8A72585526E9989_7E0DD1295E42A30B376B18CB4E6B9B9FB4C5E36B3EDF9FB0DEA51F9419420173", "nonce": "bee270b5", "merchant_identifier": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8", "domain_name": "hyperswitch-demo-store.netlify.app", "display_name": "Shankar", "signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018830820184020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234313130383039333133395a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d01090431220420a43222765aad8e37be22057b06a5ff6b4a889b86eb254c8388ecfeb483bd2d20300a06082a8648ce3d04030204473045022005d15b2d109fff00c1f25743f54b973fc0868648bdfde0a53cb08c1b9f618dca022100b68baa956928c8ef13aeadf335868abefabd1ca358e546901d0a53961018187d000000000000", "operational_analytics_identifier": "Shankar:A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8", "retries": 0, "psp_id": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8" }, "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "61.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.test.fb" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` -> Now update the mca with different apple pay session data and make the session call ``` { "payment_id": "pay_9dkYqqMjqhB6HVEdmtH8", "client_secret": "pay_9dkYqqMjqhB6HVEdmtH8_secret_yLYrfUXwlbhz1WTcwAZ0", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "61.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "apple_pay", "session_token_data": { "epoch_timestamp": 1731058447406, "expires_at": 1731062047406, "merchant_session_identifier": "SSH9AE703AD4E89431CA6995DEB16AECED6_A0E617ED4A56A343E07C6E1255BD4098423B3A8E1243236462D07B14B4A0F7C3", "nonce": "1ccfd4d4", "merchant_identifier": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8", "domain_name": "hyperswitch-demo-store.netlify.app", "display_name": "hyperswitch", "signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018830820184020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234313130383039333430375a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d01090431220420aba73465373dde2c582d797f825db72d3cc16bde7b453859381fbe56ea62a66b300a06082a8648ce3d040302044730450221008c76d246dbd8929261aea7a0035b005213d065c8a3ac66339e66ecacdfc589e202200360ac83bb14a1954cfe02f0aef3213d3310a3fef863894bb47e21cea2a39631000000000000", "operational_analytics_identifier": "hyperswitch:A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8", "retries": 0, "psp_id": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8" }, "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "61.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.test.fb" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ```
a5ac69d1a77e772e430df8c4187942de44f23079
-> Create merchant connector account with apple pay enabled (pass the certificates only in the metadata) -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_1mlXU5snhPhX9lzhh489Hafi6psrvNuTYGqgB7IWO10tUN81hYwfxqr54iHN9LqM' \ --data-raw '{ "amount": 6100, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "amount_to_capture": 6100, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } } }' ``` ``` { "payment_id": "pay_13yS6rPTfz2flIVwTdOD", "merchant_id": "merchant_1731058139", "status": "requires_payment_method", "amount": 6100, "net_amount": 6100, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_13yS6rPTfz2flIVwTdOD_secret_LDRqGrN0l1Oepne0sswI", "created": "2024-11-08T09:29:43.101Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": null, "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_qk2Nf6soRabKK4PTZPI7", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-08T09:44:43.101Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-11-08T09:29:43.156Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Make a session call ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_8f588c72e93146fd85d7888b57813cae' \ --data '{ "payment_id": "pay_13yS6rPTfz2flIVwTdOD", "wallets": [], "client_secret": "pay_13yS6rPTfz2flIVwTdOD_secret_LDRqGrN0l1Oepne0sswI" }' ``` ``` { "payment_id": "pay_9dkYqqMjqhB6HVEdmtH8", "client_secret": "pay_9dkYqqMjqhB6HVEdmtH8_secret_yLYrfUXwlbhz1WTcwAZ0", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "61.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-9dkYqqMjqhB6HVEdmtH8", "merchant": { "name": "Hyperswitch", "url": null, "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "61.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "session_token_data": { "epoch_timestamp": 1731058299555, "expires_at": 1731061899555, "merchant_session_identifier": "SSH56D7E29D55C14575B8A72585526E9989_7E0DD1295E42A30B376B18CB4E6B9B9FB4C5E36B3EDF9FB0DEA51F9419420173", "nonce": "bee270b5", "merchant_identifier": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8", "domain_name": "hyperswitch-demo-store.netlify.app", "display_name": "Shankar", "signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018830820184020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234313130383039333133395a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d01090431220420a43222765aad8e37be22057b06a5ff6b4a889b86eb254c8388ecfeb483bd2d20300a06082a8648ce3d04030204473045022005d15b2d109fff00c1f25743f54b973fc0868648bdfde0a53cb08c1b9f618dca022100b68baa956928c8ef13aeadf335868abefabd1ca358e546901d0a53961018187d000000000000", "operational_analytics_identifier": "Shankar:A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8", "retries": 0, "psp_id": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8" }, "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "61.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.test.fb" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` -> Now update the mca with different apple pay session data and make the session call ``` { "payment_id": "pay_9dkYqqMjqhB6HVEdmtH8", "client_secret": "pay_9dkYqqMjqhB6HVEdmtH8_secret_yLYrfUXwlbhz1WTcwAZ0", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "61.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "apple_pay", "session_token_data": { "epoch_timestamp": 1731058447406, "expires_at": 1731062047406, "merchant_session_identifier": "SSH9AE703AD4E89431CA6995DEB16AECED6_A0E617ED4A56A343E07C6E1255BD4098423B3A8E1243236462D07B14B4A0F7C3", "nonce": "1ccfd4d4", "merchant_identifier": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8", "domain_name": "hyperswitch-demo-store.netlify.app", "display_name": "hyperswitch", "signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018830820184020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234313130383039333430375a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d01090431220420aba73465373dde2c582d797f825db72d3cc16bde7b453859381fbe56ea62a66b300a06082a8648ce3d040302044730450221008c76d246dbd8929261aea7a0035b005213d065c8a3ac66339e66ecacdfc589e202200360ac83bb14a1954cfe02f0aef3213d3310a3fef863894bb47e21cea2a39631000000000000", "operational_analytics_identifier": "hyperswitch:A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8", "retries": 0, "psp_id": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8" }, "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "61.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.test.fb" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ```
[ "crates/router/src/core/payments/flows/session_flow.rs", "crates/router/src/core/payments/helpers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6509
Bug: [Enhancement] V2: Standardise endpoint naming scheme Use kebab case for all API endpoints consistently for V2. i.e. `/v2/like-this` instead of `/v2/not_like_this`
diff --git a/api-reference-v2/api-reference/api-key/api-key--create.mdx b/api-reference-v2/api-reference/api-key/api-key--create.mdx index a92a8ea77fd..abc1dcda10f 100644 --- a/api-reference-v2/api-reference/api-key/api-key--create.mdx +++ b/api-reference-v2/api-reference/api-key/api-key--create.mdx @@ -1,3 +1,3 @@ --- -openapi: post /v2/api_keys +openapi: post /v2/api-keys --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/api-key/api-key--list.mdx b/api-reference-v2/api-reference/api-key/api-key--list.mdx index 5975e9bd6ca..fb84b35fbc7 100644 --- a/api-reference-v2/api-reference/api-key/api-key--list.mdx +++ b/api-reference-v2/api-reference/api-key/api-key--list.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/api_keys/list +openapi: get /v2/api-keys/list --- diff --git a/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx b/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx index ee7970122d4..72864363357 100644 --- a/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx +++ b/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/api_keys/{id} +openapi: get /v2/api-keys/{id} --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/api-key/api-key--revoke.mdx b/api-reference-v2/api-reference/api-key/api-key--revoke.mdx index 9362743088b..b7ffd42e449 100644 --- a/api-reference-v2/api-reference/api-key/api-key--revoke.mdx +++ b/api-reference-v2/api-reference/api-key/api-key--revoke.mdx @@ -1,3 +1,3 @@ --- -openapi: delete /v2/api_keys/{id} +openapi: delete /v2/api-keys/{id} --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/api-key/api-key--update.mdx b/api-reference-v2/api-reference/api-key/api-key--update.mdx index c682cf1ee9e..2434e4981fc 100644 --- a/api-reference-v2/api-reference/api-key/api-key--update.mdx +++ b/api-reference-v2/api-reference/api-key/api-key--update.mdx @@ -1,3 +1,3 @@ --- -openapi: put /v2/api_keys/{id} +openapi: put /v2/api-keys/{id} --- diff --git a/api-reference-v2/api-reference/business-profile/merchant-connector--list.mdx b/api-reference-v2/api-reference/business-profile/merchant-connector--list.mdx index 6560f45e5fa..93c5a980c27 100644 --- a/api-reference-v2/api-reference/business-profile/merchant-connector--list.mdx +++ b/api-reference-v2/api-reference/business-profile/merchant-connector--list.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/profiles/{profile_id}/connector_accounts +openapi: get /v2/profiles/{profile_id}/connector-accounts --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/connector-account/connector-account--create.mdx b/api-reference-v2/api-reference/connector-account/connector-account--create.mdx index d8cac2bab39..d672d6fa34d 100644 --- a/api-reference-v2/api-reference/connector-account/connector-account--create.mdx +++ b/api-reference-v2/api-reference/connector-account/connector-account--create.mdx @@ -1,3 +1,3 @@ --- -openapi: post /v2/connector_accounts +openapi: post /v2/connector-accounts --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/connector-account/connector-account--delete.mdx b/api-reference-v2/api-reference/connector-account/connector-account--delete.mdx index 5c959648fff..15fdd664412 100644 --- a/api-reference-v2/api-reference/connector-account/connector-account--delete.mdx +++ b/api-reference-v2/api-reference/connector-account/connector-account--delete.mdx @@ -1,3 +1,3 @@ --- -openapi: delete /v2/connector_accounts/{id} +openapi: delete /v2/connector-accounts/{id} --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx b/api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx index 918de031276..dbd26b9b10b 100644 --- a/api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx +++ b/api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/connector_accounts/{id} +openapi: get /v2/connector-accounts/{id} --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/connector-account/connector-account--update.mdx b/api-reference-v2/api-reference/connector-account/connector-account--update.mdx index 6ccd052fb9b..fe864d538f8 100644 --- a/api-reference-v2/api-reference/connector-account/connector-account--update.mdx +++ b/api-reference-v2/api-reference/connector-account/connector-account--update.mdx @@ -1,3 +1,3 @@ --- -openapi: put /v2/connector_accounts/{id} +openapi: put /v2/connector-accounts/{id} --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx b/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx index 97deb0832cc..069bd602ddf 100644 --- a/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx +++ b/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/merchant_accounts/{id}/profiles +openapi: get /v2/merchant-accounts/{id}/profiles --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/merchant-account/merchant-account--create.mdx b/api-reference-v2/api-reference/merchant-account/merchant-account--create.mdx index d870b811aae..38aed603f62 100644 --- a/api-reference-v2/api-reference/merchant-account/merchant-account--create.mdx +++ b/api-reference-v2/api-reference/merchant-account/merchant-account--create.mdx @@ -1,3 +1,3 @@ --- -openapi: post /v2/merchant_accounts +openapi: post /v2/merchant-accounts --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/merchant-account/merchant-account--retrieve.mdx b/api-reference-v2/api-reference/merchant-account/merchant-account--retrieve.mdx index d082565234e..3b744fb1406 100644 --- a/api-reference-v2/api-reference/merchant-account/merchant-account--retrieve.mdx +++ b/api-reference-v2/api-reference/merchant-account/merchant-account--retrieve.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/merchant_accounts/{id} +openapi: get /v2/merchant-accounts/{id} --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/merchant-account/merchant-account--update.mdx b/api-reference-v2/api-reference/merchant-account/merchant-account--update.mdx index 51f80ceea30..eb2e92d0652 100644 --- a/api-reference-v2/api-reference/merchant-account/merchant-account--update.mdx +++ b/api-reference-v2/api-reference/merchant-account/merchant-account--update.mdx @@ -1,3 +1,3 @@ --- -openapi: put /v2/merchant_accounts/{id} +openapi: put /v2/merchant-accounts/{id} --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/merchant-account/profile--list.mdx b/api-reference-v2/api-reference/merchant-account/profile--list.mdx deleted file mode 100644 index e14bc0d6ef3..00000000000 --- a/api-reference-v2/api-reference/merchant-account/profile--list.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: get /v2/merchant_accounts/{account_id}/profiles ---- \ No newline at end of file diff --git a/api-reference-v2/api-reference/organization/organization--merchant-account--list.mdx b/api-reference-v2/api-reference/organization/organization--merchant-account--list.mdx index 58d467dc572..9a03e8713d1 100644 --- a/api-reference-v2/api-reference/organization/organization--merchant-account--list.mdx +++ b/api-reference-v2/api-reference/organization/organization--merchant-account--list.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/organization/{id}/merchant_accounts +openapi: get /v2/organization/{id}/merchant-accounts --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx b/api-reference-v2/api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx new file mode 100644 index 00000000000..7809830b820 --- /dev/null +++ b/api-reference-v2/api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/payments/{id}/saved-payment-methods +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx b/api-reference-v2/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx new file mode 100644 index 00000000000..ef5a27f9604 --- /dev/null +++ b/api-reference-v2/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/customers/{id}/saved-payment-methods +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--confirm-intent.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--confirm-intent.mdx new file mode 100644 index 00000000000..134374a7b6c --- /dev/null +++ b/api-reference-v2/api-reference/payment-methods/payment-method--confirm-intent.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/payment-methods/{id}/confirm-intent +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--create-intent.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--create-intent.mdx new file mode 100644 index 00000000000..42cf716f2ab --- /dev/null +++ b/api-reference-v2/api-reference/payment-methods/payment-method--create-intent.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/payment-methods/create-intent +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--create.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--create.mdx new file mode 100644 index 00000000000..1dce5179a94 --- /dev/null +++ b/api-reference-v2/api-reference/payment-methods/payment-method--create.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/payment-methods +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--delete.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--delete.mdx new file mode 100644 index 00000000000..210bf843f97 --- /dev/null +++ b/api-reference-v2/api-reference/payment-methods/payment-method--delete.mdx @@ -0,0 +1,3 @@ +--- +openapi: delete /v2/payment-methods/{id} +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--retrieve.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--retrieve.mdx new file mode 100644 index 00000000000..957d9760b3f --- /dev/null +++ b/api-reference-v2/api-reference/payment-methods/payment-method--retrieve.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/payment-methods/{id} +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--update.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--update.mdx new file mode 100644 index 00000000000..0adee195a6f --- /dev/null +++ b/api-reference-v2/api-reference/payment-methods/payment-method--update.mdx @@ -0,0 +1,3 @@ +--- +openapi: patch /v2/payment-methods/{id}/update-saved-payment-method +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/merchant-connector--list.mdx b/api-reference-v2/api-reference/profile/merchant-connector--list.mdx index 81f640436f4..55218be7c0b 100644 --- a/api-reference-v2/api-reference/profile/merchant-connector--list.mdx +++ b/api-reference-v2/api-reference/profile/merchant-connector--list.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/profiles/{id}/connector_accounts +openapi: get /v2/profiles/{id}/connector-accounts --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx index 7225f422e5a..ea9ee7596a0 100644 --- a/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx +++ b/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx @@ -1,3 +1,3 @@ --- -openapi: patch /v2/profiles/{id}/activate_routing_algorithm +openapi: patch /v2/profiles/{id}/activate-routing-algorithm --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx index 87aac8b9379..4d6b2d620c6 100644 --- a/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx +++ b/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx @@ -1,3 +1,3 @@ --- -openapi: patch /v2/profiles/{id}/deactivate_routing_algorithm +openapi: patch /v2/profiles/{id}/deactivate-routing-algorithm --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx index 86d2d35d57c..143837676c2 100644 --- a/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx +++ b/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/profiles/{id}/routing_algorithm +openapi: get /v2/profiles/{id}/routing-algorithm --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx index 1bc383c278f..ebaad7c53ae 100644 --- a/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx +++ b/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/profiles/{id}/fallback_routing +openapi: get /v2/profiles/{id}/fallback-routing --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx index 76f4d4fa77f..b5df6a57ef8 100644 --- a/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx +++ b/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx @@ -1,3 +1,3 @@ --- -openapi: patch /v2/profiles/{id}/fallback_routing +openapi: patch /v2/profiles/{id}/fallback-routing --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/routing/routing--create.mdx b/api-reference-v2/api-reference/routing/routing--create.mdx index 65ef15008f2..438abd8e231 100644 --- a/api-reference-v2/api-reference/routing/routing--create.mdx +++ b/api-reference-v2/api-reference/routing/routing--create.mdx @@ -1,3 +1,3 @@ --- -openapi: post /v2/routing_algorithm +openapi: post /v2/routing-algorithm --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/routing/routing--retrieve.mdx b/api-reference-v2/api-reference/routing/routing--retrieve.mdx index 776ff69e004..10db0200e18 100644 --- a/api-reference-v2/api-reference/routing/routing--retrieve.mdx +++ b/api-reference-v2/api-reference/routing/routing--retrieve.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/routing_algorithm/{id} +openapi: get /v2/routing-algorithm/{id} --- \ No newline at end of file diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json index c0723a63f3a..aed89492443 100644 --- a/api-reference-v2/mint.json +++ b/api-reference-v2/mint.json @@ -23,7 +23,9 @@ "navigation": [ { "group": "Get Started", - "pages": ["introduction"] + "pages": [ + "introduction" + ] }, { "group": "Essentials", @@ -43,6 +45,19 @@ "api-reference/payments/payments--get" ] }, + { + "group": "Payment Methods", + "pages": [ + "api-reference/payment-methods/payment-method--create", + "api-reference/payment-methods/payment-method--retrieve", + "api-reference/payment-methods/payment-method--update", + "api-reference/payment-methods/payment-method--delete", + "api-reference/payment-methods/payment-method--create-intent", + "api-reference/payment-methods/payment-method--confirm-intent", + "api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment", + "api-reference/payment-methods/list-payment-methods-for-a-customer" + ] + }, { "group": "Organization", "pages": [ @@ -119,8 +134,10 @@ "github": "https://github.com/juspay/hyperswitch", "linkedin": "https://www.linkedin.com/company/hyperswitch" }, - "openapi": ["openapi_spec.json"], + "openapi": [ + "openapi_spec.json" + ], "api": { "maintainOrder": true } -} +} \ No newline at end of file diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 1494908c5fc..88ad74a7560 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -164,7 +164,7 @@ ] } }, - "/v2/organization/{id}/merchant_accounts": { + "/v2/organization/{id}/merchant-accounts": { "get": { "tags": [ "Organization" @@ -208,7 +208,7 @@ ] } }, - "/v2/connector_accounts": { + "/v2/connector-accounts": { "post": { "tags": [ "Merchant Connector Account" @@ -285,7 +285,7 @@ ] } }, - "/v2/connector_accounts/{id}": { + "/v2/connector-accounts/{id}": { "get": { "tags": [ "Merchant Connector Account" @@ -445,7 +445,7 @@ ] } }, - "/v2/merchant_accounts": { + "/v2/merchant-accounts": { "post": { "tags": [ "Merchant Account" @@ -524,7 +524,7 @@ ] } }, - "/v2/merchant_accounts/{id}": { + "/v2/merchant-accounts/{id}": { "get": { "tags": [ "Merchant Account" @@ -630,7 +630,7 @@ ] } }, - "/v2/merchant_accounts/{id}/profiles": { + "/v2/merchant-accounts/{id}/profiles": { "get": { "tags": [ "Merchant Account" @@ -907,7 +907,7 @@ ] } }, - "/v2/profiles/{id}/connector_accounts": { + "/v2/profiles/{id}/connector-accounts": { "get": { "tags": [ "Business Profile" @@ -966,7 +966,7 @@ ] } }, - "/v2/profiles/{id}/activate_routing_algorithm": { + "/v2/profiles/{id}/activate-routing-algorithm": { "patch": { "tags": [ "Profile" @@ -1033,7 +1033,7 @@ ] } }, - "/v2/profiles/{id}/deactivate_routing_algorithm": { + "/v2/profiles/{id}/deactivate-routing-algorithm": { "patch": { "tags": [ "Profile" @@ -1086,7 +1086,7 @@ ] } }, - "/v2/profiles/{id}/fallback_routing": { + "/v2/profiles/{id}/fallback-routing": { "patch": { "tags": [ "Profile" @@ -1197,13 +1197,13 @@ ] } }, - "/v2/profiles/{id}/routing_algorithm": { + "/v2/profiles/{id}/routing-algorithm": { "get": { "tags": [ "Profile" ], "summary": "Profile - Retrieve Active Routing Algorithm", - "description": "Retrieve active routing algorithm under the profile", + "description": "_\nRetrieve active routing algorithm under the profile", "operationId": "Retrieve the active routing algorithm under the profile", "parameters": [ { @@ -1271,7 +1271,7 @@ ] } }, - "/v2/routing_algorithm": { + "/v2/routing-algorithm": { "post": { "tags": [ "Routing" @@ -1326,7 +1326,7 @@ ] } }, - "/v2/routing_algorithm/{id}": { + "/v2/routing-algorithm/{id}": { "get": { "tags": [ "Routing" @@ -1376,7 +1376,7 @@ ] } }, - "/v2/api_keys": { + "/v2/api-keys": { "post": { "tags": [ "API Key" @@ -1416,7 +1416,7 @@ ] } }, - "/v2/api_keys/{id}": { + "/v2/api-keys/{id}": { "get": { "tags": [ "API Key" @@ -1545,7 +1545,7 @@ ] } }, - "/v2/api_keys/list": { + "/v2/api-keys/list": { "get": { "tags": [ "API Key" @@ -2017,6 +2017,332 @@ ] } }, + "/v2/payments/{id}/saved-payment-methods": { + "get": { + "tags": [ + "Payment Methods" + ], + "summary": "List customer saved payment methods for a payment", + "description": "To filter and list the applicable payment methods for a particular Customer ID, is to be associated with a payment", + "operationId": "List all Payment Methods for a Customer", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodListRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomerPaymentMethodsListResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + }, + "404": { + "description": "Payment Methods does not exist in records" + } + }, + "security": [ + { + "publishable_key": [] + } + ] + } + }, + "/v2/customers/{id}/saved-payment-methods": { + "get": { + "tags": [ + "Payment Methods" + ], + "summary": "List saved payment methods for a Customer", + "description": "To filter and list the applicable payment methods for a particular Customer ID, to be used in a non-payments context", + "operationId": "List all Payment Methods for a Customer", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodListRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Payment Methods retrieved", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomerPaymentMethodsListResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + }, + "404": { + "description": "Payment Methods does not exist in records" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/v2/payment-methods": { + "post": { + "tags": [ + "Payment Methods" + ], + "summary": "Payment Method - Create", + "description": "Creates and stores a payment method against a customer. In case of cards, this API should be used only by PCI compliant merchants.", + "operationId": "Create Payment Method", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodCreate" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Payment Method Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/v2/payment-methods/create-intent": { + "post": { + "tags": [ + "Payment Methods" + ], + "summary": "Payment Method - Create Intent", + "description": "Creates a payment method for customer with billing information and other metadata.", + "operationId": "Create Payment Method Intent", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodIntentCreate" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Payment Method Intent Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/v2/payment-methods/{id}/confirm-intent": { + "post": { + "tags": [ + "Payment Methods" + ], + "summary": "Payment Method - Confirm Intent", + "description": "Update a payment method with customer's payment method related information.", + "operationId": "Confirm Payment Method Intent", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodIntentConfirm" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Payment Method Intent Confirmed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/v2/payment-methods/{id}/update-saved-payment-method": { + "patch": { + "tags": [ + "Payment Methods" + ], + "summary": "Payment Method - Update", + "description": "Update an existing payment method of a customer.", + "operationId": "Update Payment Method", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodUpdate" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Payment Method Update", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/v2/payment-methods/{id}": { + "get": { + "tags": [ + "Payment Methods" + ], + "summary": "Payment Method - Retrieve", + "description": "Retrieves a payment method of a customer.", + "operationId": "Retrieve Payment Method", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The unique identifier for the Payment Method", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Payment Method Retrieved", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodResponse" + } + } + } + }, + "404": { + "description": "Payment Method Not Found" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "delete": { + "tags": [ + "Payment Methods" + ], + "summary": "Payment Method - Delete", + "description": "Deletes a payment method of a customer.", + "operationId": "Delete Payment Method", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The unique identifier for the Payment Method", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Payment Method Retrieved", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodDeleteResponse" + } + } + } + }, + "404": { + "description": "Payment Method Not Found" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/v2/refunds": { "post": { "tags": [ @@ -11255,14 +11581,17 @@ ], "properties": { "organization_name": { - "type": "string" + "type": "string", + "description": "Name of the organization" }, "organization_details": { "type": "object", + "description": "Details about the organization", "nullable": true }, "metadata": { "type": "object", + "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true } }, @@ -11271,27 +11600,31 @@ "OrganizationResponse": { "type": "object", "required": [ - "organization_id", + "id", "modified_at", "created_at" ], "properties": { - "organization_id": { + "id": { "type": "string", + "description": "The unique identifier for the Organization", "example": "org_q98uSGAYbjEwqs0mJwnz", "maxLength": 64, "minLength": 1 }, "organization_name": { "type": "string", + "description": "Name of the Organization", "nullable": true }, "organization_details": { "type": "object", + "description": "Details about the organization", "nullable": true }, "metadata": { "type": "object", + "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true }, "modified_at": { @@ -11309,14 +11642,17 @@ "properties": { "organization_name": { "type": "string", + "description": "Name of the organization", "nullable": true }, "organization_details": { "type": "object", + "description": "Details about the organization", "nullable": true }, "metadata": { "type": "object", + "description": "Metadata is useful for storing additional, unstructured information on an object.", "nullable": true } }, @@ -12906,6 +13242,68 @@ } } }, + "PaymentMethodIntentConfirm": { + "type": "object", + "required": [ + "client_secret", + "payment_method_data", + "payment_method_type", + "payment_method_subtype" + ], + "properties": { + "client_secret": { + "type": "string", + "description": "For SDK based calls, client_secret would be required" + }, + "customer_id": { + "type": "string", + "description": "The unique identifier of the customer.", + "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", + "nullable": true, + "maxLength": 64, + "minLength": 1 + }, + "payment_method_data": { + "$ref": "#/components/schemas/PaymentMethodCreateData" + }, + "payment_method_type": { + "$ref": "#/components/schemas/PaymentMethod" + }, + "payment_method_subtype": { + "$ref": "#/components/schemas/PaymentMethodType" + } + }, + "additionalProperties": false + }, + "PaymentMethodIntentCreate": { + "type": "object", + "required": [ + "customer_id" + ], + "properties": { + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "nullable": true + }, + "billing": { + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], + "nullable": true + }, + "customer_id": { + "type": "string", + "description": "The unique identifier of the customer.", + "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", + "maxLength": 64, + "minLength": 1 + } + }, + "additionalProperties": false + }, "PaymentMethodIssuerCode": { "type": "string", "enum": [ @@ -12947,6 +13345,78 @@ } ] }, + "PaymentMethodListRequest": { + "type": "object", + "properties": { + "client_secret": { + "type": "string", + "description": "This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK", + "example": "secret_k2uj3he2893eiu2d", + "nullable": true, + "maxLength": 30, + "minLength": 30 + }, + "accepted_countries": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CountryAlpha2" + }, + "description": "The two-letter ISO currency code", + "example": [ + "US", + "UK", + "IN" + ], + "nullable": true + }, + "amount": { + "allOf": [ + { + "$ref": "#/components/schemas/MinorUnit" + } + ], + "nullable": true + }, + "accepted_currencies": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Currency" + }, + "description": "The three-letter ISO currency code", + "example": [ + "USD", + "EUR" + ], + "nullable": true + }, + "recurring_enabled": { + "type": "boolean", + "description": "Indicates whether the payment method is eligible for recurring payments", + "example": true, + "nullable": true + }, + "card_networks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CardNetwork" + }, + "description": "Indicates whether the payment method is eligible for card netwotks", + "example": [ + "visa", + "mastercard" + ], + "nullable": true + }, + "limit": { + "type": "integer", + "format": "int64", + "description": "Indicates the limit of last used payment methods", + "example": 1, + "nullable": true + } + }, + "additionalProperties": false + }, "PaymentMethodListResponse": { "type": "object", "required": [ diff --git a/crates/api_models/src/organization.rs b/crates/api_models/src/organization.rs index f95a1595116..c6bc3924d11 100644 --- a/crates/api_models/src/organization.rs +++ b/crates/api_models/src/organization.rs @@ -22,9 +22,14 @@ pub struct OrganizationId { #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OrganizationCreateRequest { + /// Name of the organization pub organization_name: String, + + /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, + + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, } @@ -32,20 +37,53 @@ pub struct OrganizationCreateRequest { #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OrganizationUpdateRequest { + /// Name of the organization pub organization_name: Option<String>, + + /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, + + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, } - +#[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct OrganizationResponse { + /// The unique identifier for the Organization #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: id_type::OrganizationId, + + /// Name of the Organization pub organization_name: Option<String>, + + /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, + + /// Metadata is useful for storing additional, unstructured information on an object. + #[schema(value_type = Option<Object>)] + pub metadata: Option<pii::SecretSerdeValue>, + pub modified_at: time::PrimitiveDateTime, + pub created_at: time::PrimitiveDateTime, +} + +#[cfg(feature = "v2")] +#[derive(Debug, serde::Serialize, Clone, ToSchema)] +pub struct OrganizationResponse { + /// The unique identifier for the Organization + #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] + pub id: id_type::OrganizationId, + + /// Name of the Organization + pub organization_name: Option<String>, + + /// Details about the organization + #[schema(value_type = Option<Object>)] + pub organization_details: Option<pii::SecretSerdeValue>, + + /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: time::PrimitiveDateTime, diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 0bb5e65213f..2c2aa4861c5 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -778,7 +778,7 @@ pub struct PaymentMethodResponse { #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema, Clone)] pub struct PaymentMethodResponse { /// Unique identifier for a merchant - #[schema(example = "merchant_1671528864", value_type = String)] + #[schema(value_type = String, example = "merchant_1671528864")] pub merchant_id: id_type::MerchantId, /// The unique identifier of the customer. diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 4cb93403219..6468345b14a 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -123,7 +123,7 @@ impl PaymentIntent { publishable_key: String, ) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> { let start_redirection_url = &format!( - "{}/v2/payments/{}/start_redirection?publishable_key={}&profile_id={}", + "{}/v2/payments/{}/start-redirection?publishable_key={}&profile_id={}", base_url, self.get_id().get_string_repr(), publishable_key, @@ -142,7 +142,7 @@ impl PaymentIntent { publishable_key: &str, ) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> { let finish_redirection_url = format!( - "{base_url}/v2/payments/{}/finish_redirection/{publishable_key}/{}", + "{base_url}/v2/payments/{}/finish-redirection/{publishable_key}/{}", self.id.get_string_repr(), self.profile_id.get_string_repr() ); diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 4198e90882e..a756d9fb1b1 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -127,6 +127,17 @@ Never share your secret api keys. Keep them guarded and secure. routes::payments::payments_confirm_intent, routes::payments::payment_status, + //Routes for payment methods + routes::payment_method::list_customer_payment_method_for_payment, + routes::payment_method::list_customer_payment_method_api, + routes::payment_method::create_payment_method_api, + routes::payment_method::create_payment_method_intent_api, + routes::payment_method::confirm_payment_method_intent_api, + routes::payment_method::payment_method_update_api, + routes::payment_method::payment_method_retrieve_api, + routes::payment_method::payment_method_delete_api, + + //Routes for refunds routes::refunds::refunds_create, ), @@ -170,9 +181,12 @@ Never share your secret api keys. Keep them guarded and secure. api_models::customers::CustomerRequest, api_models::customers::CustomerDeleteResponse, api_models::payment_methods::PaymentMethodCreate, + api_models::payment_methods::PaymentMethodIntentCreate, + api_models::payment_methods::PaymentMethodIntentConfirm, api_models::payment_methods::PaymentMethodResponse, api_models::payment_methods::PaymentMethodResponseData, api_models::payment_methods::CustomerPaymentMethod, + api_models::payment_methods::PaymentMethodListRequest, api_models::payment_methods::PaymentMethodListResponse, api_models::payment_methods::ResponsePaymentMethodsEnabled, api_models::payment_methods::ResponsePaymentMethodTypes, @@ -189,6 +203,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodCreateData, api_models::payment_methods::CardDetail, api_models::payment_methods::CardDetailUpdate, + api_models::payment_methods::CardType, api_models::payment_methods::RequestPaymentMethodTypes, api_models::payment_methods::CardType, api_models::payment_methods::PaymentMethodListData, diff --git a/crates/openapi/src/routes/api_keys.rs b/crates/openapi/src/routes/api_keys.rs index cfc4c09ce46..964fa60fcf5 100644 --- a/crates/openapi/src/routes/api_keys.rs +++ b/crates/openapi/src/routes/api_keys.rs @@ -25,7 +25,7 @@ pub async fn api_key_create() {} /// displayed only once on creation, so ensure you store it securely. #[utoipa::path( post, - path = "/v2/api_keys", + path = "/v2/api-keys", request_body= CreateApiKeyRequest, responses( (status = 200, description = "API Key created", body = CreateApiKeyResponse), @@ -64,7 +64,7 @@ pub async fn api_key_retrieve() {} /// Retrieve information about the specified API Key. #[utoipa::path( get, - path = "/v2/api_keys/{id}", + path = "/v2/api-keys/{id}", params ( ("id" = String, Path, description = "The unique identifier for the API Key") ), @@ -106,7 +106,7 @@ pub async fn api_key_update() {} /// Update information for the specified API Key. #[utoipa::path( put, - path = "/v2/api_keys/{id}", + path = "/v2/api-keys/{id}", request_body = UpdateApiKeyRequest, params ( ("id" = String, Path, description = "The unique identifier for the API Key") @@ -150,7 +150,7 @@ pub async fn api_key_revoke() {} /// authenticating with our APIs. #[utoipa::path( delete, - path = "/v2/api_keys/{id}", + path = "/v2/api-keys/{id}", params ( ("id" = String, Path, description = "The unique identifier for the API Key") ), @@ -191,7 +191,7 @@ pub async fn api_key_list() {} /// List all the API Keys associated to a merchant account. #[utoipa::path( get, - path = "/v2/api_keys/list", + path = "/v2/api-keys/list", params( ("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"), ("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."), diff --git a/crates/openapi/src/routes/merchant_account.rs b/crates/openapi/src/routes/merchant_account.rs index 022a5e6c006..a3bf96ab897 100644 --- a/crates/openapi/src/routes/merchant_account.rs +++ b/crates/openapi/src/routes/merchant_account.rs @@ -50,7 +50,7 @@ pub async fn merchant_account_create() {} /// Before creating the merchant account, it is mandatory to create an organization. #[utoipa::path( post, - path = "/v2/merchant_accounts", + path = "/v2/merchant-accounts", params( ( "X-Organization-Id" = String, Header, @@ -128,7 +128,7 @@ pub async fn retrieve_merchant_account() {} /// Retrieve a *merchant* account details. #[utoipa::path( get, - path = "/v2/merchant_accounts/{id}", + path = "/v2/merchant-accounts/{id}", params (("id" = String, Path, description = "The unique identifier for the merchant account")), responses( (status = 200, description = "Merchant Account Retrieved", body = MerchantAccountResponse), @@ -190,7 +190,7 @@ pub async fn update_merchant_account() {} /// Updates details of an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc #[utoipa::path( put, - path = "/v2/merchant_accounts/{id}", + path = "/v2/merchant-accounts/{id}", request_body ( content = MerchantAccountUpdate, examples( @@ -300,7 +300,7 @@ pub async fn payment_connector_list_profile() {} /// List profiles for an Merchant #[utoipa::path( get, - path = "/v2/merchant_accounts/{id}/profiles", + path = "/v2/merchant-accounts/{id}/profiles", params (("id" = String, Path, description = "The unique identifier for the Merchant")), responses( (status = 200, description = "profile list retrieved successfully", body = Vec<ProfileResponse>), diff --git a/crates/openapi/src/routes/merchant_connector_account.rs b/crates/openapi/src/routes/merchant_connector_account.rs index 29092b5bba0..372f8688a26 100644 --- a/crates/openapi/src/routes/merchant_connector_account.rs +++ b/crates/openapi/src/routes/merchant_connector_account.rs @@ -67,7 +67,7 @@ pub async fn connector_create() {} #[cfg(feature = "v2")] #[utoipa::path( post, - path = "/v2/connector_accounts", + path = "/v2/connector-accounts", request_body( content = MerchantConnectorCreate, examples( @@ -152,7 +152,7 @@ pub async fn connector_retrieve() {} #[cfg(feature = "v2")] #[utoipa::path( get, - path = "/v2/connector_accounts/{id}", + path = "/v2/connector-accounts/{id}", params( ("id" = i32, Path, description = "The unique identifier for the Merchant Connector") ), @@ -241,7 +241,7 @@ pub async fn connector_update() {} #[cfg(feature = "v2")] #[utoipa::path( put, - path = "/v2/connector_accounts/{id}", + path = "/v2/connector-accounts/{id}", request_body( content = MerchantConnectorUpdate, examples( @@ -310,7 +310,7 @@ pub async fn connector_delete() {} #[cfg(feature = "v2")] #[utoipa::path( delete, - path = "/v2/connector_accounts/{id}", + path = "/v2/connector-accounts/{id}", params( ("id" = i32, Path, description = "The unique identifier for the Merchant Connector") ), diff --git a/crates/openapi/src/routes/organization.rs b/crates/openapi/src/routes/organization.rs index ce3199343cf..d677131d5db 100644 --- a/crates/openapi/src/routes/organization.rs +++ b/crates/openapi/src/routes/organization.rs @@ -150,7 +150,7 @@ pub async fn organization_update() {} /// List merchant accounts for an Organization #[utoipa::path( get, - path = "/v2/organization/{id}/merchant_accounts", + path = "/v2/organization/{id}/merchant-accounts", params (("id" = String, Path, description = "The unique identifier for the Organization")), responses( (status = 200, description = "Merchant Account list retrieved successfully", body = Vec<MerchantAccountResponse>), diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs index 3bc593aa5b2..b38a2342678 100644 --- a/crates/openapi/src/routes/payment_method.rs +++ b/crates/openapi/src/routes/payment_method.rs @@ -31,6 +31,7 @@ operation_id = "Create a Payment Method", security(("api_key" = [])) )] +#[cfg(feature = "v1")] pub async fn create_payment_method_api() {} /// List payment methods for a Merchant @@ -84,6 +85,7 @@ pub async fn list_payment_method_api() {} operation_id = "List all Payment Methods for a Customer", security(("api_key" = [])) )] +#[cfg(feature = "v1")] pub async fn list_customer_payment_method_api() {} /// List customer saved payment methods for a Payment @@ -130,6 +132,7 @@ pub async fn list_customer_payment_method_api_client() {} operation_id = "Retrieve a Payment method", security(("api_key" = [])) )] +#[cfg(feature = "v1")] pub async fn payment_method_retrieve_api() {} /// Payment Method - Update @@ -151,6 +154,7 @@ pub async fn payment_method_retrieve_api() {} operation_id = "Update a Payment method", security(("api_key" = []), ("publishable_key" = [])) )] +#[cfg(feature = "v1")] pub async fn payment_method_update_api() {} /// Payment Method - Delete @@ -170,6 +174,7 @@ pub async fn payment_method_update_api() {} operation_id = "Delete a Payment method", security(("api_key" = [])) )] +#[cfg(feature = "v1")] pub async fn payment_method_delete_api() {} /// Payment Method - Set Default Payment Method for Customer @@ -192,3 +197,171 @@ pub async fn payment_method_delete_api() {} security(("ephemeral_key" = [])) )] pub async fn default_payment_method_set_api() {} + +/// Payment Method - Create Intent +/// +/// Creates a payment method for customer with billing information and other metadata. +#[utoipa::path( + post, + path = "/v2/payment-methods/create-intent", + request_body( + content = PaymentMethodIntentCreate, + // TODO: Add examples + ), + responses( + (status = 200, description = "Payment Method Intent Created", body = PaymentMethodResponse), + (status = 400, description = "Invalid Data"), + ), + tag = "Payment Methods", + operation_id = "Create Payment Method Intent", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn create_payment_method_intent_api() {} + +/// Payment Method - Confirm Intent +/// +/// Update a payment method with customer's payment method related information. +#[utoipa::path( + post, + path = "/v2/payment-methods/{id}/confirm-intent", + request_body( + content = PaymentMethodIntentConfirm, + // TODO: Add examples + ), + responses( + (status = 200, description = "Payment Method Intent Confirmed", body = PaymentMethodResponse), + (status = 400, description = "Invalid Data"), + ), + tag = "Payment Methods", + operation_id = "Confirm Payment Method Intent", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn confirm_payment_method_intent_api() {} + +/// Payment Method - Create +/// +/// Creates and stores a payment method against a customer. In case of cards, this API should be used only by PCI compliant merchants. +#[utoipa::path( + post, + path = "/v2/payment-methods", + request_body( + content = PaymentMethodCreate, + // TODO: Add examples + ), + responses( + (status = 200, description = "Payment Method Created", body = PaymentMethodResponse), + (status = 400, description = "Invalid Data"), + ), + tag = "Payment Methods", + operation_id = "Create Payment Method", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn create_payment_method_api() {} + +/// Payment Method - Retrieve +/// +/// Retrieves a payment method of a customer. +#[utoipa::path( + get, + path = "/v2/payment-methods/{id}", + params ( + ("id" = String, Path, description = "The unique identifier for the Payment Method"), + ), + responses( + (status = 200, description = "Payment Method Retrieved", body = PaymentMethodResponse), + (status = 404, description = "Payment Method Not Found"), + ), + tag = "Payment Methods", + operation_id = "Retrieve Payment Method", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn payment_method_retrieve_api() {} + +/// Payment Method - Update +/// +/// Update an existing payment method of a customer. +#[utoipa::path( + patch, + path = "/v2/payment-methods/{id}/update-saved-payment-method", + request_body( + content = PaymentMethodUpdate, + // TODO: Add examples + ), + responses( + (status = 200, description = "Payment Method Update", body = PaymentMethodResponse), + (status = 400, description = "Invalid Data"), + ), + tag = "Payment Methods", + operation_id = "Update Payment Method", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn payment_method_update_api() {} + +/// Payment Method - Delete +/// +/// Deletes a payment method of a customer. +#[utoipa::path( + delete, + path = "/v2/payment-methods/{id}", + params ( + ("id" = String, Path, description = "The unique identifier for the Payment Method"), + ), + responses( + (status = 200, description = "Payment Method Retrieved", body = PaymentMethodDeleteResponse), + (status = 404, description = "Payment Method Not Found"), + ), + tag = "Payment Methods", + operation_id = "Delete Payment Method", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn payment_method_delete_api() {} + +/// List customer saved payment methods for a payment +/// +/// To filter and list the applicable payment methods for a particular Customer ID, is to be associated with a payment +#[utoipa::path( + get, + path = "/v2/payments/{id}/saved-payment-methods", + request_body( + content = PaymentMethodListRequest, + // TODO: Add examples and add param for customer_id + ), + responses( + (status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse), + (status = 400, description = "Invalid Data"), + (status = 404, description = "Payment Methods does not exist in records") + ), + tag = "Payment Methods", + operation_id = "List all Payment Methods for a Customer", + security(("publishable_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn list_customer_payment_method_for_payment() {} + +/// List saved payment methods for a Customer +/// +/// To filter and list the applicable payment methods for a particular Customer ID, to be used in a non-payments context +#[utoipa::path( + get, + path = "/v2/customers/{id}/saved-payment-methods", + request_body( + content = PaymentMethodListRequest, + // TODO: Add examples and add param for customer_id + ), + responses( + (status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse), + (status = 400, description = "Invalid Data"), + (status = 404, description = "Payment Methods does not exist in records") + ), + tag = "Payment Methods", + operation_id = "List all Payment Methods for a Customer", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn list_customer_payment_method_api() {} diff --git a/crates/openapi/src/routes/profile.rs b/crates/openapi/src/routes/profile.rs index d88568653a4..cc484aa3f95 100644 --- a/crates/openapi/src/routes/profile.rs +++ b/crates/openapi/src/routes/profile.rs @@ -210,7 +210,7 @@ pub async fn profile_update() {} /// Activates a routing algorithm under a profile #[utoipa::path( patch, - path = "/v2/profiles/{id}/activate_routing_algorithm", + path = "/v2/profiles/{id}/activate-routing-algorithm", request_body ( content = RoutingAlgorithmId, examples( ( "Activate a routing algorithm" = ( @@ -240,7 +240,7 @@ pub async fn routing_link_config() {} /// Deactivates a routing algorithm under a profile #[utoipa::path( patch, - path = "/v2/profiles/{id}/deactivate_routing_algorithm", + path = "/v2/profiles/{id}/deactivate-routing-algorithm", params( ("id" = String, Path, description = "The unique identifier for the profile"), ), @@ -263,7 +263,7 @@ pub async fn routing_unlink_config() {} /// Update the default fallback routing algorithm for the profile #[utoipa::path( patch, - path = "/v2/profiles/{id}/fallback_routing", + path = "/v2/profiles/{id}/fallback-routing", request_body = Vec<RoutableConnectorChoice>, params( ("id" = String, Path, description = "The unique identifier for the profile"), @@ -307,11 +307,11 @@ pub async fn profile_retrieve() {} #[cfg(feature = "v2")] /// Profile - Retrieve Active Routing Algorithm -/// +///_ /// Retrieve active routing algorithm under the profile #[utoipa::path( get, - path = "/v2/profiles/{id}/routing_algorithm", + path = "/v2/profiles/{id}/routing-algorithm", params( ("id" = String, Path, description = "The unique identifier for the profile"), ("limit" = Option<u16>, Query, description = "The number of records of the algorithms to be returned"), @@ -334,7 +334,7 @@ pub async fn routing_retrieve_linked_config() {} /// Retrieve the default fallback routing algorithm for the profile #[utoipa::path( get, - path = "/v2/profiles/{id}/fallback_routing", + path = "/v2/profiles/{id}/fallback-routing", params( ("id" = String, Path, description = "The unique identifier for the profile"), ), @@ -353,7 +353,7 @@ pub async fn routing_retrieve_default_config() {} /// List Connector Accounts for the profile #[utoipa::path( get, - path = "/v2/profiles/{id}/connector_accounts", + path = "/v2/profiles/{id}/connector-accounts", params( ("id" = String, Path, description = "The unique identifier for the business profile"), ( diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs index 67a22c2ca64..b144fd046ad 100644 --- a/crates/openapi/src/routes/routing.rs +++ b/crates/openapi/src/routes/routing.rs @@ -26,7 +26,7 @@ pub async fn routing_create_config() {} /// Create a routing algorithm #[utoipa::path( post, - path = "/v2/routing_algorithm", + path = "/v2/routing-algorithm", request_body = RoutingConfigRequest, responses( (status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord), @@ -94,7 +94,7 @@ pub async fn routing_retrieve_config() {} #[utoipa::path( get, - path = "/v2/routing_algorithm/{id}", + path = "/v2/routing-algorithm/{id}", params( ("id" = String, Path, description = "The unique identifier for a routing algorithm"), ), diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 1584cfae2b9..96741824254 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -556,11 +556,15 @@ impl Payments { ) .service(web::resource("").route(web::get().to(payments::payment_status))) .service( - web::resource("/start_redirection") + web::resource("/start-redirection") .route(web::get().to(payments::payments_start_redirection)), ) .service( - web::resource("/finish_redirection/{publishable_key}/{profile_id}") + web::resource("/saved-payment-methods") + .route(web::get().to(list_customer_payment_method_for_payment)), + ) + .service( + web::resource("/finish-redirection/{publishable_key}/{profile_id}") .route(web::get().to(payments::payments_finish_redirection)), ), ); @@ -715,7 +719,7 @@ pub struct Routing; #[cfg(all(feature = "olap", feature = "v2"))] impl Routing { pub fn server(state: AppState) -> Scope { - web::scope("/v2/routing_algorithm") + web::scope("/v2/routing-algorithm") .app_data(web::Data::new(state.clone())) .service( web::resource("").route(web::post().to(|state, req, payload| { @@ -968,7 +972,7 @@ impl Customers { #[cfg(all(feature = "oltp", feature = "v2", feature = "payment_methods_v2"))] { route = route.service( - web::resource("/{customer_id}/saved_payment_methods") + web::resource("/{customer_id}/saved-payment-methods") .route(web::get().to(list_customer_payment_method_api)), ); } @@ -1113,7 +1117,7 @@ impl Payouts { #[cfg(all(feature = "oltp", feature = "v2", feature = "payment_methods_v2",))] impl PaymentMethods { pub fn server(state: AppState) -> Scope { - let mut route = web::scope("/v2/payment_methods").app_data(web::Data::new(state)); + let mut route = web::scope("/v2/payment-methods").app_data(web::Data::new(state)); route = route .service(web::resource("").route(web::post().to(create_payment_method_api))) .service( @@ -1125,7 +1129,7 @@ impl PaymentMethods { .route(web::post().to(confirm_payment_method_intent_api)), ) .service( - web::resource("/{id}/update_saved_payment_method") + web::resource("/{id}/update-saved-payment-method") .route(web::patch().to(payment_method_update_api)), ) .service(web::resource("/{id}").route(web::get().to(payment_method_retrieve_api))) @@ -1267,7 +1271,7 @@ impl Organization { .route(web::put().to(admin::organization_update)), ) .service( - web::resource("/merchant_accounts") + web::resource("/merchant-accounts") .route(web::get().to(admin::merchant_account_list)), ), ) @@ -1279,7 +1283,7 @@ pub struct MerchantAccount; #[cfg(all(feature = "v2", feature = "olap"))] impl MerchantAccount { pub fn server(state: AppState) -> Scope { - web::scope("/v2/merchant_accounts") + web::scope("/v2/merchant-accounts") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(admin::merchant_account_create))) .service( @@ -1329,7 +1333,7 @@ pub struct MerchantConnectorAccount; #[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v2"))] impl MerchantConnectorAccount { pub fn server(state: AppState) -> Scope { - let mut route = web::scope("/v2/connector_accounts").app_data(web::Data::new(state)); + let mut route = web::scope("/v2/connector-accounts").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { @@ -1526,7 +1530,7 @@ pub struct ApiKeys; #[cfg(all(feature = "olap", feature = "v2"))] impl ApiKeys { pub fn server(state: AppState) -> Scope { - web::scope("/v2/api_keys") + web::scope("/v2/api-keys") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(api_keys::api_key_create))) .service(web::resource("/list").route(web::get().to(api_keys::api_key_list))) @@ -1692,16 +1696,16 @@ impl Profile { .route(web::put().to(profiles::profile_update)), ) .service( - web::resource("/connector_accounts") + web::resource("/connector-accounts") .route(web::get().to(admin::connector_list)), ) .service( - web::resource("/fallback_routing") + web::resource("/fallback-routing") .route(web::get().to(routing::routing_retrieve_default_config)) .route(web::patch().to(routing::routing_update_default_config)), ) .service( - web::resource("/activate_routing_algorithm").route(web::patch().to( + web::resource("/activate-routing-algorithm").route(web::patch().to( |state, req, path, payload| { routing::routing_link_config( state, @@ -1714,7 +1718,7 @@ impl Profile { )), ) .service( - web::resource("/deactivate_routing_algorithm").route(web::patch().to( + web::resource("/deactivate-routing-algorithm").route(web::patch().to( |state, req, path| { routing::routing_unlink_config( state, @@ -1725,7 +1729,7 @@ impl Profile { }, )), ) - .service(web::resource("/routing_algorithm").route(web::get().to( + .service(web::resource("/routing-algorithm").route(web::get().to( |state, req, query_params, path| { routing::routing_retrieve_linked_config( state, @@ -2000,7 +2004,7 @@ impl User { ) .service(web::resource("/verify_email").route(web::post().to(user::verify_email))) .service( - web::resource("/v2/verify_email").route(web::post().to(user::verify_email)), + web::resource("/v2/verify-email").route(web::post().to(user::verify_email)), ) .service( web::resource("/verify_email_request") @@ -2054,7 +2058,7 @@ impl User { .route(web::post().to(user_role::accept_invitations_v2)), ) .service( - web::resource("/pre_auth").route( + web::resource("/pre-auth").route( web::post().to(user_role::accept_invitations_pre_auth), ), ), diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 7296a510248..8ee31ecf943 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -508,30 +508,6 @@ pub async fn list_customer_payment_method_api( } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -/// List payment methods for a Customer v2 -/// -/// To filter and list the applicable payment methods for a particular Customer ID, is to be associated with a payment -#[utoipa::path( - get, - path = "v2/payments/{payment_id}/saved_payment_methods", - params ( - ("client-secret" = String, Path, description = "A secret known only to your application and the authorization server"), - ("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"), - ("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"), - ("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."), - ("maximum_amount" = i64, Query, description = "The maximum amount amount accepted for processing by the particular payment method."), - ("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"), - ("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"), - ), - responses( - (status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse), - (status = 400, description = "Invalid Data"), - (status = 404, description = "Payment Methods does not exist in records") - ), - tag = "Payment Methods", - operation_id = "List all Payment Methods for a Customer", - security(("publishable_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] pub async fn list_customer_payment_method_for_payment( state: web::Data<AppState>, @@ -575,29 +551,6 @@ pub async fn list_customer_payment_method_for_payment( feature = "payment_methods_v2", feature = "customer_v2" ))] -/// List payment methods for a Customer v2 -/// -/// To filter and list the applicable payment methods for a particular Customer ID, to be used in a non-payments context -#[utoipa::path( - get, - path = "v2/customers/{customer_id}/saved_payment_methods", - params ( - ("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"), - ("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"), - ("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."), - ("maximum_amount" = i64, Query, description = "The maximum amount amount accepted for processing by the particular payment method."), - ("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"), - ("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"), - ), - responses( - (status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse), - (status = 400, description = "Invalid Data"), - (status = 404, description = "Payment Methods does not exist in records") - ), - tag = "Payment Methods", - operation_id = "List all Payment Methods for a Customer", - security(("api_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] pub async fn list_customer_payment_method_api( state: web::Data<AppState>, diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index c81fc7ceb48..85275a768df 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -34,6 +34,10 @@ use crate::{ impl ForeignFrom<diesel_models::organization::Organization> for OrganizationResponse { fn foreign_from(org: diesel_models::organization::Organization) -> Self { Self { + #[cfg(feature = "v2")] + id: org.get_organization_id(), + + #[cfg(feature = "v1")] organization_id: org.get_organization_id(), organization_name: org.get_organization_name(), organization_details: org.organization_details, diff --git a/cypress-tests-v2/cypress/support/commands.js b/cypress-tests-v2/cypress/support/commands.js index eb4ca3423eb..b6955c542a7 100644 --- a/cypress-tests-v2/cypress/support/commands.js +++ b/cypress-tests-v2/cypress/support/commands.js @@ -64,10 +64,10 @@ Cypress.Commands.add( if (response.status === 200) { expect(response.body) - .to.have.property("organization_id") + .to.have.property("id") .and.to.include("org_") .and.to.be.a("string").and.not.be.empty; - globalState.set("organizationId", response.body.organization_id); + globalState.set("organizationId", response.body.id); cy.task("setGlobalState", globalState.data); expect(response.body).to.have.property("metadata").and.to.equal(null); } else { @@ -99,7 +99,7 @@ Cypress.Commands.add("organizationRetrieveCall", (globalState) => { if (response.status === 200) { expect(response.body) - .to.have.property("organization_id") + .to.have.property("id") .and.to.include("org_") .and.to.be.a("string").and.not.be.empty; expect(response.body.organization_name) @@ -107,7 +107,7 @@ Cypress.Commands.add("organizationRetrieveCall", (globalState) => { .and.to.be.a("string").and.not.be.empty; if (organization_id === undefined || organization_id === null) { - globalState.set("organizationId", response.body.organization_id); + globalState.set("organizationId", response.body.id); cy.task("setGlobalState", globalState.data); } } else { @@ -144,14 +144,14 @@ Cypress.Commands.add( if (response.status === 200) { expect(response.body) - .to.have.property("organization_id") + .to.have.property("id") .and.to.include("org_") .and.to.be.a("string").and.not.be.empty; expect(response.body).to.have.property("metadata").and.to.be.a("object") .and.not.be.empty; if (organization_id === undefined || organization_id === null) { - globalState.set("organizationId", response.body.organization_id); + globalState.set("organizationId", response.body.id); cy.task("setGlobalState", globalState.data); } } else { @@ -174,7 +174,7 @@ Cypress.Commands.add( const key_id_type = "publishable_key"; const key_id = validateEnv(base_url, key_id_type); const organization_id = globalState.get("organizationId"); - const url = `${base_url}/v2/merchant_accounts`; + const url = `${base_url}/v2/merchant-accounts`; const merchant_name = merchantAccountCreateBody.merchant_name .replaceAll(" ", "") @@ -223,7 +223,7 @@ Cypress.Commands.add("merchantAccountRetrieveCall", (globalState) => { const key_id_type = "publishable_key"; const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); - const url = `${base_url}/v2/merchant_accounts/${merchant_id}`; + const url = `${base_url}/v2/merchant-accounts/${merchant_id}`; cy.request({ method: "GET", @@ -265,7 +265,7 @@ Cypress.Commands.add( const key_id_type = "publishable_key"; const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); - const url = `${base_url}/v2/merchant_accounts/${merchant_id}`; + const url = `${base_url}/v2/merchant-accounts/${merchant_id}`; const merchant_name = merchantAccountUpdateBody.merchant_name; @@ -456,7 +456,7 @@ Cypress.Commands.add( const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId"); - const url = `${base_url}/v2/connector_accounts`; + const url = `${base_url}/v2/connector-accounts`; const customHeaders = { "x-merchant-id": merchant_id, @@ -536,7 +536,7 @@ Cypress.Commands.add("mcaRetrieveCall", (globalState) => { const connector_name = globalState.get("connectorId"); const merchant_connector_id = globalState.get("merchantConnectorId"); const merchant_id = globalState.get("merchantId"); - const url = `${base_url}/v2/connector_accounts/${merchant_connector_id}`; + const url = `${base_url}/v2/connector-accounts/${merchant_connector_id}`; const customHeaders = { "x-merchant-id": merchant_id, @@ -590,7 +590,7 @@ Cypress.Commands.add( const merchant_connector_id = globalState.get("merchantConnectorId"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId"); - const url = `${base_url}/v2/connector_accounts/${merchant_connector_id}`; + const url = `${base_url}/v2/connector-accounts/${merchant_connector_id}`; const customHeaders = { "x-merchant-id": merchant_id, @@ -653,7 +653,7 @@ Cypress.Commands.add("apiKeyCreateCall", (apiKeyCreateBody, globalState) => { const key_id_type = "key_id"; const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); - const url = `${base_url}/v2/api_keys`; + const url = `${base_url}/v2/api-keys`; const customHeaders = { "x-merchant-id": merchant_id, @@ -703,7 +703,7 @@ Cypress.Commands.add("apiKeyRetrieveCall", (globalState) => { const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); const api_key_id = globalState.get("apiKeyId"); - const url = `${base_url}/v2/api_keys/${api_key_id}`; + const url = `${base_url}/v2/api-keys/${api_key_id}`; const customHeaders = { "x-merchant-id": merchant_id, @@ -750,7 +750,7 @@ Cypress.Commands.add("apiKeyUpdateCall", (apiKeyUpdateBody, globalState) => { const key_id_type = "key_id"; const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); - const url = `${base_url}/v2/api_keys/${api_key_id}`; + const url = `${base_url}/v2/api-keys/${api_key_id}`; const customHeaders = { "x-merchant-id": merchant_id, @@ -801,7 +801,7 @@ Cypress.Commands.add( const api_key = globalState.get("userInfoToken"); const base_url = globalState.get("baseUrl"); const profile_id = globalState.get("profileId"); - const url = `${base_url}/v2/routing_algorithm`; + const url = `${base_url}/v2/routing-algorithm`; // Update request body routingSetupBody.algorithm.data = payload.data; @@ -847,7 +847,7 @@ Cypress.Commands.add( const base_url = globalState.get("baseUrl"); const profile_id = globalState.get("profileId"); const routing_algorithm_id = globalState.get("routingAlgorithmId"); - const url = `${base_url}/v2/profiles/${profile_id}/activate_routing_algorithm`; + const url = `${base_url}/v2/profiles/${profile_id}/activate-routing-algorithm`; // Update request body routingActivationBody.routing_algorithm_id = routing_algorithm_id; @@ -885,7 +885,7 @@ Cypress.Commands.add("routingActivationRetrieveCall", (globalState) => { const profile_id = globalState.get("profileId"); const query_params = "limit=10"; const routing_algorithm_id = globalState.get("routingAlgorithmId"); - const url = `${base_url}/v2/profiles/${profile_id}/routing_algorithm?${query_params}`; + const url = `${base_url}/v2/profiles/${profile_id}/routing-algorithm?${query_params}`; cy.request({ method: "GET", @@ -922,7 +922,7 @@ Cypress.Commands.add("routingDeactivateCall", (globalState) => { const base_url = globalState.get("baseUrl"); const profile_id = globalState.get("profileId"); const routing_algorithm_id = globalState.get("routingAlgorithmId"); - const url = `${base_url}/v2/profiles/${profile_id}/deactivate_routing_algorithm`; + const url = `${base_url}/v2/profiles/${profile_id}/deactivate-routing-algorithm`; cy.request({ method: "PATCH", @@ -957,7 +957,7 @@ Cypress.Commands.add("routingRetrieveCall", (globalState) => { const base_url = globalState.get("baseUrl"); const profile_id = globalState.get("profileId"); const routing_algorithm_id = globalState.get("routingAlgorithmId"); - const url = `${base_url}/v2/routing_algorithm/${routing_algorithm_id}`; + const url = `${base_url}/v2/routing-algorithm/${routing_algorithm_id}`; cy.request({ method: "GET", @@ -996,7 +996,7 @@ Cypress.Commands.add( const base_url = globalState.get("baseUrl"); const profile_id = globalState.get("profileId"); const routing_algorithm_id = globalState.get("routingAlgorithmId"); - const url = `${base_url}/v2/profiles/${profile_id}/fallback_routing`; + const url = `${base_url}/v2/profiles/${profile_id}/fallback-routing`; // Update request body routingDefaultFallbackBody = payload; @@ -1029,7 +1029,7 @@ Cypress.Commands.add("routingFallbackRetrieveCall", (globalState) => { const api_key = globalState.get("userInfoToken"); const base_url = globalState.get("baseUrl"); const profile_id = globalState.get("profileId"); - const url = `${base_url}/v2/profiles/${profile_id}/fallback_routing`; + const url = `${base_url}/v2/profiles/${profile_id}/fallback-routing`; cy.request({ method: "GET", @@ -1166,7 +1166,7 @@ Cypress.Commands.add("merchantAccountsListCall", (globalState) => { const key_id_type = "publishable_key"; const key_id = validateEnv(base_url, key_id_type); const organization_id = globalState.get("organizationId"); - const url = `${base_url}/v2/organization/${organization_id}/merchant_accounts`; + const url = `${base_url}/v2/organization/${organization_id}/merchant-accounts`; cy.request({ method: "GET", @@ -1204,7 +1204,7 @@ Cypress.Commands.add("businessProfilesListCall", (globalState) => { const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); - const url = `${base_url}/v2/merchant_accounts/${merchant_id}/profiles`; + const url = `${base_url}/v2/merchant-accounts/${merchant_id}/profiles`; const customHeaders = { "x-merchant-id": merchant_id, @@ -1246,7 +1246,7 @@ Cypress.Commands.add("mcaListCall", (globalState, service_type) => { const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId"); - const url = `${base_url}/v2/profiles/${profile_id}/connector_accounts`; + const url = `${base_url}/v2/profiles/${profile_id}/connector-accounts`; const customHeaders = { "x-merchant-id": merchant_id, @@ -1308,7 +1308,7 @@ Cypress.Commands.add("apiKeysListCall", (globalState) => { const key_id_type = "key_id"; const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); - const url = `${base_url}/v2/api_keys/list`; + const url = `${base_url}/v2/api-keys/list`; const customHeaders = { "x-merchant-id": merchant_id,
2024-11-07T13:12:55Z
## Description <!-- Describe your changes in detail --> Use kebab-case for all API endpoints in V2 ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This is mostly a documentation PR, doesn't require any additional test cases. Verified that existing cypress tests are passing
d4b482c21cf57b022c7bbadc1a3a9c9d9e5d4f03
This is mostly a documentation PR, doesn't require any additional test cases. Verified that existing cypress tests are passing
[ "api-reference-v2/api-reference/api-key/api-key--create.mdx", "api-reference-v2/api-reference/api-key/api-key--list.mdx", "api-reference-v2/api-reference/api-key/api-key--retrieve.mdx", "api-reference-v2/api-reference/api-key/api-key--revoke.mdx", "api-reference-v2/api-reference/api-key/api-key--update.mdx", "api-reference-v2/api-reference/business-profile/merchant-connector--list.mdx", "api-reference-v2/api-reference/connector-account/connector-account--create.mdx", "api-reference-v2/api-reference/connector-account/connector-account--delete.mdx", "api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx", "api-reference-v2/api-reference/connector-account/connector-account--update.mdx", "api-reference-v2/api-reference/merchant-account/business-profile--list.mdx", "api-reference-v2/api-reference/merchant-account/merchant-account--create.mdx", "api-reference-v2/api-reference/merchant-account/merchant-account--retrieve.mdx", "api-reference-v2/api-reference/merchant-account/merchant-account--update.mdx", "api-reference-v2/api-reference/merchant-account/profile--list.mdx", "api-reference-v2/api-reference/organization/organization--merchant-account--list.mdx", "api-reference-v2/api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx", "api-reference-v2/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx", "api-reference-v2/api-reference/payment-methods/payment-method--confirm-intent.mdx", "api-reference-v2/api-reference/payment-methods/payment-method--create-intent.mdx", "api-reference-v2/api-reference/payment-methods/payment-method--create.mdx", "api-reference-v2/api-reference/payment-methods/payment-method--delete.mdx", "api-reference-v2/api-reference/payment-methods/payment-method--retrieve.mdx", "api-reference-v2/api-reference/payment-methods/payment-method--update.mdx", "api-reference-v2/api-reference/profile/merchant-connector--list.mdx", "api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx", "api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx", "api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx", "api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx", "api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx", "api-reference-v2/api-reference/routing/routing--create.mdx", "api-reference-v2/api-reference/routing/routing--retrieve.mdx", "api-reference-v2/mint.json", "api-reference-v2/openapi_spec.json", "crates/api_models/src/organization.rs", "crates/api_models/src/payment_methods.rs", "crates/hyperswitch_domain_models/src/payments.rs", "crates/openapi/src/openapi_v2.rs", "crates/openapi/src/routes/api_keys.rs", "crates/openapi/src/routes/merchant_account.rs", "crates/openapi/src/routes/merchant_connector_account.rs", "crates/openapi/src/routes/organization.rs", "crates/openapi/src/routes/payment_method.rs", "crates/openapi/src/routes/profile.rs", "crates/openapi/src/routes/routing.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/payment_methods.rs", "crates/router/src/types/api/admin.rs", "cypress-tests-v2/cypress/support/commands.js" ]
juspay/hyperswitch
juspay__hyperswitch-6506
Bug: [BUG] API Reference documentation broken ### Bug Description API reference is broken for following endpoints: - `API Key - Create` - `API Key - Revoke` - `Routing - Retrieve` - `Routing - Activate Config` ### Expected Behavior <img width="1514" alt="image" src="https://github.com/user-attachments/assets/139a8e53-1d10-4e60-98c4-a4cb569f3d22"> ### Actual Behavior <img width="1514" alt="image" src="https://github.com/user-attachments/assets/f89e07c1-94a3-4e95-8a19-1c3495138704"> ### Steps To Reproduce Go to https://api-reference.hyperswitch.io/api-reference/api-key/api-key--create ### Context For The Bug _No response_ ### Environment Web ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
2024-11-07T11:04:51Z
## Description <!-- Describe your changes in detail --> Fixed broken API reference for the following endpoints: - `API Key - Create` - `API Key - Revoke` - `Routing - Retrieve` - `Routing - Activate Config` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
cf126b940812b8adce26d7a0f957ed92309130d6
[]
juspay/hyperswitch
juspay__hyperswitch-6505
Bug: add card expiry check in the `network_transaction_id_and_card_details` based `MIT` flow [Reference pr](https://github.com/juspay/hyperswitch/pull/6245). Add card expiry validation for the `recurring_details` = `network_transaction_id_and_card_details` based MIT flow
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 5d75001b118..a09510a4c4e 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4464,6 +4464,11 @@ where let (mandate_reference_id, card_details_for_network_transaction_id)= hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId::get_nti_and_card_details_for_mit_flow(recurring_payment_details.clone()).get_required_value("network transaction id and card details").attach_printable("Failed to fetch network transaction id and card details for mit")?; + helpers::validate_card_expiry( + &card_details_for_network_transaction_id.card_exp_month, + &card_details_for_network_transaction_id.card_exp_year, + )?; + let network_transaction_id_supported_connectors = &state .conf .network_transaction_id_supported_connectors
2024-11-07T10:52:50Z
## Description <!-- Describe your changes in detail --> [Reference pr](https://github.com/juspay/hyperswitch/pull/6245). Add card expiry validation for the `recurring_details` = `network_transaction_id_and_card_details` based MIT flow ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create the cybersource connector -> Create payment with recurring details "type": "network_transaction_id_and_card_details" with expired card ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --header 'Content-Type: application/json' \ --data-raw '{ "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "email": "guest@example.com", "payment_method": "card", "payment_method_type": "credit", "off_session": true, "recurring_details": { "type": "network_transaction_id_and_card_details", "data": { "card_number": "5454545454545454", "card_exp_month": "11", "card_exp_year": "2023", "card_holder_name": "name name", "network_transaction_id": "737" } }, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" } }' ``` ``` { "error": { "type": "invalid_request", "message": "Invalid Expiry Year", "code": "IR_16" } } ``` -> Create payment with recurring details "type": "network_transaction_id_and_card_details" with valid card ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --header 'Content-Type: application/json' \ --data-raw '{ "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "email": "guest@example.com", "payment_method": "card", "payment_method_type": "credit", "off_session": true, "recurring_details": { "type": "network_transaction_id_and_card_details", "data": { "card_number": "5454545454545454", "card_exp_month": "11", "card_exp_year": "2024", "card_holder_name": "name name", "network_transaction_id": "737" } }, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" } }' ``` ``` { "payment_id": "pay_1BG9IxreD8qApunv5xiB", "merchant_id": "merchant_1730973695", "status": "succeeded", "amount": 499, "net_amount": 499, "shipping_cost": null, "amount_capturable": 0, "amount_received": 499, "connector": "cybersource", "client_secret": "pay_1BG9IxreD8qApunv5xiB_secret_Kwrf2y7DNIo17tGrh4Ua", "created": "2024-11-07T11:04:36.886Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "5454", "card_type": "CREDIT", "card_network": null, "card_issuer": "BANKHANDLOWYWWARSZAWIE.S.A.", "card_issuing_country": "POLAND", "card_isin": "545454", "card_extended_bin": null, "card_exp_month": "11", "card_exp_year": "2024", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7309774770706430804953", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_1BG9IxreD8qApunv5xiB_1", "payment_link": null, "profile_id": "pro_nHm5ZVnwRP6Wixvy0bPZ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1Cr87i1MXNK3yoZsjM7q", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-07T11:19:36.886Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-11-07T11:04:37.995Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Psync ``` curl --location 'http://localhost:8080/payments/pay_1BG9IxreD8qApunv5xiB?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: ' ``` ``` { "payment_id": "pay_1BG9IxreD8qApunv5xiB", "merchant_id": "merchant_1730973695", "status": "succeeded", "amount": 499, "net_amount": 499, "shipping_cost": null, "amount_capturable": 0, "amount_received": 499, "connector": "cybersource", "client_secret": "pay_1BG9IxreD8qApunv5xiB_secret_Kwrf2y7DNIo17tGrh4Ua", "created": "2024-11-07T11:04:36.886Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "5454", "card_type": "CREDIT", "card_network": null, "card_issuer": "BANKHANDLOWYWWARSZAWIE.S.A.", "card_issuing_country": "POLAND", "card_isin": "545454", "card_extended_bin": null, "card_exp_month": "11", "card_exp_year": "2024", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7309774770706430804953", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_1BG9IxreD8qApunv5xiB_1", "payment_link": null, "profile_id": "pro_nHm5ZVnwRP6Wixvy0bPZ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1Cr87i1MXNK3yoZsjM7q", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-07T11:19:36.886Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-11-07T11:04:37.995Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ```
cf126b940812b8adce26d7a0f957ed92309130d6
-> Create the cybersource connector -> Create payment with recurring details "type": "network_transaction_id_and_card_details" with expired card ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --header 'Content-Type: application/json' \ --data-raw '{ "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "email": "guest@example.com", "payment_method": "card", "payment_method_type": "credit", "off_session": true, "recurring_details": { "type": "network_transaction_id_and_card_details", "data": { "card_number": "5454545454545454", "card_exp_month": "11", "card_exp_year": "2023", "card_holder_name": "name name", "network_transaction_id": "737" } }, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" } }' ``` ``` { "error": { "type": "invalid_request", "message": "Invalid Expiry Year", "code": "IR_16" } } ``` -> Create payment with recurring details "type": "network_transaction_id_and_card_details" with valid card ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --header 'Content-Type: application/json' \ --data-raw '{ "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "email": "guest@example.com", "payment_method": "card", "payment_method_type": "credit", "off_session": true, "recurring_details": { "type": "network_transaction_id_and_card_details", "data": { "card_number": "5454545454545454", "card_exp_month": "11", "card_exp_year": "2024", "card_holder_name": "name name", "network_transaction_id": "737" } }, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" } }' ``` ``` { "payment_id": "pay_1BG9IxreD8qApunv5xiB", "merchant_id": "merchant_1730973695", "status": "succeeded", "amount": 499, "net_amount": 499, "shipping_cost": null, "amount_capturable": 0, "amount_received": 499, "connector": "cybersource", "client_secret": "pay_1BG9IxreD8qApunv5xiB_secret_Kwrf2y7DNIo17tGrh4Ua", "created": "2024-11-07T11:04:36.886Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "5454", "card_type": "CREDIT", "card_network": null, "card_issuer": "BANKHANDLOWYWWARSZAWIE.S.A.", "card_issuing_country": "POLAND", "card_isin": "545454", "card_extended_bin": null, "card_exp_month": "11", "card_exp_year": "2024", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7309774770706430804953", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_1BG9IxreD8qApunv5xiB_1", "payment_link": null, "profile_id": "pro_nHm5ZVnwRP6Wixvy0bPZ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1Cr87i1MXNK3yoZsjM7q", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-07T11:19:36.886Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-11-07T11:04:37.995Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Psync ``` curl --location 'http://localhost:8080/payments/pay_1BG9IxreD8qApunv5xiB?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: ' ``` ``` { "payment_id": "pay_1BG9IxreD8qApunv5xiB", "merchant_id": "merchant_1730973695", "status": "succeeded", "amount": 499, "net_amount": 499, "shipping_cost": null, "amount_capturable": 0, "amount_received": 499, "connector": "cybersource", "client_secret": "pay_1BG9IxreD8qApunv5xiB_secret_Kwrf2y7DNIo17tGrh4Ua", "created": "2024-11-07T11:04:36.886Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "5454", "card_type": "CREDIT", "card_network": null, "card_issuer": "BANKHANDLOWYWWARSZAWIE.S.A.", "card_issuing_country": "POLAND", "card_isin": "545454", "card_extended_bin": null, "card_exp_month": "11", "card_exp_year": "2024", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7309774770706430804953", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_1BG9IxreD8qApunv5xiB_1", "payment_link": null, "profile_id": "pro_nHm5ZVnwRP6Wixvy0bPZ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1Cr87i1MXNK3yoZsjM7q", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-07T11:19:36.886Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-11-07T11:04:37.995Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ```
[ "crates/router/src/core/payments.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6501
Bug: feat: implement scylla cql traits for StrongSecret
diff --git a/Cargo.lock b/Cargo.lock index d232fcbf024..2d1f3cf4b06 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3698,6 +3698,12 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "histogram" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cb882ccb290b8646e554b157ab0b71e64e8d5bef775cd66b6531e52d302669" + [[package]] name = "hkdf" version = "0.12.4" @@ -4309,6 +4315,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.11" @@ -4566,6 +4581,15 @@ dependencies = [ "linked-hash-map", ] +[[package]] +name = "lz4_flex" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75761162ae2b0e580d7e7c390558127e5f01b4194debd6221fd8c207fc80e3f5" +dependencies = [ + "twox-hash", +] + [[package]] name = "masking" version = "0.1.0" @@ -4573,6 +4597,7 @@ dependencies = [ "bytes 1.7.1", "diesel", "erased-serde 0.4.5", + "scylla", "serde", "serde_json", "subtle", @@ -5970,6 +5995,15 @@ dependencies = [ "getrandom", ] +[[package]] +name = "rand_pcg" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e" +dependencies = [ + "rand_core", +] + [[package]] name = "rand_xorshift" version = "0.3.0" @@ -6891,6 +6925,66 @@ dependencies = [ "untrusted 0.9.0", ] +[[package]] +name = "scylla" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8139623d3fb0c8205b15e84fa587f3aa0ba61f876c19a9157b688f7c1763a7c5" +dependencies = [ + "arc-swap", + "async-trait", + "byteorder", + "bytes 1.7.1", + "chrono", + "dashmap", + "futures 0.3.30", + "hashbrown 0.14.5", + "histogram", + "itertools 0.13.0", + "lazy_static", + "lz4_flex", + "rand", + "rand_pcg", + "scylla-cql", + "scylla-macros", + "smallvec 1.13.2", + "snap", + "socket2", + "thiserror", + "tokio 1.40.0", + "tracing", + "uuid", +] + +[[package]] +name = "scylla-cql" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de7020bcd1f6fdbeaed356cd426bf294b2071bd7120d48d2e8e319295e2acdcd" +dependencies = [ + "async-trait", + "byteorder", + "bytes 1.7.1", + "lz4_flex", + "scylla-macros", + "snap", + "thiserror", + "tokio 1.40.0", + "uuid", +] + +[[package]] +name = "scylla-macros" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3859b6938663fc5062e3b26f3611649c9bd26fb252e85f6fdfa581e0d2ce74b6" +dependencies = [ + "darling 0.20.10", + "proc-macro2", + "quote", + "syn 2.0.77", +] + [[package]] name = "sdd" version = "3.0.2" @@ -7314,6 +7408,12 @@ dependencies = [ "serde", ] +[[package]] +name = "snap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b6b67fb9a61334225b5b790716f609cd58395f895b3fe8b328786812a40bc3b" + [[package]] name = "socket2" version = "0.5.7" @@ -7568,6 +7668,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "storage_impl" version = "0.1.0" @@ -8669,6 +8775,16 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "twox-hash" +version = "1.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" +dependencies = [ + "cfg-if 1.0.0", + "static_assertions", +] + [[package]] name = "typeid" version = "1.0.2" diff --git a/crates/masking/Cargo.toml b/crates/masking/Cargo.toml index ed20a08de34..425c1ca36ec 100644 --- a/crates/masking/Cargo.toml +++ b/crates/masking/Cargo.toml @@ -12,6 +12,7 @@ default = ["alloc", "serde", "diesel", "time"] alloc = ["zeroize/alloc"] serde = ["dep:serde", "dep:serde_json"] time = ["dep:time"] +cassandra = ["dep:scylla"] [package.metadata.docs.rs] all-features = true @@ -27,6 +28,7 @@ subtle = "2.5.0" time = { version = "0.3.35", optional = true, features = ["serde-human-readable"] } url = { version = "2.5.0", features = ["serde"] } zeroize = { version = "1.7", default-features = false } +scylla = { version = "0.14.0", optional = true} [dev-dependencies] serde_json = "1.0.115" diff --git a/crates/masking/src/cassandra.rs b/crates/masking/src/cassandra.rs new file mode 100644 index 00000000000..dc81512e79d --- /dev/null +++ b/crates/masking/src/cassandra.rs @@ -0,0 +1,50 @@ +use scylla::{ + cql_to_rust::FromCqlVal, + deserialize::DeserializeValue, + frame::response::result::{ColumnType, CqlValue}, + serialize::{ + value::SerializeValue, + writers::{CellWriter, WrittenCellProof}, + SerializationError, + }, +}; + +use crate::{abs::PeekInterface, StrongSecret}; + +impl<T> SerializeValue for StrongSecret<T> +where + T: SerializeValue + zeroize::Zeroize + Clone, +{ + fn serialize<'b>( + &self, + typ: &ColumnType, + writer: CellWriter<'b>, + ) -> Result<WrittenCellProof<'b>, SerializationError> { + self.peek().serialize(typ, writer) + } +} + +impl<'frame, T> DeserializeValue<'frame> for StrongSecret<T> +where + T: DeserializeValue<'frame> + zeroize::Zeroize + Clone, +{ + fn type_check(typ: &ColumnType) -> Result<(), scylla::deserialize::TypeCheckError> { + T::type_check(typ) + } + + fn deserialize( + typ: &'frame ColumnType, + v: Option<scylla::deserialize::FrameSlice<'frame>>, + ) -> Result<Self, scylla::deserialize::DeserializationError> { + Ok(Self::new(T::deserialize(typ, v)?)) + } +} + +impl<T> FromCqlVal<CqlValue> for StrongSecret<T> +where + T: FromCqlVal<CqlValue> + zeroize::Zeroize + Clone, +{ + fn from_cql(cql_val: CqlValue) -> Result<Self, scylla::cql_to_rust::FromCqlValError> { + Ok(Self::new(T::from_cql(cql_val)?)) + } +} diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs index ca0da6b6767..d376e935bd6 100644 --- a/crates/masking/src/lib.rs +++ b/crates/masking/src/lib.rs @@ -57,6 +57,9 @@ pub mod prelude { #[cfg(feature = "diesel")] mod diesel; +#[cfg(feature = "cassandra")] +mod cassandra; + pub mod maskable; pub use maskable::*;
2024-11-07T06:34:24Z
## Description <!-- Describe your changes in detail --> This adds `SerializeValue` and `FromCQL` traits for masking StrongSecret ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This is needed for Cassandra ORM to work ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ** THIS CANNOT BE TESTED ON ENVIRONEMTS ** Compiler guided
90d9ffc1d2e13b83931762b05632056520eea07f
** THIS CANNOT BE TESTED ON ENVIRONEMTS ** Compiler guided
[ "Cargo.lock", "crates/masking/Cargo.toml", "crates/masking/src/cassandra.rs", "crates/masking/src/lib.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6495
Bug: [DOCS] FIx API documentation for V2 - Merchant Account Update: Path Parameters in definition says it is {account_id} instead that should be {id} - Merchant Profile List Changes: Instead `Profile - list` make `Merchant Account - Profile List` , Path Parameters in definition says it is {account_id} instead that should be {id} - Profile Changes: In profile all routes has [profile_id] in the path, change the path to [id] and the explanation in path parameter also to [id]. For `Merchant Connector - list` in side-bar, change to `Profile - Connector Accounts list`. In the definition of the api `List Merchant Connector Details for the business profile` instead `List Connector Accounts for the profile` - Connector Account Changes: Instead of `Merchant Connector Account` use the term `Connector Account` - Api-Key Changes: In the path param and its definition we are using {key_id] instead use [id] - Routing Changes: In path param and its definition we are using {routing_algorithm_id} instead is {id] , these changes are in api-documentation
diff --git a/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx b/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx index 13b87953f1b..ee7970122d4 100644 --- a/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx +++ b/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/api_keys/{key_id} +openapi: get /v2/api_keys/{id} --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/api-key/api-key--revoke.mdx b/api-reference-v2/api-reference/api-key/api-key--revoke.mdx index 37a9c9fcc09..9362743088b 100644 --- a/api-reference-v2/api-reference/api-key/api-key--revoke.mdx +++ b/api-reference-v2/api-reference/api-key/api-key--revoke.mdx @@ -1,3 +1,3 @@ --- -openapi: delete /v2/api_keys/{key_id} +openapi: delete /v2/api_keys/{id} --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/api-key/api-key--update.mdx b/api-reference-v2/api-reference/api-key/api-key--update.mdx index 8d1b6e2ee11..c682cf1ee9e 100644 --- a/api-reference-v2/api-reference/api-key/api-key--update.mdx +++ b/api-reference-v2/api-reference/api-key/api-key--update.mdx @@ -1,3 +1,3 @@ --- -openapi: put /v2/api_keys/{key_id} +openapi: put /v2/api_keys/{id} --- diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--create.mdx b/api-reference-v2/api-reference/connector-account/connector-account--create.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-connector-account/merchant-connector--create.mdx rename to api-reference-v2/api-reference/connector-account/connector-account--create.mdx diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--delete.mdx b/api-reference-v2/api-reference/connector-account/connector-account--delete.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-connector-account/merchant-connector--delete.mdx rename to api-reference-v2/api-reference/connector-account/connector-account--delete.mdx diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--retrieve.mdx b/api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-connector-account/merchant-connector--retrieve.mdx rename to api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--update.mdx b/api-reference-v2/api-reference/connector-account/connector-account--update.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-connector-account/merchant-connector--update.mdx rename to api-reference-v2/api-reference/connector-account/connector-account--update.mdx diff --git a/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx b/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx index e14bc0d6ef3..97deb0832cc 100644 --- a/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx +++ b/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/merchant_accounts/{account_id}/profiles +openapi: get /v2/merchant_accounts/{id}/profiles --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/payments/payments--session-token.mdx b/api-reference-v2/api-reference/payments/payments--session-token.mdx index 2b4f6b0bec6..615bafcc03d 100644 --- a/api-reference-v2/api-reference/payments/payments--session-token.mdx +++ b/api-reference-v2/api-reference/payments/payments--session-token.mdx @@ -1,3 +1,3 @@ --- -openapi: post /v2/payments/{payment_id}/create_external_sdk_tokens +openapi: post /v2/payments/{payment_id}/create-external-sdk-tokens --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/merchant-connector--list.mdx b/api-reference-v2/api-reference/profile/merchant-connector--list.mdx index 6560f45e5fa..81f640436f4 100644 --- a/api-reference-v2/api-reference/profile/merchant-connector--list.mdx +++ b/api-reference-v2/api-reference/profile/merchant-connector--list.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/profiles/{profile_id}/connector_accounts +openapi: get /v2/profiles/{id}/connector_accounts --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx index 9ff6f4fdd57..7225f422e5a 100644 --- a/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx +++ b/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx @@ -1,3 +1,3 @@ --- -openapi: patch /v2/profiles/{profile_id}/activate_routing_algorithm +openapi: patch /v2/profiles/{id}/activate_routing_algorithm --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx index 5cc815612e0..87aac8b9379 100644 --- a/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx +++ b/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx @@ -1,3 +1,3 @@ --- -openapi: patch /v2/profiles/{profile_id}/deactivate_routing_algorithm +openapi: patch /v2/profiles/{id}/deactivate_routing_algorithm --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx index 7aba27485ed..86d2d35d57c 100644 --- a/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx +++ b/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/profiles/{profile_id}/routing_algorithm +openapi: get /v2/profiles/{id}/routing_algorithm --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx index 9b1b9429077..1bc383c278f 100644 --- a/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx +++ b/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/profiles/{profile_id}/fallback_routing +openapi: get /v2/profiles/{id}/fallback_routing --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--retrieve.mdx b/api-reference-v2/api-reference/profile/profile--retrieve.mdx index 235bb7d7f50..28ca1fbd1b1 100644 --- a/api-reference-v2/api-reference/profile/profile--retrieve.mdx +++ b/api-reference-v2/api-reference/profile/profile--retrieve.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/profiles/{profile_id} +openapi: get /v2/profiles/{id} --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx index 0ba69796a7e..76f4d4fa77f 100644 --- a/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx +++ b/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx @@ -1,3 +1,3 @@ --- -openapi: patch /v2/profiles/{profile_id}/fallback_routing +openapi: patch /v2/profiles/{id}/fallback_routing --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/profile/profile--update.mdx b/api-reference-v2/api-reference/profile/profile--update.mdx index bf35d0afb64..21b50001c63 100644 --- a/api-reference-v2/api-reference/profile/profile--update.mdx +++ b/api-reference-v2/api-reference/profile/profile--update.mdx @@ -1,3 +1,3 @@ --- -openapi: put /v2/profiles/{profile_id} +openapi: put /v2/profiles/{id} --- \ No newline at end of file diff --git a/api-reference-v2/api-reference/routing/routing--retrieve.mdx b/api-reference-v2/api-reference/routing/routing--retrieve.mdx index 03f209951c0..776ff69e004 100644 --- a/api-reference-v2/api-reference/routing/routing--retrieve.mdx +++ b/api-reference-v2/api-reference/routing/routing--retrieve.mdx @@ -1,3 +1,3 @@ --- -openapi: get /v2/routing_algorithm/{routing_algorithm_id} +openapi: get /v2/routing_algorithm/{id} --- \ No newline at end of file diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json index 17dd6dfb7ff..dc47cf5d4c0 100644 --- a/api-reference-v2/mint.json +++ b/api-reference-v2/mint.json @@ -76,11 +76,11 @@ ] }, { - "group": "Merchant Connector Account", + "group": "Connector Account", "pages": [ - "api-reference/merchant-connector-account/merchant-connector--create", - "api-reference/merchant-connector-account/merchant-connector--retrieve", - "api-reference/merchant-connector-account/merchant-connector--update" + "api-reference/connector-account/connector-account--create", + "api-reference/connector-account/connector-account--retrieve", + "api-reference/connector-account/connector-account--update" ] }, { diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 4c1559fe099..1f955ab1d80 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -213,8 +213,8 @@ "tags": [ "Merchant Connector Account" ], - "summary": "Merchant Connector - Create", - "description": "Creates a new Merchant Connector for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.", + "summary": "Connector Account - Create", + "description": "Creates a new Connector Account for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.", "operationId": "Create a Merchant Connector", "requestBody": { "content": { @@ -290,7 +290,7 @@ "tags": [ "Merchant Connector Account" ], - "summary": "Merchant Connector - Retrieve", + "summary": "Connector Account - Retrieve", "description": "Retrieves details of a Connector account", "operationId": "Retrieve a Merchant Connector", "parameters": [ @@ -333,8 +333,8 @@ "tags": [ "Merchant Connector Account" ], - "summary": "Merchant Connector - Update", - "description": "To update an existing Merchant Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector", + "summary": "Connector Account - Update", + "description": "To update an existing Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector", "operationId": "Update a Merchant Connector", "parameters": [ { @@ -573,7 +573,7 @@ "operationId": "Update a Merchant Account", "parameters": [ { - "name": "account_id", + "name": "id", "in": "path", "description": "The unique identifier for the merchant account", "required": true, @@ -630,17 +630,17 @@ ] } }, - "/v2/merchant_accounts/{account_id}/profiles": { + "/v2/merchant_accounts/{id}/profiles": { "get": { "tags": [ "Merchant Account" ], - "summary": "Profile - List", + "summary": "Merchant Account - Profile List", "description": "List profiles for an Merchant", "operationId": "List Profiles", "parameters": [ { - "name": "account_id", + "name": "id", "in": "path", "description": "The unique identifier for the Merchant", "required": true, @@ -682,6 +682,17 @@ "summary": "Payments - Session token", "description": "Creates a session object or a session token for wallets like Apple Pay, Google Pay, etc. These tokens are used by Hyperswitch's SDK to initiate these wallets' SDK.", "operationId": "Create Session tokens for a Payment", + "parameters": [ + { + "name": "payment_id", + "in": "path", + "description": "The identifier for payment", + "required": true, + "schema": { + "type": "string" + } + } + ], "requestBody": { "content": { "application/json": { @@ -775,7 +786,7 @@ ] } }, - "/v2/profiles/{profile_id}": { + "/v2/profiles/{id}": { "get": { "tags": [ "Profile" @@ -785,7 +796,7 @@ "operationId": "Retrieve a Profile", "parameters": [ { - "name": "profile_id", + "name": "id", "in": "path", "description": "The unique identifier for the profile", "required": true, @@ -836,7 +847,7 @@ "operationId": "Update a Profile", "parameters": [ { - "name": "profile_id", + "name": "id", "in": "path", "description": "The unique identifier for the profile", "required": true, @@ -896,17 +907,17 @@ ] } }, - "/v2/profiles/{profile_id}/connector_accounts": { + "/v2/profiles/{id}/connector_accounts": { "get": { "tags": [ "Business Profile" ], - "summary": "Merchant Connector - List", - "description": "List Merchant Connector Details for the business profile", + "summary": "Profile - Connector Accounts List", + "description": "List Connector Accounts for the profile", "operationId": "List all Merchant Connectors", "parameters": [ { - "name": "profile_id", + "name": "id", "in": "path", "description": "The unique identifier for the business profile", "required": true, @@ -955,7 +966,7 @@ ] } }, - "/v2/profiles/{profile_id}/activate_routing_algorithm": { + "/v2/profiles/{id}/activate_routing_algorithm": { "patch": { "tags": [ "Profile" @@ -965,7 +976,7 @@ "operationId": "Activates a routing algorithm under a profile", "parameters": [ { - "name": "profile_id", + "name": "id", "in": "path", "description": "The unique identifier for the profile", "required": true, @@ -1022,7 +1033,7 @@ ] } }, - "/v2/profiles/{profile_id}/deactivate_routing_algorithm": { + "/v2/profiles/{id}/deactivate_routing_algorithm": { "patch": { "tags": [ "Profile" @@ -1032,7 +1043,7 @@ "operationId": " Deactivates a routing algorithm under a profile", "parameters": [ { - "name": "profile_id", + "name": "id", "in": "path", "description": "The unique identifier for the profile", "required": true, @@ -1075,7 +1086,7 @@ ] } }, - "/v2/profiles/{profile_id}/fallback_routing": { + "/v2/profiles/{id}/fallback_routing": { "patch": { "tags": [ "Profile" @@ -1085,7 +1096,7 @@ "operationId": "Update the default fallback routing algorithm for the profile", "parameters": [ { - "name": "profile_id", + "name": "id", "in": "path", "description": "The unique identifier for the profile", "required": true, @@ -1149,7 +1160,7 @@ "operationId": "Retrieve the default fallback routing algorithm for the profile", "parameters": [ { - "name": "profile_id", + "name": "id", "in": "path", "description": "The unique identifier for the profile", "required": true, @@ -1186,7 +1197,7 @@ ] } }, - "/v2/profiles/{profile_id}/routing_algorithm": { + "/v2/profiles/{id}/routing_algorithm": { "get": { "tags": [ "Profile" @@ -1196,7 +1207,7 @@ "operationId": "Retrieve the active routing algorithm under the profile", "parameters": [ { - "name": "profile_id", + "name": "id", "in": "path", "description": "The unique identifier for the profile", "required": true, @@ -1315,7 +1326,7 @@ ] } }, - "/v2/routing_algorithm/{routing_algorithm_id}": { + "/v2/routing_algorithm/{id}": { "get": { "tags": [ "Routing" @@ -1325,7 +1336,7 @@ "operationId": "Retrieve a routing algorithm with its algorithm id", "parameters": [ { - "name": "routing_algorithm_id", + "name": "id", "in": "path", "description": "The unique identifier for a routing algorithm", "required": true, @@ -1405,7 +1416,7 @@ ] } }, - "/v2/api_keys/{key_id}": { + "/v2/api_keys/{id}": { "get": { "tags": [ "API Key" @@ -1415,7 +1426,7 @@ "operationId": "Retrieve an API Key", "parameters": [ { - "name": "key_id", + "name": "id", "in": "path", "description": "The unique identifier for the API Key", "required": true, @@ -1454,7 +1465,7 @@ "operationId": "Update an API Key", "parameters": [ { - "name": "key_id", + "name": "id", "in": "path", "description": "The unique identifier for the API Key", "required": true, @@ -1503,7 +1514,7 @@ "operationId": "Revoke an API Key", "parameters": [ { - "name": "key_id", + "name": "id", "in": "path", "description": "The unique identifier for the API Key", "required": true, @@ -20082,7 +20093,7 @@ "type": "apiKey", "in": "header", "name": "api-key", - "description": "Admin API keys allow you to perform some privileged actions such as creating a merchant account and Merchant Connector account." + "description": "Admin API keys allow you to perform some privileged actions such as creating a merchant account and Connector account." }, "api_key": { "type": "apiKey", diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 40f694b80a2..13706912ecd 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -614,7 +614,7 @@ impl utoipa::Modify for SecurityAddon { SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description( "api-key", "Admin API keys allow you to perform some privileged actions such as \ - creating a merchant account and Merchant Connector account." + creating a merchant account and Connector account." ))), ), ( diff --git a/crates/openapi/src/routes/api_keys.rs b/crates/openapi/src/routes/api_keys.rs index 7527c8a1095..cfc4c09ce46 100644 --- a/crates/openapi/src/routes/api_keys.rs +++ b/crates/openapi/src/routes/api_keys.rs @@ -64,9 +64,9 @@ pub async fn api_key_retrieve() {} /// Retrieve information about the specified API Key. #[utoipa::path( get, - path = "/v2/api_keys/{key_id}", + path = "/v2/api_keys/{id}", params ( - ("key_id" = String, Path, description = "The unique identifier for the API Key") + ("id" = String, Path, description = "The unique identifier for the API Key") ), responses( (status = 200, description = "API Key retrieved", body = RetrieveApiKeyResponse), @@ -106,10 +106,10 @@ pub async fn api_key_update() {} /// Update information for the specified API Key. #[utoipa::path( put, - path = "/v2/api_keys/{key_id}", + path = "/v2/api_keys/{id}", request_body = UpdateApiKeyRequest, params ( - ("key_id" = String, Path, description = "The unique identifier for the API Key") + ("id" = String, Path, description = "The unique identifier for the API Key") ), responses( (status = 200, description = "API Key updated", body = RetrieveApiKeyResponse), @@ -150,9 +150,9 @@ pub async fn api_key_revoke() {} /// authenticating with our APIs. #[utoipa::path( delete, - path = "/v2/api_keys/{key_id}", + path = "/v2/api_keys/{id}", params ( - ("key_id" = String, Path, description = "The unique identifier for the API Key") + ("id" = String, Path, description = "The unique identifier for the API Key") ), responses( (status = 200, description = "API Key revoked", body = RevokeApiKeyResponse), diff --git a/crates/openapi/src/routes/merchant_account.rs b/crates/openapi/src/routes/merchant_account.rs index 01571da1de9..022a5e6c006 100644 --- a/crates/openapi/src/routes/merchant_account.rs +++ b/crates/openapi/src/routes/merchant_account.rs @@ -212,7 +212,7 @@ pub async fn update_merchant_account() {} ) ), )), - params (("account_id" = String, Path, description = "The unique identifier for the merchant account")), + params (("id" = String, Path, description = "The unique identifier for the merchant account")), responses( (status = 200, description = "Merchant Account Updated", body = MerchantAccountResponse), (status = 404, description = "Merchant account not found") @@ -295,13 +295,13 @@ pub async fn merchant_account_kv_status() {} pub async fn payment_connector_list_profile() {} #[cfg(feature = "v2")] -/// Profile - List +/// Merchant Account - Profile List /// /// List profiles for an Merchant #[utoipa::path( get, - path = "/v2/merchant_accounts/{account_id}/profiles", - params (("account_id" = String, Path, description = "The unique identifier for the Merchant")), + path = "/v2/merchant_accounts/{id}/profiles", + params (("id" = String, Path, description = "The unique identifier for the Merchant")), responses( (status = 200, description = "profile list retrieved successfully", body = Vec<ProfileResponse>), (status = 400, description = "Invalid data") diff --git a/crates/openapi/src/routes/merchant_connector_account.rs b/crates/openapi/src/routes/merchant_connector_account.rs index a9cabde8af4..29092b5bba0 100644 --- a/crates/openapi/src/routes/merchant_connector_account.rs +++ b/crates/openapi/src/routes/merchant_connector_account.rs @@ -61,9 +61,9 @@ )] pub async fn connector_create() {} -/// Merchant Connector - Create +/// Connector Account - Create /// -/// Creates a new Merchant Connector for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc. +/// Creates a new Connector Account for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc. #[cfg(feature = "v2")] #[utoipa::path( post, @@ -146,7 +146,7 @@ pub async fn connector_create() {} )] pub async fn connector_retrieve() {} -/// Merchant Connector - Retrieve +/// Connector Account - Retrieve /// /// Retrieves details of a Connector account #[cfg(feature = "v2")] @@ -235,9 +235,9 @@ pub async fn connector_list() {} )] pub async fn connector_update() {} -/// Merchant Connector - Update +/// Connector Account - Update /// -/// To update an existing Merchant Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector +/// To update an existing Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector #[cfg(feature = "v2")] #[utoipa::path( put, diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index e245c5af68a..77e5bea10f3 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -406,6 +406,9 @@ pub fn payments_connector_session() {} #[utoipa::path( post, path = "/v2/payments/{payment_id}/create-external-sdk-tokens", + params( + ("payment_id" = String, Path, description = "The identifier for payment") + ), request_body=PaymentsSessionRequest, responses( (status = 200, description = "Payment session object created or session token was retrieved from wallets", body = PaymentsSessionResponse), diff --git a/crates/openapi/src/routes/profile.rs b/crates/openapi/src/routes/profile.rs index fc56e642719..d88568653a4 100644 --- a/crates/openapi/src/routes/profile.rs +++ b/crates/openapi/src/routes/profile.rs @@ -174,9 +174,9 @@ pub async fn profile_create() {} /// Update the *profile* #[utoipa::path( put, - path = "/v2/profiles/{profile_id}", + path = "/v2/profiles/{id}", params( - ("profile_id" = String, Path, description = "The unique identifier for the profile"), + ("id" = String, Path, description = "The unique identifier for the profile"), ( "X-Merchant-Id" = String, Header, description = "Merchant ID of the profile.", @@ -210,7 +210,7 @@ pub async fn profile_update() {} /// Activates a routing algorithm under a profile #[utoipa::path( patch, - path = "/v2/profiles/{profile_id}/activate_routing_algorithm", + path = "/v2/profiles/{id}/activate_routing_algorithm", request_body ( content = RoutingAlgorithmId, examples( ( "Activate a routing algorithm" = ( @@ -220,7 +220,7 @@ pub async fn profile_update() {} ) ))), params( - ("profile_id" = String, Path, description = "The unique identifier for the profile"), + ("id" = String, Path, description = "The unique identifier for the profile"), ), responses( (status = 200, description = "Routing Algorithm is activated", body = RoutingDictionaryRecord), @@ -240,9 +240,9 @@ pub async fn routing_link_config() {} /// Deactivates a routing algorithm under a profile #[utoipa::path( patch, - path = "/v2/profiles/{profile_id}/deactivate_routing_algorithm", + path = "/v2/profiles/{id}/deactivate_routing_algorithm", params( - ("profile_id" = String, Path, description = "The unique identifier for the profile"), + ("id" = String, Path, description = "The unique identifier for the profile"), ), responses( (status = 200, description = "Successfully deactivated routing config", body = RoutingDictionaryRecord), @@ -263,10 +263,10 @@ pub async fn routing_unlink_config() {} /// Update the default fallback routing algorithm for the profile #[utoipa::path( patch, - path = "/v2/profiles/{profile_id}/fallback_routing", + path = "/v2/profiles/{id}/fallback_routing", request_body = Vec<RoutableConnectorChoice>, params( - ("profile_id" = String, Path, description = "The unique identifier for the profile"), + ("id" = String, Path, description = "The unique identifier for the profile"), ), responses( (status = 200, description = "Successfully updated the default fallback routing algorithm", body = Vec<RoutableConnectorChoice>), @@ -286,9 +286,9 @@ pub async fn routing_update_default_config() {} /// Retrieve existing *profile* #[utoipa::path( get, - path = "/v2/profiles/{profile_id}", + path = "/v2/profiles/{id}", params( - ("profile_id" = String, Path, description = "The unique identifier for the profile"), + ("id" = String, Path, description = "The unique identifier for the profile"), ( "X-Merchant-Id" = String, Header, description = "Merchant ID of the profile.", @@ -311,9 +311,9 @@ pub async fn profile_retrieve() {} /// Retrieve active routing algorithm under the profile #[utoipa::path( get, - path = "/v2/profiles/{profile_id}/routing_algorithm", + path = "/v2/profiles/{id}/routing_algorithm", params( - ("profile_id" = String, Path, description = "The unique identifier for the profile"), + ("id" = String, Path, description = "The unique identifier for the profile"), ("limit" = Option<u16>, Query, description = "The number of records of the algorithms to be returned"), ("offset" = Option<u8>, Query, description = "The record offset of the algorithm from which to start gathering the results")), responses( @@ -334,9 +334,9 @@ pub async fn routing_retrieve_linked_config() {} /// Retrieve the default fallback routing algorithm for the profile #[utoipa::path( get, - path = "/v2/profiles/{profile_id}/fallback_routing", + path = "/v2/profiles/{id}/fallback_routing", params( - ("profile_id" = String, Path, description = "The unique identifier for the profile"), + ("id" = String, Path, description = "The unique identifier for the profile"), ), responses( (status = 200, description = "Successfully retrieved default fallback routing algorithm", body = Vec<RoutableConnectorChoice>), @@ -348,14 +348,14 @@ pub async fn routing_retrieve_linked_config() {} )] pub async fn routing_retrieve_default_config() {} -/// Merchant Connector - List +/// Profile - Connector Accounts List /// -/// List Merchant Connector Details for the business profile +/// List Connector Accounts for the profile #[utoipa::path( get, - path = "/v2/profiles/{profile_id}/connector_accounts", + path = "/v2/profiles/{id}/connector_accounts", params( - ("profile_id" = String, Path, description = "The unique identifier for the business profile"), + ("id" = String, Path, description = "The unique identifier for the business profile"), ( "X-Merchant-Id" = String, Header, description = "Merchant ID of the profile.", diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs index 0bb79a2bbe4..67a22c2ca64 100644 --- a/crates/openapi/src/routes/routing.rs +++ b/crates/openapi/src/routes/routing.rs @@ -94,9 +94,9 @@ pub async fn routing_retrieve_config() {} #[utoipa::path( get, - path = "/v2/routing_algorithm/{routing_algorithm_id}", + path = "/v2/routing_algorithm/{id}", params( - ("routing_algorithm_id" = String, Path, description = "The unique identifier for a routing algorithm"), + ("id" = String, Path, description = "The unique identifier for a routing algorithm"), ), responses( (status = 200, description = "Successfully fetched routing algorithm", body = MerchantRoutingAlgorithm),
2024-11-06T13:16:33Z
## Description <!-- Describe your changes in detail --> Improved OpenAPI documentation for V2 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Issues Addressed <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - Merchant Account Update: Path Parameters in definition says it is {account_id} instead that should be {id} - Merchant Profile List Changes: Instead `Profile - list` make `Merchant Account - Profile List` , Path Parameters in definition says it is {account_id} instead that should be {id} - Profile Changes: In profile all routes has [profile_id] in the path, change the path to [id] and the explanation in path parameter also to [id]. For `Merchant Connector - list` in side-bar, change to `Profile - Connector Accounts list`. In the definition of the api `List Merchant Connector Details for the business profile` instead `List Connector Accounts for the profile` - Connector Account Changes: Instead of `Merchant Connector Account` use the term `Connector Account` - Api-Key Changes: In the path param and its definition we are using {key_id] instead use [id] - Routing Changes: In path param and its definition we are using {routing_algorithm_id} instead is {id] , these changes are in api-documentation ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
01c5216fdd6f1d841082868cccea6054b64e9e07
[ "api-reference-v2/api-reference/api-key/api-key--retrieve.mdx", "api-reference-v2/api-reference/api-key/api-key--revoke.mdx", "api-reference-v2/api-reference/api-key/api-key--update.mdx", "api-reference-v2/api-reference/merchant-connector-account/merchant-connector--create.mdx", "api-reference-v2/api-reference/merchant-connector-account/merchant-connector--delete.mdx", "api-reference-v2/api-reference/merchant-connector-account/merchant-connector--retrieve.mdx", "api-reference-v2/api-reference/merchant-connector-account/merchant-connector--update.mdx", "api-reference-v2/api-reference/merchant-account/business-profile--list.mdx", "api-reference-v2/api-reference/payments/payments--session-token.mdx", "api-reference-v2/api-reference/profile/merchant-connector--list.mdx", "api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx", "api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx", "api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx", "api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx", "api-reference-v2/api-reference/profile/profile--retrieve.mdx", "api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx", "api-reference-v2/api-reference/profile/profile--update.mdx", "api-reference-v2/api-reference/routing/routing--retrieve.mdx", "api-reference-v2/mint.json", "api-reference-v2/openapi_spec.json", "crates/openapi/src/openapi_v2.rs", "crates/openapi/src/routes/api_keys.rs", "crates/openapi/src/routes/merchant_account.rs", "crates/openapi/src/routes/merchant_connector_account.rs", "crates/openapi/src/routes/payments.rs", "crates/openapi/src/routes/profile.rs", "crates/openapi/src/routes/routing.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6491
Bug: feat(analytics): revert remove additional filters from PaymentIntentFilters When global filters are applied on the dashboard, these filters are being sent to both Payment Attempt and Payment Intent related metrics. Initially backend support was not present for capturing these filters and adding to the queries, for Payment Intent related metrics, but for the new Analytics V2 dashboard, since the Sessionizer Tables are being used, all these filter fields are supported in the Sessionizer Payment Intents table. When backend support was added to apply these filters for the new dashboard, the old dashboard started breaking, as the filter fields are not present in the existing Payment Intents table. FE stopped sending these filters to Payment Intent metrics on the old dashboard, and so we can add these filters back to PaymentIntentFilters to support the filters on the new Analytics V2 dashboard.
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index 3e8915c60a2..42b4895b6a2 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -372,6 +372,15 @@ pub async fn get_filters( PaymentIntentDimensions::PaymentIntentStatus => fil.status.map(|i| i.as_ref().to_string()), PaymentIntentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), PaymentIntentDimensions::ProfileId => fil.profile_id, + PaymentIntentDimensions::Connector => fil.connector, + PaymentIntentDimensions::AuthType => fil.authentication_type.map(|i| i.as_ref().to_string()), + PaymentIntentDimensions::PaymentMethod => fil.payment_method, + PaymentIntentDimensions::PaymentMethodType => fil.payment_method_type, + PaymentIntentDimensions::CardNetwork => fil.card_network, + PaymentIntentDimensions::MerchantId => fil.merchant_id, + PaymentIntentDimensions::CardLast4 => fil.card_last_4, + PaymentIntentDimensions::CardIssuer => fil.card_issuer, + PaymentIntentDimensions::ErrorReason => fil.error_reason, }) .collect::<Vec<String>>(); res.query_data.push(PaymentIntentFilterValue { diff --git a/crates/analytics/src/payment_intents/filters.rs b/crates/analytics/src/payment_intents/filters.rs index d03d6c2a15f..1468a67570a 100644 --- a/crates/analytics/src/payment_intents/filters.rs +++ b/crates/analytics/src/payment_intents/filters.rs @@ -1,6 +1,6 @@ use api_models::analytics::{payment_intents::PaymentIntentDimensions, Granularity, TimeRange}; use common_utils::errors::ReportSwitchExt; -use diesel_models::enums::{Currency, IntentStatus}; +use diesel_models::enums::{AuthenticationType, Currency, IntentStatus}; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -54,5 +54,14 @@ pub struct PaymentIntentFilterRow { pub status: Option<DBEnumWrapper<IntentStatus>>, pub currency: Option<DBEnumWrapper<Currency>>, pub profile_id: Option<String>, + pub connector: Option<String>, + pub authentication_type: Option<DBEnumWrapper<AuthenticationType>>, + pub payment_method: Option<String>, + pub payment_method_type: Option<String>, + pub card_network: Option<String>, + pub merchant_id: Option<String>, + pub card_last_4: Option<String>, + pub card_issuer: Option<String>, + pub error_reason: Option<String>, pub customer_id: Option<String>, } diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs index 9aa7d3e9771..ee3d4773e24 100644 --- a/crates/analytics/src/payment_intents/metrics.rs +++ b/crates/analytics/src/payment_intents/metrics.rs @@ -36,6 +36,15 @@ pub struct PaymentIntentMetricRow { pub status: Option<DBEnumWrapper<storage_enums::IntentStatus>>, pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub profile_id: Option<String>, + pub connector: Option<String>, + pub authentication_type: Option<DBEnumWrapper<storage_enums::AuthenticationType>>, + pub payment_method: Option<String>, + pub payment_method_type: Option<String>, + pub card_network: Option<String>, + pub merchant_id: Option<String>, + pub card_last_4: Option<String>, + pub card_issuer: Option<String>, + pub error_reason: Option<String>, pub first_attempt: Option<i64>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, diff --git a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs index 4632cbe9f37..b301a9b9b23 100644 --- a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs +++ b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs @@ -101,6 +101,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs index 51b574f4ad3..cf733b0c3da 100644 --- a/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs @@ -138,6 +138,15 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs index 14e168b3523..07b1bfcf69f 100644 --- a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs +++ b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs @@ -114,6 +114,15 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs index 644bf35a723..7475a75bb53 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs @@ -101,6 +101,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs index e7772245063..506965375f5 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs @@ -128,6 +128,15 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs index eed6bf85a2c..0b55c101a7c 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs @@ -113,6 +113,15 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs index bd1f8bbbcd9..8c340d0b2d6 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs @@ -114,6 +114,15 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs index 6d36aca5172..8105a4c82a4 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs @@ -122,6 +122,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs index bf97e4c41ef..0b28cb5366d 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs @@ -111,6 +111,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs index cea5b2fa465..20ef8be6277 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs @@ -106,6 +106,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs index b23fcafdee0..8468911f7bb 100644 --- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs @@ -122,6 +122,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs index 4fe5f3a26f5..a19bdec518c 100644 --- a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs @@ -111,6 +111,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs index e98efa9f6ab..f5539abd9f5 100644 --- a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs @@ -106,6 +106,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/types.rs b/crates/analytics/src/payment_intents/types.rs index bb5141297c5..a27ef2d840d 100644 --- a/crates/analytics/src/payment_intents/types.rs +++ b/crates/analytics/src/payment_intents/types.rs @@ -30,6 +30,63 @@ where .add_filter_in_range_clause(PaymentIntentDimensions::ProfileId, &self.profile_id) .attach_printable("Error adding profile id filter")?; } + if !self.connector.is_empty() { + builder + .add_filter_in_range_clause(PaymentIntentDimensions::Connector, &self.connector) + .attach_printable("Error adding connector filter")?; + } + if !self.auth_type.is_empty() { + builder + .add_filter_in_range_clause(PaymentIntentDimensions::AuthType, &self.auth_type) + .attach_printable("Error adding auth type filter")?; + } + if !self.payment_method.is_empty() { + builder + .add_filter_in_range_clause( + PaymentIntentDimensions::PaymentMethod, + &self.payment_method, + ) + .attach_printable("Error adding payment method filter")?; + } + if !self.payment_method_type.is_empty() { + builder + .add_filter_in_range_clause( + PaymentIntentDimensions::PaymentMethodType, + &self.payment_method_type, + ) + .attach_printable("Error adding payment method type filter")?; + } + if !self.card_network.is_empty() { + builder + .add_filter_in_range_clause( + PaymentIntentDimensions::CardNetwork, + &self.card_network, + ) + .attach_printable("Error adding card network filter")?; + } + if !self.merchant_id.is_empty() { + builder + .add_filter_in_range_clause(PaymentIntentDimensions::MerchantId, &self.merchant_id) + .attach_printable("Error adding merchant id filter")?; + } + if !self.card_last_4.is_empty() { + builder + .add_filter_in_range_clause(PaymentIntentDimensions::CardLast4, &self.card_last_4) + .attach_printable("Error adding card last 4 filter")?; + } + if !self.card_issuer.is_empty() { + builder + .add_filter_in_range_clause(PaymentIntentDimensions::CardIssuer, &self.card_issuer) + .attach_printable("Error adding card issuer filter")?; + } + if !self.error_reason.is_empty() { + builder + .add_filter_in_range_clause( + PaymentIntentDimensions::ErrorReason, + &self.error_reason, + ) + .attach_printable("Error adding error reason filter")?; + } if !self.customer_id.is_empty() { builder .add_filter_in_range_clause("customer_id", &self.customer_id) diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 7c90e37c55f..0a641fbc5f9 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -604,6 +604,45 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let connector: Option<String> = row.try_get("connector").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let payment_method: Option<String> = + row.try_get("payment_method").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let payment_method_type: Option<String> = + row.try_get("payment_method_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -627,6 +666,15 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe status, currency, profile_id, + connector, + authentication_type, + payment_method, + payment_method_type, + card_network, + merchant_id, + card_last_4, + card_issuer, + error_reason, first_attempt, total, count, @@ -652,6 +700,45 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFi ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let connector: Option<String> = row.try_get("connector").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let payment_method: Option<String> = + row.try_get("payment_method").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let payment_method_type: Option<String> = + row.try_get("payment_method_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let customer_id: Option<String> = row.try_get("customer_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -660,6 +747,15 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFi status, currency, profile_id, + connector, + authentication_type, + payment_method, + payment_method_type, + card_network, + merchant_id, + card_last_4, + card_issuer, + error_reason, customer_id, }) } diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index 435e95451fe..fc21bf09819 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -35,6 +35,12 @@ pub fn get_payment_intent_dimensions() -> Vec<NameDescription> { PaymentIntentDimensions::PaymentIntentStatus, PaymentIntentDimensions::Currency, PaymentIntentDimensions::ProfileId, + PaymentIntentDimensions::Connector, + PaymentIntentDimensions::AuthType, + PaymentIntentDimensions::PaymentMethod, + PaymentIntentDimensions::PaymentMethodType, + PaymentIntentDimensions::CardNetwork, + PaymentIntentDimensions::MerchantId, ] .into_iter() .map(Into::into) diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs index 60662f2e90a..ab93fdc4815 100644 --- a/crates/api_models/src/analytics/payment_intents.rs +++ b/crates/api_models/src/analytics/payment_intents.rs @@ -6,7 +6,9 @@ use std::{ use common_utils::id_type; use super::{NameDescription, TimeRange}; -use crate::enums::{Currency, IntentStatus}; +use crate::enums::{ + AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType, +}; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct PaymentIntentFilters { @@ -17,6 +19,24 @@ pub struct PaymentIntentFilters { #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, #[serde(default)] + pub connector: Vec<Connector>, + #[serde(default)] + pub auth_type: Vec<AuthenticationType>, + #[serde(default)] + pub payment_method: Vec<PaymentMethod>, + #[serde(default)] + pub payment_method_type: Vec<PaymentMethodType>, + #[serde(default)] + pub card_network: Vec<String>, + #[serde(default)] + pub merchant_id: Vec<id_type::MerchantId>, + #[serde(default)] + pub card_last_4: Vec<String>, + #[serde(default)] + pub card_issuer: Vec<String>, + #[serde(default)] + pub error_reason: Vec<String>, + #[serde(default)] pub customer_id: Vec<id_type::CustomerId>, } @@ -42,6 +62,15 @@ pub enum PaymentIntentDimensions { PaymentIntentStatus, Currency, ProfileId, + Connector, + AuthType, + PaymentMethod, + PaymentMethodType, + CardNetwork, + MerchantId, + CardLast4, + CardIssuer, + ErrorReason, } #[derive( @@ -112,6 +141,15 @@ pub struct PaymentIntentMetricsBucketIdentifier { pub status: Option<IntentStatus>, pub currency: Option<Currency>, pub profile_id: Option<String>, + pub connector: Option<String>, + pub auth_type: Option<AuthenticationType>, + pub payment_method: Option<String>, + pub payment_method_type: Option<String>, + pub card_network: Option<String>, + pub merchant_id: Option<String>, + pub card_last_4: Option<String>, + pub card_issuer: Option<String>, + pub error_reason: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] @@ -125,12 +163,30 @@ impl PaymentIntentMetricsBucketIdentifier { status: Option<IntentStatus>, currency: Option<Currency>, profile_id: Option<String>, + connector: Option<String>, + auth_type: Option<AuthenticationType>, + payment_method: Option<String>, + payment_method_type: Option<String>, + card_network: Option<String>, + merchant_id: Option<String>, + card_last_4: Option<String>, + card_issuer: Option<String>, + error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { status, currency, profile_id, + connector, + auth_type, + payment_method, + payment_method_type, + card_network, + merchant_id, + card_last_4, + card_issuer, + error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -142,6 +198,15 @@ impl Hash for PaymentIntentMetricsBucketIdentifier { self.status.map(|i| i.to_string()).hash(state); self.currency.hash(state); self.profile_id.hash(state); + self.connector.hash(state); + self.auth_type.map(|i| i.to_string()).hash(state); + self.payment_method.hash(state); + self.payment_method_type.hash(state); + self.card_network.hash(state); + self.merchant_id.hash(state); + self.card_last_4.hash(state); + self.card_issuer.hash(state); + self.error_reason.hash(state); self.time_bucket.hash(state); } }
2024-11-06T11:07:03Z
## Description <!-- Describe your changes in detail --> Reverts [https://github.com/juspay/hyperswitch/pull/6403](https://github.com/juspay/hyperswitch/pull/6403) When global filters are applied on the dashboard, these filters are being sent to both Payment Attempt and Payment Intent related metrics. Initially backend support was not present for capturing these filters and adding to the queries, for Payment Intent related metrics, but for the new Analytics V2 dashboard, since the Sessionizer Tables are being used, all these filter fields are supported in the Sessionizer Payment Intents table. When backend support was added to apply these filters for the new dashboard, the old dashboard started breaking, as the filter fields are not present in the existing Payment Intents table. FE stopped sending these filters to Payment Intent metrics on the old dashboard, and so adding these filters back to PaymentIntentFilters to support the filters on the new Analytics V2 dashboard. The additional filters added: - connector - authentication_type - payment_method - payment_method_type - card_network - merchant_id - card_last_4 - card_issuer - error_reason ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Enable filters for Payment Intent related metrics on the new Analytics V2 dashboard. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDkxNDM0Mywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.Y7RdCF52kfFCUld587axdN5d4Xl7SGK4wv7C-bdDI0M' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-14T18:30:00Z", "endTime": "2024-10-22T15:24:00Z" }, "groupByNames": [ "currency" ], "filters": { "connector": [ "stripe_test" ] }, "timeSeries": { "granularity": "G_ONEDAY" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_total_smart_retries" ] } ]' ``` We should be able to extract the results based on the additional filters that are applied: - connector - authentication_type - payment_method - payment_method_type - card_network - merchant_id - card_last_4 - card_issuer - error_reason
01c5216fdd6f1d841082868cccea6054b64e9e07
Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDkxNDM0Mywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.Y7RdCF52kfFCUld587axdN5d4Xl7SGK4wv7C-bdDI0M' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-14T18:30:00Z", "endTime": "2024-10-22T15:24:00Z" }, "groupByNames": [ "currency" ], "filters": { "connector": [ "stripe_test" ] }, "timeSeries": { "granularity": "G_ONEDAY" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_total_smart_retries" ] } ]' ``` We should be able to extract the results based on the additional filters that are applied: - connector - authentication_type - payment_method - payment_method_type - card_network - merchant_id - card_last_4 - card_issuer - error_reason
[ "crates/analytics/src/payment_intents/core.rs", "crates/analytics/src/payment_intents/filters.rs", "crates/analytics/src/payment_intents/metrics.rs", "crates/analytics/src/payment_intents/metrics/payment_intent_count.rs", "crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs", "crates/analytics/src/payment_intents/metrics/payments_success_rate.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs", "crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs", "crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs", "crates/analytics/src/payment_intents/metrics/total_smart_retries.rs", "crates/analytics/src/payment_intents/types.rs", "crates/analytics/src/sqlx.rs", "crates/analytics/src/utils.rs", "crates/api_models/src/analytics/payment_intents.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6489
Bug: [FEATURE] Add payments update-intent API for v2 Add payments `update-intent` API for v2
diff --git a/api-reference-v2/api-reference/payments/payments--update-intent.mdx b/api-reference-v2/api-reference/payments/payments--update-intent.mdx new file mode 100644 index 00000000000..3ef58f4db72 --- /dev/null +++ b/api-reference-v2/api-reference/payments/payments--update-intent.mdx @@ -0,0 +1,3 @@ +--- +openapi: put /v2/payments/{id}/update-intent +--- \ No newline at end of file diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json index aed89492443..4212b2dbd21 100644 --- a/api-reference-v2/mint.json +++ b/api-reference-v2/mint.json @@ -40,6 +40,7 @@ "pages": [ "api-reference/payments/payments--create-intent", "api-reference/payments/payments--get-intent", + "api-reference/payments/payments--update-intent", "api-reference/payments/payments--session-token", "api-reference/payments/payments--confirm-intent", "api-reference/payments/payments--get" diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 778e89ab30b..64949c3812b 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -1911,6 +1911,79 @@ ] } }, + "/v2/payments/{id}/update-intent": { + "put": { + "tags": [ + "Payments" + ], + "summary": "Payments - Update Intent", + "description": "**Update a payment intent object**\n\nYou will require the 'API - Key' from the Hyperswitch dashboard to make the call.", + "operationId": "Update a Payment Intent", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The unique identifier for the Payment Intent", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "X-Profile-Id", + "in": "header", + "description": "Profile ID associated to the payment intent", + "required": true, + "schema": { + "type": "string" + }, + "example": { + "X-Profile-Id": "pro_abcdefghijklmnop" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsUpdateIntentRequest" + }, + "examples": { + "Update a payment intent with minimal fields": { + "value": { + "amount_details": { + "currency": "USD", + "order_amount": 6540 + } + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Payment Intent Updated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsIntentResponse" + } + } + } + }, + "404": { + "description": "Payment Intent Not Found" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/v2/payments/{id}/confirm-intent": { "post": { "tags": [ @@ -3026,6 +3099,75 @@ } } }, + "AmountDetailsUpdate": { + "type": "object", + "properties": { + "order_amount": { + "type": "integer", + "format": "int64", + "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)", + "example": 6540, + "nullable": true, + "minimum": 0 + }, + "currency": { + "allOf": [ + { + "$ref": "#/components/schemas/Currency" + } + ], + "nullable": true + }, + "shipping_cost": { + "allOf": [ + { + "$ref": "#/components/schemas/MinorUnit" + } + ], + "nullable": true + }, + "order_tax_amount": { + "allOf": [ + { + "$ref": "#/components/schemas/MinorUnit" + } + ], + "nullable": true + }, + "skip_external_tax_calculation": { + "allOf": [ + { + "$ref": "#/components/schemas/TaxCalculationOverride" + } + ], + "nullable": true + }, + "skip_surcharge_calculation": { + "allOf": [ + { + "$ref": "#/components/schemas/SurchargeCalculationOverride" + } + ], + "nullable": true + }, + "surcharge_amount": { + "allOf": [ + { + "$ref": "#/components/schemas/MinorUnit" + } + ], + "nullable": true + }, + "tax_on_surcharge": { + "allOf": [ + { + "$ref": "#/components/schemas/MinorUnit" + } + ], + "nullable": true + } + } + }, "AmountFilter": { "type": "object", "properties": { @@ -15898,6 +16040,176 @@ } } }, + "PaymentsUpdateIntentRequest": { + "type": "object", + "properties": { + "amount_details": { + "allOf": [ + { + "$ref": "#/components/schemas/AmountDetailsUpdate" + } + ], + "nullable": true + }, + "routing_algorithm_id": { + "type": "string", + "description": "The routing algorithm id to be used for the payment", + "nullable": true + }, + "capture_method": { + "allOf": [ + { + "$ref": "#/components/schemas/CaptureMethod" + } + ], + "nullable": true + }, + "authentication_type": { + "allOf": [ + { + "$ref": "#/components/schemas/AuthenticationType" + } + ], + "default": "no_three_ds", + "nullable": true + }, + "billing": { + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], + "nullable": true + }, + "shipping": { + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], + "nullable": true + }, + "customer_present": { + "allOf": [ + { + "$ref": "#/components/schemas/PresenceOfCustomerDuringPayment" + } + ], + "nullable": true + }, + "description": { + "type": "string", + "description": "A description for the payment", + "example": "It's my first payment request", + "nullable": true + }, + "return_url": { + "type": "string", + "description": "The URL to which you want the user to be redirected after the completion of the payment operation", + "example": "https://hyperswitch.io", + "nullable": true + }, + "setup_future_usage": { + "allOf": [ + { + "$ref": "#/components/schemas/FutureUsage" + } + ], + "nullable": true + }, + "apply_mit_exemption": { + "allOf": [ + { + "$ref": "#/components/schemas/MitExemptionRequest" + } + ], + "nullable": true + }, + "statement_descriptor": { + "type": "string", + "description": "For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.", + "example": "Hyperswitch Router", + "nullable": true, + "maxLength": 22 + }, + "order_details": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OrderDetailsWithAmount" + }, + "description": "Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount", + "example": "[{\n \"product_name\": \"Apple iPhone 16\",\n \"quantity\": 1,\n \"amount\" : 69000\n \"product_img_link\" : \"https://dummy-img-link.com\"\n }]", + "nullable": true + }, + "allowed_payment_method_types": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "description": "Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent", + "nullable": true + }, + "metadata": { + "type": "object", + "description": "Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments", + "nullable": true + }, + "connector_metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/ConnectorMetadata" + } + ], + "nullable": true + }, + "feature_metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/FeatureMetadata" + } + ], + "nullable": true + }, + "payment_link_config": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkConfigRequest" + } + ], + "nullable": true + }, + "request_incremental_authorization": { + "allOf": [ + { + "$ref": "#/components/schemas/RequestIncrementalAuthorization" + } + ], + "nullable": true + }, + "session_expiry": { + "type": "integer", + "format": "int32", + "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config\n(900) for 15 mins", + "example": 900, + "nullable": true, + "minimum": 0 + }, + "frm_metadata": { + "type": "object", + "description": "Additional data related to some frm(Fraud Risk Management) connectors", + "nullable": true + }, + "request_external_three_ds_authentication": { + "allOf": [ + { + "$ref": "#/components/schemas/External3dsAuthenticationRequest" + } + ], + "nullable": true + } + }, + "additionalProperties": false + }, "PayoutActionRequest": { "type": "object" }, @@ -17189,10 +17501,10 @@ }, "PresenceOfCustomerDuringPayment": { "type": "string", - "description": "Set to true to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be false when merchant's doing merchant initiated payments and customer is not present while doing the payment.", + "description": "Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.", "enum": [ - "Present", - "Absent" + "present", + "absent" ] }, "PrimaryBusinessDetails": { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 603c0f76934..6a7f7148bd3 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -156,8 +156,8 @@ pub struct PaymentsCreateIntentRequest { #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, - /// Set to true to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be false when merchant's doing merchant initiated payments and customer is not present while doing the payment. - #[schema(example = true, value_type = Option<PresenceOfCustomerDuringPayment>)] + /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. + #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment @@ -297,6 +297,99 @@ pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] +#[serde(deny_unknown_fields)] +#[cfg(feature = "v2")] +pub struct PaymentsUpdateIntentRequest { + pub amount_details: Option<AmountDetailsUpdate>, + + /// The routing algorithm id to be used for the payment + #[schema(value_type = Option<String>)] + pub routing_algorithm_id: Option<id_type::RoutingId>, + + #[schema(value_type = Option<CaptureMethod>, example = "automatic")] + pub capture_method: Option<api_enums::CaptureMethod>, + + #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] + pub authentication_type: Option<api_enums::AuthenticationType>, + + /// The billing details of the payment. This address will be used for invoicing. + pub billing: Option<Address>, + + /// The shipping address for the payment + pub shipping: Option<Address>, + + /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. + #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] + pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, + + /// A description for the payment + #[schema(example = "It's my first payment request", value_type = Option<String>)] + pub description: Option<common_utils::types::Description>, + + /// The URL to which you want the user to be redirected after the completion of the payment operation + #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] + pub return_url: Option<common_utils::types::Url>, + + #[schema(value_type = Option<FutureUsage>, example = "off_session")] + pub setup_future_usage: Option<api_enums::FutureUsage>, + + /// Apply MIT exemption for a payment + #[schema(value_type = Option<MitExemptionRequest>)] + pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, + + /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. + #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] + pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, + + /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount + #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ + "product_name": "Apple iPhone 16", + "quantity": 1, + "amount" : 69000 + "product_img_link" : "https://dummy-img-link.com" + }]"#)] + pub order_details: Option<Vec<OrderDetailsWithAmount>>, + + /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent + #[schema(value_type = Option<Vec<PaymentMethodType>>)] + pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, + + /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments + #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] + pub metadata: Option<pii::SecretSerdeValue>, + + /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. + #[schema(value_type = Option<ConnectorMetadata>)] + pub connector_metadata: Option<pii::SecretSerdeValue>, + + /// Additional data that might be required by hyperswitch based on the requested features by the merchants. + #[schema(value_type = Option<FeatureMetadata>)] + pub feature_metadata: Option<FeatureMetadata>, + + /// Configure a custom payment link for the particular payment + #[schema(value_type = Option<PaymentLinkConfigRequest>)] + pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, + + /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. + #[schema(value_type = Option<RequestIncrementalAuthorization>)] + pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, + + /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config + ///(900) for 15 mins + #[schema(value_type = Option<u32>, example = 900)] + pub session_expiry: Option<u32>, + + /// Additional data related to some frm(Fraud Risk Management) connectors + #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] + pub frm_metadata: Option<pii::SecretSerdeValue>, + + /// Whether to perform external authentication (if applicable) + #[schema(value_type = Option<External3dsAuthenticationRequest>)] + pub request_external_three_ds_authentication: + Option<common_enums::External3dsAuthenticationRequest>, +} + #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] @@ -352,8 +445,8 @@ pub struct PaymentsIntentResponse { #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, - /// Set to true to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be false when merchant's doing merchant initiated payments and customer is not present while doing the payment. - #[schema(example = true, value_type = PresenceOfCustomerDuringPayment)] + /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. + #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment @@ -453,6 +546,32 @@ pub struct AmountDetails { tax_on_surcharge: Option<MinorUnit>, } +#[cfg(feature = "v2")] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct AmountDetailsUpdate { + /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) + #[schema(value_type = Option<u64>, example = 6540)] + #[serde(default, deserialize_with = "amount::deserialize_option")] + order_amount: Option<Amount>, + /// The currency of the order + #[schema(example = "USD", value_type = Option<Currency>)] + currency: Option<common_enums::Currency>, + /// The shipping cost of the order. This has to be collected from the merchant + shipping_cost: Option<MinorUnit>, + /// Tax amount related to the order. This will be calculated by the external tax provider + order_tax_amount: Option<MinorUnit>, + /// The action to whether calculate tax by calling external tax provider or not + #[schema(value_type = Option<TaxCalculationOverride>)] + skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, + /// The action to whether calculate surcharge or not + #[schema(value_type = Option<SurchargeCalculationOverride>)] + skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, + /// The surcharge amount to be added to the order, collected from the merchant + surcharge_amount: Option<MinorUnit>, + /// tax on surcharge amount + tax_on_surcharge: Option<MinorUnit>, +} + #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, @@ -552,10 +671,10 @@ impl AmountDetails { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { - self.skip_external_tax_calculation.clone() + self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { - self.skip_surcharge_calculation.clone() + self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount @@ -565,6 +684,33 @@ impl AmountDetails { } } +#[cfg(feature = "v2")] +impl AmountDetailsUpdate { + pub fn order_amount(&self) -> Option<Amount> { + self.order_amount + } + pub fn currency(&self) -> Option<common_enums::Currency> { + self.currency + } + pub fn shipping_cost(&self) -> Option<MinorUnit> { + self.shipping_cost + } + pub fn order_tax_amount(&self) -> Option<MinorUnit> { + self.order_tax_amount + } + pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { + self.skip_external_tax_calculation + } + pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { + self.skip_surcharge_calculation + } + pub fn surcharge_amount(&self) -> Option<MinorUnit> { + self.surcharge_amount + } + pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { + self.tax_on_surcharge + } +} #[cfg(feature = "v1")] #[derive( Default, diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index c3c876b22aa..6c38172e540 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -3332,8 +3332,9 @@ pub enum MitExemptionRequest { Skip, } -/// Set to true to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be false when merchant's doing merchant initiated payments and customer is not present while doing the payment. +/// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] +#[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value #[default] @@ -3352,7 +3353,9 @@ impl From<ConnectorType> for TransactionType { } } -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] +#[derive( + Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, +)] #[serde(rename_all = "snake_case")] pub enum TaxCalculationOverride { /// Skip calling the external tax provider @@ -3362,7 +3365,27 @@ pub enum TaxCalculationOverride { Calculate, } -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] +impl From<Option<bool>> for TaxCalculationOverride { + fn from(value: Option<bool>) -> Self { + match value { + Some(true) => Self::Calculate, + _ => Self::Skip, + } + } +} + +impl TaxCalculationOverride { + pub fn as_bool(self) -> bool { + match self { + Self::Skip => false, + Self::Calculate => true, + } + } +} + +#[derive( + Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, +)] #[serde(rename_all = "snake_case")] pub enum SurchargeCalculationOverride { /// Skip calculating surcharge @@ -3372,6 +3395,24 @@ pub enum SurchargeCalculationOverride { Calculate, } +impl From<Option<bool>> for SurchargeCalculationOverride { + fn from(value: Option<bool>) -> Self { + match value { + Some(true) => Self::Calculate, + _ => Self::Skip, + } + } +} + +impl SurchargeCalculationOverride { + pub fn as_bool(self) -> bool { + match self { + Self::Skip => false, + Self::Calculate => true, + } + } +} + /// Connector Mandate Status #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs index 7c5c3a8de17..80159271292 100644 --- a/crates/diesel_models/src/kv.rs +++ b/crates/diesel_models/src/kv.rs @@ -3,6 +3,8 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "v2")] use crate::payment_attempt::PaymentAttemptUpdateInternal; +#[cfg(feature = "v1")] +use crate::payment_intent::PaymentIntentUpdate; #[cfg(feature = "v2")] use crate::payment_intent::PaymentIntentUpdateInternal; use crate::{ @@ -10,7 +12,7 @@ use crate::{ customers::{Customer, CustomerNew, CustomerUpdateInternal}, errors, payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate}, - payment_intent::{PaymentIntentNew, PaymentIntentUpdate}, + payment_intent::PaymentIntentNew, payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate}, payouts::{Payouts, PayoutsNew, PayoutsUpdate}, refund::{Refund, RefundNew, RefundUpdate}, @@ -115,11 +117,9 @@ impl DBOperation { DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?)) } #[cfg(feature = "v2")] - Updateable::PaymentIntentUpdate(a) => DBResult::PaymentIntent(Box::new( - a.orig - .update(conn, PaymentIntentUpdateInternal::from(a.update_data)) - .await?, - )), + Updateable::PaymentIntentUpdate(a) => { + DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?)) + } #[cfg(feature = "v1")] Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( a.orig.update_with_attempt_id(conn, a.update_data).await?, @@ -247,13 +247,20 @@ pub struct AddressUpdateMems { pub orig: Address, pub update_data: AddressUpdateInternal, } - +#[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentIntentUpdateMems { pub orig: PaymentIntent, pub update_data: PaymentIntentUpdate, } +#[cfg(feature = "v2")] +#[derive(Debug, Serialize, Deserialize)] +pub struct PaymentIntentUpdateMems { + pub orig: PaymentIntent, + pub update_data: PaymentIntentUpdateInternal, +} + #[derive(Debug, Serialize, Deserialize)] pub struct PaymentAttemptUpdateMems { pub orig: PaymentAttempt, diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 9f0bf17230d..b29da50d0a7 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -140,7 +140,8 @@ pub struct PaymentIntent { pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, } -#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)] +#[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PaymentLinkConfigRequestForPayments { /// custom theme for the payment link pub theme: Option<String>, @@ -359,22 +360,6 @@ pub struct PaymentIntentNew { pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, } -#[cfg(feature = "v2")] -#[derive(Debug, Clone, Serialize, Deserialize)] -pub enum PaymentIntentUpdate { - /// Update the payment intent details on payment intent confirmation, before calling the connector - ConfirmIntent { - status: storage_enums::IntentStatus, - active_attempt_id: common_utils::id_type::GlobalAttemptId, - updated_by: String, - }, - /// Update the payment intent details on payment intent confirmation, after calling the connector - ConfirmIntentPostUpdate { - status: storage_enums::IntentStatus, - updated_by: String, - }, -} - #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { @@ -516,34 +501,42 @@ pub struct PaymentIntentUpdateFields { // TODO: uncomment fields as necessary #[cfg(feature = "v2")] -#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { - // pub amount: Option<MinorUnit>, - // pub currency: Option<storage_enums::Currency>, pub status: Option<storage_enums::IntentStatus>, - // pub amount_captured: Option<MinorUnit>, - // pub customer_id: Option<common_utils::id_type::CustomerId>, - // pub return_url: Option<>, - // pub setup_future_usage: Option<storage_enums::FutureUsage>, - // pub metadata: Option<pii::SecretSerdeValue>, - pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, - // pub description: Option<String>, - // pub statement_descriptor: Option<String>, - // #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] - // pub order_details: Option<Vec<pii::SecretSerdeValue>>, - // pub attempt_count: Option<i16>, + pub modified_at: PrimitiveDateTime, + pub amount: Option<MinorUnit>, + pub currency: Option<storage_enums::Currency>, + pub shipping_cost: Option<MinorUnit>, + pub tax_details: Option<TaxDetails>, + pub skip_external_tax_calculation: Option<bool>, + pub surcharge_applicable: Option<bool>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_on_surcharge: Option<MinorUnit>, + pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, + pub capture_method: Option<common_enums::CaptureMethod>, + pub authentication_type: Option<common_enums::AuthenticationType>, + pub billing_address: Option<Encryption>, + pub shipping_address: Option<Encryption>, + pub customer_present: Option<bool>, + pub description: Option<common_utils::types::Description>, + pub return_url: Option<common_utils::types::Url>, + pub setup_future_usage: Option<storage_enums::FutureUsage>, + pub apply_mit_exemption: Option<bool>, + pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, + pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, + pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, + pub metadata: Option<pii::SecretSerdeValue>, + pub connector_metadata: Option<pii::SecretSerdeValue>, + pub feature_metadata: Option<FeatureMetadata>, + pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, + pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, + pub session_expiry: Option<PrimitiveDateTime>, + pub frm_metadata: Option<pii::SecretSerdeValue>, + pub request_external_three_ds_authentication: Option<bool>, pub updated_by: String, - // pub surcharge_applicable: Option<bool>, - // pub authorization_count: Option<i32>, - // pub session_expiry: Option<PrimitiveDateTime>, - // pub request_external_three_ds_authentication: Option<bool>, - // pub frm_metadata: Option<pii::SecretSerdeValue>, - // pub customer_details: Option<Encryption>, - // pub billing_address: Option<Encryption>, - // pub shipping_address: Option<Encryption>, - // pub frm_merchant_decision: Option<String>, } #[cfg(feature = "v1")] @@ -589,66 +582,6 @@ pub struct PaymentIntentUpdateInternal { pub tax_details: Option<TaxDetails>, } -#[cfg(feature = "v2")] -impl PaymentIntentUpdate { - pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { - let PaymentIntentUpdateInternal { - // amount, - // currency, - status, - // amount_captured, - // customer_id, - // return_url, - // setup_future_usage, - // metadata, - modified_at: _, - active_attempt_id, - // description, - // statement_descriptor, - // order_details, - // attempt_count, - // frm_merchant_decision, - updated_by, - // surcharge_applicable, - // authorization_count, - // session_expiry, - // request_external_three_ds_authentication, - // frm_metadata, - // customer_details, - // billing_address, - // shipping_address, - } = self.into(); - PaymentIntent { - // amount: amount.unwrap_or(source.amount), - // currency: currency.unwrap_or(source.currency), - status: status.unwrap_or(source.status), - // amount_captured: amount_captured.or(source.amount_captured), - // customer_id: customer_id.or(source.customer_id), - // return_url: return_url.or(source.return_url), - // setup_future_usage: setup_future_usage.or(source.setup_future_usage), - // metadata: metadata.or(source.metadata), - modified_at: common_utils::date_time::now(), - active_attempt_id: active_attempt_id.or(source.active_attempt_id), - // description: description.or(source.description), - // statement_descriptor: statement_descriptor.or(source.statement_descriptor), - // order_details: order_details.or(source.order_details), - // attempt_count: attempt_count.unwrap_or(source.attempt_count), - // frm_merchant_decision: frm_merchant_decision.or(source.frm_merchant_decision), - updated_by, - // surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable), - // authorization_count: authorization_count.or(source.authorization_count), - // session_expiry: session_expiry.or(source.session_expiry), - // request_external_three_ds_authentication: request_external_three_ds_authentication - // .or(source.request_external_three_ds_authentication), - // frm_metadata: frm_metadata.or(source.frm_metadata), - // customer_details: customer_details.or(source.customer_details), - // billing_address: billing_address.or(source.billing_address), - // shipping_address: shipping_address.or(source.shipping_address), - ..source - } - } -} - #[cfg(feature = "v1")] impl PaymentIntentUpdate { pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { @@ -739,30 +672,6 @@ impl PaymentIntentUpdate { } } -#[cfg(feature = "v2")] -impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { - fn from(payment_intent_update: PaymentIntentUpdate) -> Self { - match payment_intent_update { - PaymentIntentUpdate::ConfirmIntent { - status, - active_attempt_id, - updated_by, - } => Self { - status: Some(status), - active_attempt_id: Some(active_attempt_id), - modified_at: common_utils::date_time::now(), - updated_by, - }, - PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => Self { - status: Some(status), - active_attempt_id: None, - modified_at: common_utils::date_time::now(), - updated_by, - }, - } - } -} - #[cfg(feature = "v1")] impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fn from(payment_intent_update: PaymentIntentUpdate) -> Self { diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index d94e921c120..31732e13286 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -302,12 +302,8 @@ impl From<api_models::payments::AmountDetails> for payments::AmountDetails { payment_method_type: None, } }), - skip_external_tax_calculation: payments::TaxCalculationOverride::from( - amount_details.skip_external_tax_calculation(), - ), - skip_surcharge_calculation: payments::SurchargeCalculationOverride::from( - amount_details.skip_surcharge_calculation(), - ), + skip_external_tax_calculation: amount_details.skip_external_tax_calculation(), + skip_surcharge_calculation: amount_details.skip_surcharge_calculation(), surcharge_amount: amount_details.surcharge_amount(), tax_on_surcharge: amount_details.tax_on_surcharge(), // We will not receive this in the request. This will be populated after calling the connector / processor @@ -315,23 +311,3 @@ impl From<api_models::payments::AmountDetails> for payments::AmountDetails { } } } - -#[cfg(feature = "v2")] -impl From<common_enums::SurchargeCalculationOverride> for payments::SurchargeCalculationOverride { - fn from(surcharge_calculation_override: common_enums::SurchargeCalculationOverride) -> Self { - match surcharge_calculation_override { - common_enums::SurchargeCalculationOverride::Calculate => Self::Calculate, - common_enums::SurchargeCalculationOverride::Skip => Self::Skip, - } - } -} - -#[cfg(feature = "v2")] -impl From<common_enums::TaxCalculationOverride> for payments::TaxCalculationOverride { - fn from(tax_calculation_override: common_enums::TaxCalculationOverride) -> Self { - match tax_calculation_override { - common_enums::TaxCalculationOverride::Calculate => Self::Calculate, - common_enums::TaxCalculationOverride::Skip => Self::Skip, - } - } -} diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 207668817e3..9e6477fa26b 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -17,6 +17,8 @@ use diesel_models::payment_intent::TaxDetails; #[cfg(feature = "v2")] use error_stack::ResultExt; use masking::Secret; +#[cfg(feature = "v2")] +use payment_intent::PaymentIntentUpdate; use router_derive::ToEncryption; use rustc_hash::FxHashMap; use serde_json::Value; @@ -155,44 +157,6 @@ impl PaymentIntent { } } -#[cfg(feature = "v2")] -#[derive(Clone, Debug, PartialEq, Copy, serde::Serialize)] -pub enum TaxCalculationOverride { - /// Skip calling the external tax provider - Skip, - /// Calculate tax by calling the external tax provider - Calculate, -} - -#[cfg(feature = "v2")] -#[derive(Clone, Debug, PartialEq, Copy, serde::Serialize)] -pub enum SurchargeCalculationOverride { - /// Skip calculating surcharge - Skip, - /// Calculate surcharge - Calculate, -} - -#[cfg(feature = "v2")] -impl From<Option<bool>> for TaxCalculationOverride { - fn from(value: Option<bool>) -> Self { - match value { - Some(true) => Self::Calculate, - _ => Self::Skip, - } - } -} - -#[cfg(feature = "v2")] -impl From<Option<bool>> for SurchargeCalculationOverride { - fn from(value: Option<bool>) -> Self { - match value { - Some(true) => Self::Calculate, - _ => Self::Skip, - } - } -} - #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize)] pub struct AmountDetails { @@ -205,9 +169,9 @@ pub struct AmountDetails { /// Tax details related to the order. This will be calculated by the external tax provider pub tax_details: Option<TaxDetails>, /// The action to whether calculate tax by calling external tax provider or not - pub skip_external_tax_calculation: TaxCalculationOverride, + pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not - pub skip_surcharge_calculation: SurchargeCalculationOverride, + pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount @@ -221,18 +185,12 @@ pub struct AmountDetails { impl AmountDetails { /// Get the action to whether calculate surcharge or not as a boolean value fn get_surcharge_action_as_bool(&self) -> bool { - match self.skip_surcharge_calculation { - SurchargeCalculationOverride::Skip => false, - SurchargeCalculationOverride::Calculate => true, - } + self.skip_surcharge_calculation.as_bool() } /// Get the action to whether calculate external tax or not as a boolean value fn get_external_tax_action_as_bool(&self) -> bool { - match self.skip_external_tax_calculation { - TaxCalculationOverride::Skip => false, - TaxCalculationOverride::Calculate => true, - } + self.skip_external_tax_calculation.as_bool() } /// Calculate the net amount for the order @@ -250,20 +208,22 @@ impl AmountDetails { let net_amount = self.calculate_net_amount(); let surcharge_amount = match self.skip_surcharge_calculation { - SurchargeCalculationOverride::Skip => self.surcharge_amount, - SurchargeCalculationOverride::Calculate => None, + common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount, + common_enums::SurchargeCalculationOverride::Calculate => None, }; let tax_on_surcharge = match self.skip_surcharge_calculation { - SurchargeCalculationOverride::Skip => self.tax_on_surcharge, - SurchargeCalculationOverride::Calculate => None, + common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge, + common_enums::SurchargeCalculationOverride::Calculate => None, }; let order_tax_amount = match self.skip_external_tax_calculation { - TaxCalculationOverride::Skip => self.tax_details.as_ref().and_then(|tax_details| { - tax_details.get_tax_amount(confirm_intent_request.payment_method_subtype) - }), - TaxCalculationOverride::Calculate => None, + common_enums::TaxCalculationOverride::Skip => { + self.tax_details.as_ref().and_then(|tax_details| { + tax_details.get_tax_amount(confirm_intent_request.payment_method_subtype) + }) + } + common_enums::TaxCalculationOverride::Calculate => None, }; payment_attempt::AttemptAmountDetails { @@ -277,6 +237,33 @@ impl AmountDetails { order_tax_amount, } } + + pub fn update_from_request(self, req: &api_models::payments::AmountDetailsUpdate) -> Self { + Self { + order_amount: req + .order_amount() + .unwrap_or(self.order_amount.into()) + .into(), + currency: req.currency().unwrap_or(self.currency), + shipping_cost: req.shipping_cost().or(self.shipping_cost), + tax_details: req + .order_tax_amount() + .map(|order_tax_amount| TaxDetails { + default: Some(diesel_models::DefaultTax { order_tax_amount }), + payment_method_type: None, + }) + .or(self.tax_details), + skip_external_tax_calculation: req + .skip_external_tax_calculation() + .unwrap_or(self.skip_external_tax_calculation), + skip_surcharge_calculation: req + .skip_surcharge_calculation() + .unwrap_or(self.skip_surcharge_calculation), + surcharge_amount: req.surcharge_amount().or(self.surcharge_amount), + tax_on_surcharge: req.tax_on_surcharge().or(self.tax_on_surcharge), + amount_captured: self.amount_captured, + } + } } #[cfg(feature = "v2")] diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index b0ffe519d63..9b6b6fe5572 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1,4 +1,3 @@ -use common_enums as storage_enums; #[cfg(feature = "v2")] use common_utils::ext_traits::{Encode, ValueExt}; use common_utils::{ @@ -14,8 +13,6 @@ use common_utils::{ MinorUnit, }, }; -#[cfg(feature = "v2")] -use diesel_models::types::OrderDetailsWithAmount; use diesel_models::{ PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew, }; @@ -29,6 +26,8 @@ use time::PrimitiveDateTime; #[cfg(all(feature = "v1", feature = "olap"))] use super::payment_attempt::PaymentAttempt; use super::PaymentIntent; +#[cfg(feature = "v2")] +use crate::address::Address; use crate::{ behaviour, errors, merchant_key_store::MerchantKeyStore, @@ -44,7 +43,7 @@ pub trait PaymentIntentInterface { this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, - storage_scheme: storage_enums::MerchantStorageScheme, + storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, errors::StorageError>; async fn insert_payment_intent( @@ -52,7 +51,7 @@ pub trait PaymentIntentInterface { state: &KeyManagerState, new: PaymentIntent, merchant_key_store: &MerchantKeyStore, - storage_scheme: storage_enums::MerchantStorageScheme, + storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, errors::StorageError>; #[cfg(feature = "v1")] @@ -62,7 +61,7 @@ pub trait PaymentIntentInterface { payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, merchant_key_store: &MerchantKeyStore, - storage_scheme: storage_enums::MerchantStorageScheme, + storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, errors::StorageError>; #[cfg(feature = "v2")] @@ -71,7 +70,7 @@ pub trait PaymentIntentInterface { state: &KeyManagerState, id: &id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, - storage_scheme: storage_enums::MerchantStorageScheme, + storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] @@ -81,7 +80,7 @@ pub trait PaymentIntentInterface { merchant_id: &id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, - storage_scheme: storage_enums::MerchantStorageScheme, + storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] @@ -91,7 +90,7 @@ pub trait PaymentIntentInterface { merchant_id: &id_type::MerchantId, time_range: &common_utils::types::TimeRange, merchant_key_store: &MerchantKeyStore, - storage_scheme: storage_enums::MerchantStorageScheme, + storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] @@ -109,7 +108,7 @@ pub trait PaymentIntentInterface { merchant_id: &id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, - storage_scheme: storage_enums::MerchantStorageScheme, + storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] @@ -117,7 +116,7 @@ pub trait PaymentIntentInterface { &self, merchant_id: &id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, - storage_scheme: storage_enums::MerchantStorageScheme, + storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<String>, errors::StorageError>; } @@ -133,39 +132,52 @@ pub struct CustomerData { #[derive(Debug, Clone, Serialize)] pub struct PaymentIntentUpdateFields { pub amount: Option<MinorUnit>, - pub currency: Option<storage_enums::Currency>, - pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub status: storage_enums::IntentStatus, - pub customer_id: Option<id_type::CustomerId>, - pub shipping_address: Option<Encryptable<Secret<serde_json::Value>>>, - pub billing_address: Option<Encryptable<Secret<serde_json::Value>>>, - pub return_url: Option<String>, - pub description: Option<String>, - pub statement_descriptor: Option<String>, - pub order_details: Option<Vec<pii::SecretSerdeValue>>, + pub currency: Option<common_enums::Currency>, + pub shipping_cost: Option<MinorUnit>, + pub tax_details: Option<diesel_models::TaxDetails>, + pub skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, + pub skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_on_surcharge: Option<MinorUnit>, + pub routing_algorithm_id: Option<id_type::RoutingId>, + pub capture_method: Option<common_enums::CaptureMethod>, + pub authentication_type: Option<common_enums::AuthenticationType>, + pub billing_address: Option<Encryptable<Address>>, + pub shipping_address: Option<Encryptable<Address>>, + pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, + pub description: Option<common_utils::types::Description>, + pub return_url: Option<common_utils::types::Url>, + pub setup_future_usage: Option<common_enums::FutureUsage>, + pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, + pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, + pub order_details: Option<Vec<Secret<diesel_models::types::OrderDetailsWithAmount>>>, + pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, pub metadata: Option<pii::SecretSerdeValue>, - pub payment_confirm_source: Option<storage_enums::PaymentSource>, - pub updated_by: String, + pub connector_metadata: Option<pii::SecretSerdeValue>, + pub feature_metadata: Option<diesel_models::types::FeatureMetadata>, + pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>, + pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, pub session_expiry: Option<PrimitiveDateTime>, - pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, - pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, - pub merchant_order_reference_id: Option<String>, - pub is_payment_processor_token_flow: Option<bool>, + pub request_external_three_ds_authentication: + Option<common_enums::External3dsAuthenticationRequest>, + + // updated_by is set internally, field not present in request + pub updated_by: String, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, - pub currency: storage_enums::Currency, - pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub status: storage_enums::IntentStatus, + pub currency: common_enums::Currency, + pub setup_future_usage: Option<common_enums::FutureUsage>, + pub status: common_enums::IntentStatus, pub customer_id: Option<id_type::CustomerId>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub return_url: Option<String>, - pub business_country: Option<storage_enums::CountryAlpha2>, + pub business_country: Option<common_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, @@ -173,7 +185,7 @@ pub struct PaymentIntentUpdateFields { pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<serde_json::Value>, pub frm_metadata: Option<pii::SecretSerdeValue>, - pub payment_confirm_source: Option<storage_enums::PaymentSource>, + pub payment_confirm_source: Option<common_enums::PaymentSource>, pub updated_by: String, pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, @@ -190,7 +202,7 @@ pub struct PaymentIntentUpdateFields { #[derive(Debug, Clone, Serialize)] pub enum PaymentIntentUpdate { ResponseUpdate { - status: storage_enums::IntentStatus, + status: common_enums::IntentStatus, amount_captured: Option<MinorUnit>, return_url: Option<String>, updated_by: String, @@ -204,7 +216,7 @@ pub enum PaymentIntentUpdate { Update(Box<PaymentIntentUpdateFields>), PaymentCreateUpdate { return_url: Option<String>, - status: Option<storage_enums::IntentStatus>, + status: Option<common_enums::IntentStatus>, customer_id: Option<id_type::CustomerId>, shipping_address_id: Option<String>, billing_address_id: Option<String>, @@ -212,13 +224,13 @@ pub enum PaymentIntentUpdate { updated_by: String, }, MerchantStatusUpdate { - status: storage_enums::IntentStatus, + status: common_enums::IntentStatus, shipping_address_id: Option<String>, billing_address_id: Option<String>, updated_by: String, }, PGStatusUpdate { - status: storage_enums::IntentStatus, + status: common_enums::IntentStatus, incremental_authorization_allowed: Option<bool>, updated_by: String, }, @@ -228,18 +240,18 @@ pub enum PaymentIntentUpdate { updated_by: String, }, StatusAndAttemptUpdate { - status: storage_enums::IntentStatus, + status: common_enums::IntentStatus, active_attempt_id: String, attempt_count: i16, updated_by: String, }, ApproveUpdate { - status: storage_enums::IntentStatus, + status: common_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, RejectUpdate { - status: storage_enums::IntentStatus, + status: common_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, @@ -257,7 +269,7 @@ pub enum PaymentIntentUpdate { shipping_address_id: Option<String>, }, ManualUpdate { - status: Option<storage_enums::IntentStatus>, + status: Option<common_enums::IntentStatus>, updated_by: String, }, SessionResponseUpdate { @@ -273,72 +285,41 @@ pub enum PaymentIntentUpdate { pub enum PaymentIntentUpdate { /// PreUpdate tracker of ConfirmIntent ConfirmIntent { - status: storage_enums::IntentStatus, + status: common_enums::IntentStatus, active_attempt_id: id_type::GlobalAttemptId, updated_by: String, }, /// PostUpdate tracker of ConfirmIntent ConfirmIntentPostUpdate { - status: storage_enums::IntentStatus, + status: common_enums::IntentStatus, updated_by: String, }, /// SyncUpdate of ConfirmIntent in PostUpdateTrackers SyncUpdate { - status: storage_enums::IntentStatus, + status: common_enums::IntentStatus, updated_by: String, }, -} - -#[cfg(feature = "v2")] -#[derive(Clone, Debug, Default)] -pub struct PaymentIntentUpdateInternal { - pub amount: Option<MinorUnit>, - pub currency: Option<storage_enums::Currency>, - pub status: Option<storage_enums::IntentStatus>, - pub amount_captured: Option<MinorUnit>, - pub customer_id: Option<id_type::CustomerId>, - pub return_url: Option<String>, - pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub off_session: Option<bool>, - pub metadata: Option<pii::SecretSerdeValue>, - pub modified_at: Option<PrimitiveDateTime>, - pub active_attempt_id: Option<id_type::GlobalAttemptId>, - pub description: Option<String>, - pub statement_descriptor: Option<String>, - pub order_details: Option<Vec<pii::SecretSerdeValue>>, - pub attempt_count: Option<i16>, - pub frm_merchant_decision: Option<common_enums::MerchantDecision>, - pub payment_confirm_source: Option<storage_enums::PaymentSource>, - pub updated_by: String, - pub surcharge_applicable: Option<bool>, - pub authorization_count: Option<i32>, - pub session_expiry: Option<PrimitiveDateTime>, - pub request_external_three_ds_authentication: Option<bool>, - pub frm_metadata: Option<pii::SecretSerdeValue>, - pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, - pub billing_address: Option<Encryptable<Secret<serde_json::Value>>>, - pub shipping_address: Option<Encryptable<Secret<serde_json::Value>>>, - pub merchant_order_reference_id: Option<String>, - pub is_payment_processor_token_flow: Option<bool>, + /// UpdateIntent + UpdateIntent(Box<PaymentIntentUpdateFields>), } #[cfg(feature = "v1")] #[derive(Clone, Debug, Default)] pub struct PaymentIntentUpdateInternal { pub amount: Option<MinorUnit>, - pub currency: Option<storage_enums::Currency>, - pub status: Option<storage_enums::IntentStatus>, + pub currency: Option<common_enums::Currency>, + pub status: Option<common_enums::IntentStatus>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<id_type::CustomerId>, pub return_url: Option<String>, - pub setup_future_usage: Option<storage_enums::FutureUsage>, + pub setup_future_usage: Option<common_enums::FutureUsage>, pub off_session: Option<bool>, pub metadata: Option<serde_json::Value>, pub billing_address_id: Option<String>, pub shipping_address_id: Option<String>, pub modified_at: Option<PrimitiveDateTime>, pub active_attempt_id: Option<String>, - pub business_country: Option<storage_enums::CountryAlpha2>, + pub business_country: Option<common_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, @@ -348,7 +329,7 @@ pub struct PaymentIntentUpdateInternal { // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, - pub payment_confirm_source: Option<storage_enums::PaymentSource>, + pub payment_confirm_source: Option<common_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, @@ -379,49 +360,185 @@ impl From<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal { status: Some(status), active_attempt_id: Some(active_attempt_id), modified_at: common_utils::date_time::now(), + amount: None, + currency: None, + shipping_cost: None, + tax_details: None, + skip_external_tax_calculation: None, + surcharge_applicable: None, + surcharge_amount: None, + tax_on_surcharge: None, + routing_algorithm_id: None, + capture_method: None, + authentication_type: None, + billing_address: None, + shipping_address: None, + customer_present: None, + description: None, + return_url: None, + setup_future_usage: None, + apply_mit_exemption: None, + statement_descriptor: None, + order_details: None, + allowed_payment_method_types: None, + metadata: None, + connector_metadata: None, + feature_metadata: None, + payment_link_config: None, + request_incremental_authorization: None, + session_expiry: None, + frm_metadata: None, + request_external_three_ds_authentication: None, updated_by, }, + PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => Self { status: Some(status), active_attempt_id: None, modified_at: common_utils::date_time::now(), + amount: None, + currency: None, + shipping_cost: None, + tax_details: None, + skip_external_tax_calculation: None, + surcharge_applicable: None, + surcharge_amount: None, + tax_on_surcharge: None, + routing_algorithm_id: None, + capture_method: None, + authentication_type: None, + billing_address: None, + shipping_address: None, + customer_present: None, + description: None, + return_url: None, + setup_future_usage: None, + apply_mit_exemption: None, + statement_descriptor: None, + order_details: None, + allowed_payment_method_types: None, + metadata: None, + connector_metadata: None, + feature_metadata: None, + payment_link_config: None, + request_incremental_authorization: None, + session_expiry: None, + frm_metadata: None, + request_external_three_ds_authentication: None, updated_by, }, PaymentIntentUpdate::SyncUpdate { status, updated_by } => Self { status: Some(status), active_attempt_id: None, modified_at: common_utils::date_time::now(), + amount: None, + currency: None, + shipping_cost: None, + tax_details: None, + skip_external_tax_calculation: None, + surcharge_applicable: None, + surcharge_amount: None, + tax_on_surcharge: None, + routing_algorithm_id: None, + capture_method: None, + authentication_type: None, + billing_address: None, + shipping_address: None, + customer_present: None, + description: None, + return_url: None, + setup_future_usage: None, + apply_mit_exemption: None, + statement_descriptor: None, + order_details: None, + allowed_payment_method_types: None, + metadata: None, + connector_metadata: None, + feature_metadata: None, + payment_link_config: None, + request_incremental_authorization: None, + session_expiry: None, + frm_metadata: None, + request_external_three_ds_authentication: None, updated_by, }, - } - } -} + PaymentIntentUpdate::UpdateIntent(boxed_intent) => { + let PaymentIntentUpdateFields { + amount, + currency, + shipping_cost, + tax_details, + skip_external_tax_calculation, + skip_surcharge_calculation, + surcharge_amount, + tax_on_surcharge, + routing_algorithm_id, + capture_method, + authentication_type, + billing_address, + shipping_address, + customer_present, + description, + return_url, + setup_future_usage, + apply_mit_exemption, + statement_descriptor, + order_details, + allowed_payment_method_types, + metadata, + connector_metadata, + feature_metadata, + payment_link_config, + request_incremental_authorization, + session_expiry, + frm_metadata, + request_external_three_ds_authentication, + updated_by, + } = *boxed_intent; + Self { + status: None, + active_attempt_id: None, + modified_at: common_utils::date_time::now(), -// This conversion is required for the `apply_changeset` function used for mockdb -#[cfg(feature = "v2")] -impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { - fn from(payment_intent_update: PaymentIntentUpdate) -> Self { - match payment_intent_update { - PaymentIntentUpdate::ConfirmIntent { - status, - active_attempt_id, - updated_by, - } => Self { - status: Some(status), - active_attempt_id: Some(active_attempt_id), - updated_by, - ..Default::default() - }, - PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => Self { - status: Some(status), - updated_by, - ..Default::default() - }, - PaymentIntentUpdate::SyncUpdate { status, updated_by } => Self { - status: Some(status), - updated_by, - ..Default::default() - }, + amount, + currency, + shipping_cost, + tax_details, + skip_external_tax_calculation: skip_external_tax_calculation + .map(|val| val.as_bool()), + surcharge_applicable: skip_surcharge_calculation.map(|val| val.as_bool()), + surcharge_amount, + tax_on_surcharge, + routing_algorithm_id, + capture_method, + authentication_type, + billing_address: billing_address.map(Encryption::from), + shipping_address: shipping_address.map(Encryption::from), + customer_present: customer_present.map(|val| val.as_bool()), + description, + return_url, + setup_future_usage, + apply_mit_exemption: apply_mit_exemption.map(|val| val.as_bool()), + statement_descriptor, + order_details, + allowed_payment_method_types: allowed_payment_method_types + .map(|allowed_payment_method_types| { + allowed_payment_method_types.encode_to_value() + }) + .and_then(|r| r.ok().map(Secret::new)), + metadata, + connector_metadata, + feature_metadata, + payment_link_config, + request_incremental_authorization, + session_expiry, + frm_metadata, + request_external_three_ds_authentication: + request_external_three_ds_authentication.map(|val| val.as_bool()), + + updated_by, + } + } } } } @@ -623,6 +740,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { } } +#[cfg(feature = "v1")] use diesel_models::{ PaymentIntentUpdate as DieselPaymentIntentUpdate, PaymentIntentUpdateFields as DieselPaymentIntentUpdateFields, @@ -814,75 +932,6 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { } } -// TODO: evaluate if we will be using the same update struct for v2 as well, uncomment this and make necessary changes if necessary -#[cfg(feature = "v2")] -impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInternal { - fn from(value: PaymentIntentUpdateInternal) -> Self { - todo!() - // let modified_at = common_utils::date_time::now(); - // let PaymentIntentUpdateInternal { - // amount, - // currency, - // status, - // amount_captured, - // customer_id, - // return_url, - // setup_future_usage, - // off_session, - // metadata, - // modified_at: _, - // active_attempt_id, - // description, - // statement_descriptor, - // order_details, - // attempt_count, - // frm_merchant_decision, - // payment_confirm_source, - // updated_by, - // surcharge_applicable, - // authorization_count, - // session_expiry, - // request_external_three_ds_authentication, - // frm_metadata, - // customer_details, - // billing_address, - // merchant_order_reference_id, - // shipping_address, - // is_payment_processor_token_flow, - // } = value; - // Self { - // amount, - // currency, - // status, - // amount_captured, - // customer_id, - // return_url, - // setup_future_usage, - // off_session, - // metadata, - // modified_at, - // active_attempt_id, - // description, - // statement_descriptor, - // order_details, - // attempt_count, - // frm_merchant_decision, - // payment_confirm_source, - // updated_by, - // surcharge_applicable, - // authorization_count, - // session_expiry, - // request_external_three_ds_authentication, - // frm_metadata, - // customer_details: customer_details.map(Encryption::from), - // billing_address: billing_address.map(Encryption::from), - // merchant_order_reference_id, - // shipping_address: shipping_address.map(Encryption::from), - // is_payment_processor_token_flow, - // } - } -} - #[cfg(feature = "v1")] impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInternal { fn from(value: PaymentIntentUpdateInternal) -> Self { @@ -989,11 +1038,11 @@ pub struct PaymentIntentListParams { pub ending_at: Option<PrimitiveDateTime>, pub amount_filter: Option<api_models::payments::AmountFilter>, pub connector: Option<Vec<api_models::enums::Connector>>, - pub currency: Option<Vec<storage_enums::Currency>>, - pub status: Option<Vec<storage_enums::IntentStatus>>, - pub payment_method: Option<Vec<storage_enums::PaymentMethod>>, - pub payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>, - pub authentication_type: Option<Vec<storage_enums::AuthenticationType>>, + pub currency: Option<Vec<common_enums::Currency>>, + pub status: Option<Vec<common_enums::IntentStatus>>, + pub payment_method: Option<Vec<common_enums::PaymentMethod>>, + pub payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, + pub authentication_type: Option<Vec<common_enums::AuthenticationType>>, pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, pub profile_id: Option<Vec<id_type::ProfileId>>, pub customer_id: Option<id_type::CustomerId>, @@ -1001,7 +1050,7 @@ pub struct PaymentIntentListParams { pub ending_before_id: Option<id_type::PaymentId>, pub limit: Option<u32>, pub order: api_models::payments::Order, - pub card_network: Option<Vec<storage_enums::CardNetwork>>, + pub card_network: Option<Vec<common_enums::CardNetwork>>, pub merchant_order_reference_id: Option<String>, } @@ -1328,10 +1377,10 @@ impl behaviour::Conversion for PaymentIntent { tax_on_surcharge: storage_model.tax_on_surcharge, shipping_cost: storage_model.shipping_cost, tax_details: storage_model.tax_details, - skip_external_tax_calculation: super::TaxCalculationOverride::from( + skip_external_tax_calculation: common_enums::TaxCalculationOverride::from( storage_model.skip_external_tax_calculation, ), - skip_surcharge_calculation: super::SurchargeCalculationOverride::from( + skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::from( storage_model.surcharge_applicable, ), amount_captured: storage_model.amount_captured, @@ -1396,10 +1445,9 @@ impl behaviour::Conversion for PaymentIntent { .unwrap_or_default(), authorization_count: storage_model.authorization_count, session_expiry: storage_model.session_expiry, - request_external_three_ds_authentication: - common_enums::External3dsAuthenticationRequest::from( - storage_model.request_external_three_ds_authentication, - ), + request_external_three_ds_authentication: storage_model + .request_external_three_ds_authentication + .into(), frm_metadata: storage_model.frm_metadata, customer_details: data.customer_details, billing_address, @@ -1410,15 +1458,9 @@ impl behaviour::Conversion for PaymentIntent { organization_id: storage_model.organization_id, authentication_type: storage_model.authentication_type.unwrap_or_default(), prerouting_algorithm: storage_model.prerouting_algorithm, - enable_payment_link: common_enums::EnablePaymentLinkRequest::from( - storage_model.enable_payment_link, - ), - apply_mit_exemption: common_enums::MitExemptionRequest::from( - storage_model.apply_mit_exemption, - ), - customer_present: common_enums::PresenceOfCustomerDuringPayment::from( - storage_model.customer_present, - ), + enable_payment_link: storage_model.enable_payment_link.into(), + apply_mit_exemption: storage_model.apply_mit_exemption.into(), + customer_present: storage_model.customer_present.into(), payment_link_config: storage_model.payment_link_config, routing_algorithm_id: storage_model.routing_algorithm_id, }) diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs index c43d72ce8de..bbe1a65de86 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs @@ -62,5 +62,8 @@ pub struct PaymentCreateIntent; #[derive(Debug, Clone)] pub struct PaymentGetIntent; +#[derive(Debug, Clone)] +pub struct PaymentUpdateIntent; + #[derive(Debug, Clone)] pub struct PostSessionTokens; diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 2221055be5a..ba2975349c0 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -124,6 +124,7 @@ Never share your secret api keys. Keep them guarded and secure. //Routes for payments routes::payments::payments_create_intent, routes::payments::payments_get_intent, + routes::payments::payments_update_intent, routes::payments::payments_confirm_intent, routes::payments::payment_status, @@ -353,9 +354,11 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsSessionRequest, api_models::payments::PaymentsSessionResponse, api_models::payments::PaymentsCreateIntentRequest, + api_models::payments::PaymentsUpdateIntentRequest, api_models::payments::PaymentsIntentResponse, api_models::payments::PazeWalletData, api_models::payments::AmountDetails, + api_models::payments::AmountDetailsUpdate, api_models::payments::SessionToken, api_models::payments::ApplePaySessionResponse, api_models::payments::ThirdPartySdkSessionResponse, diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index 4c9d069a458..927f4e69e3a 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -646,6 +646,43 @@ pub fn payments_create_intent() {} )] #[cfg(feature = "v2")] pub fn payments_get_intent() {} + +/// Payments - Update Intent +/// +/// **Update a payment intent object** +/// +/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call. +#[utoipa::path( + put, + path = "/v2/payments/{id}/update-intent", + params (("id" = String, Path, description = "The unique identifier for the Payment Intent"), + ( + "X-Profile-Id" = String, Header, + description = "Profile ID associated to the payment intent", + example = json!({"X-Profile-Id": "pro_abcdefghijklmnop"}) + ), + ), + request_body( + content = PaymentsUpdateIntentRequest, + examples( + ( + "Update a payment intent with minimal fields" = ( + value = json!({"amount_details": {"order_amount": 6540, "currency": "USD"}}) + ) + ), + ), + ), + responses( + (status = 200, description = "Payment Intent Updated", body = PaymentsIntentResponse), + (status = 404, description = "Payment Intent Not Found") + ), + tag = "Payments", + operation_id = "Update a Payment Intent", + security(("api_key" = [])), +)] +#[cfg(feature = "v2")] +pub fn payments_update_intent() {} + /// Payments - Confirm Intent /// /// **Confirms a payment intent object with the payment method data** diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 99b0a635400..dea0ca35123 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1001,12 +1001,13 @@ where #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn payments_intent_operation_core<F, Req, Op, D>( state: &SessionState, - _req_state: ReqState, + req_state: ReqState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, operation: Op, req: Req, + payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, ) -> RouterResult<(D, Req, Option<domain::Customer>)> where @@ -1023,8 +1024,6 @@ where .to_validate_request()? .validate_request(&req, &merchant_account)?; - let payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id.clone()); - tracing::Span::current().record("global_payment_id", payment_id.get_string_repr()); let operations::GetTrackerResponse { mut payment_data } = operation @@ -1051,6 +1050,22 @@ where .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("Failed while fetching/creating customer")?; + + let (_operation, payment_data) = operation + .to_update_tracker()? + .update_trackers( + state, + req_state, + payment_data, + customer.clone(), + merchant_account.storage_scheme, + None, + &key_store, + None, + header_payload, + ) + .await?; + Ok((payment_data, req, customer)) } @@ -1436,6 +1451,7 @@ pub async fn payments_intent_core<F, Res, Req, Op, D>( key_store: domain::MerchantKeyStore, operation: Op, req: Req, + payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, ) -> RouterResponse<Res> where @@ -1453,6 +1469,7 @@ where key_store, operation.clone(), req, + payment_id, header_payload.clone(), ) .await?; diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 5cdfff60b45..f957b939acf 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -36,6 +36,8 @@ pub mod payment_confirm_intent; pub mod payment_create_intent; #[cfg(feature = "v2")] pub mod payment_get_intent; +#[cfg(feature = "v2")] +pub mod payment_update_intent; #[cfg(feature = "v2")] pub mod payment_get; @@ -52,6 +54,8 @@ pub use self::payment_get::PaymentGet; #[cfg(feature = "v2")] pub use self::payment_get_intent::PaymentGetIntent; pub use self::payment_response::PaymentResponse; +#[cfg(feature = "v2")] +pub use self::payment_update_intent::PaymentUpdateIntent; #[cfg(feature = "v1")] pub use self::{ payment_approve::PaymentApprove, payment_cancel::PaymentCancel, diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs new file mode 100644 index 00000000000..f8ce03d558e --- /dev/null +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -0,0 +1,447 @@ +use std::marker::PhantomData; + +use api_models::{enums::FrmSuggestion, payments::PaymentsUpdateIntentRequest}; +use async_trait::async_trait; +use common_utils::{ + errors::CustomResult, + ext_traits::{Encode, ValueExt}, + types::keymanager::ToEncryptable, +}; +use diesel_models::types::FeatureMetadata; +use error_stack::ResultExt; +use hyperswitch_domain_models::{ + payments::payment_intent::{PaymentIntentUpdate, PaymentIntentUpdateFields}, + ApiModelToDieselModelConvertor, +}; +use masking::PeekInterface; +use router_env::{instrument, tracing}; + +use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; +use crate::{ + core::{ + errors::{self, RouterResult}, + payments::{ + self, + operations::{self, ValidateStatusForOperation}, + }, + }, + db::errors::StorageErrorExt, + routes::{app::ReqState, SessionState}, + types::{ + api, + domain::{self, types as domain_types}, + storage::{self, enums}, + }, +}; + +#[derive(Debug, Clone, Copy)] +pub struct PaymentUpdateIntent; + +impl ValidateStatusForOperation for PaymentUpdateIntent { + /// Validate if the current operation can be performed on the current status of the payment intent + fn validate_status_for_operation( + &self, + intent_status: common_enums::IntentStatus, + ) -> Result<(), errors::ApiErrorResponse> { + match intent_status { + common_enums::IntentStatus::RequiresPaymentMethod => Ok(()), + common_enums::IntentStatus::Succeeded + | common_enums::IntentStatus::Failed + | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::Processing + | common_enums::IntentStatus::RequiresCustomerAction + | common_enums::IntentStatus::RequiresMerchantAction + | common_enums::IntentStatus::RequiresCapture + | common_enums::IntentStatus::PartiallyCaptured + | common_enums::IntentStatus::RequiresConfirmation + | common_enums::IntentStatus::PartiallyCapturedAndCapturable => { + Err(errors::ApiErrorResponse::PaymentUnexpectedState { + current_flow: format!("{self:?}"), + field_name: "status".to_string(), + current_value: intent_status.to_string(), + states: ["requires_payment_method".to_string()].join(", "), + }) + } + } + } +} + +impl<F: Send + Clone> Operation<F, PaymentsUpdateIntentRequest> for &PaymentUpdateIntent { + type Data = payments::PaymentIntentData<F>; + fn to_validate_request( + &self, + ) -> RouterResult< + &(dyn ValidateRequest<F, PaymentsUpdateIntentRequest, Self::Data> + Send + Sync), + > { + Ok(*self) + } + fn to_get_tracker( + &self, + ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)> + { + Ok(*self) + } + fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsUpdateIntentRequest, Self::Data>)> { + Ok(*self) + } + fn to_update_tracker( + &self, + ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)> + { + Ok(*self) + } +} + +impl<F: Send + Clone> Operation<F, PaymentsUpdateIntentRequest> for PaymentUpdateIntent { + type Data = payments::PaymentIntentData<F>; + fn to_validate_request( + &self, + ) -> RouterResult< + &(dyn ValidateRequest<F, PaymentsUpdateIntentRequest, Self::Data> + Send + Sync), + > { + Ok(self) + } + fn to_get_tracker( + &self, + ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)> + { + Ok(self) + } + fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsUpdateIntentRequest, Self::Data>> { + Ok(self) + } + fn to_update_tracker( + &self, + ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)> + { + Ok(self) + } +} + +type PaymentsUpdateIntentOperation<'b, F> = + BoxedOperation<'b, F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>; + +#[async_trait] +impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateIntentRequest> + for PaymentUpdateIntent +{ + #[instrument(skip_all)] + async fn get_trackers<'a>( + &'a self, + state: &'a SessionState, + payment_id: &common_utils::id_type::GlobalPaymentId, + request: &PaymentsUpdateIntentRequest, + merchant_account: &domain::MerchantAccount, + _profile: &domain::Profile, + key_store: &domain::MerchantKeyStore, + _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> { + let db = &*state.store; + let key_manager_state = &state.into(); + let storage_scheme = merchant_account.storage_scheme; + let payment_intent = db + .find_payment_intent_by_id(key_manager_state, payment_id, key_store, storage_scheme) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + self.validate_status_for_operation(payment_intent.status)?; + + let PaymentsUpdateIntentRequest { + amount_details, + routing_algorithm_id, + capture_method, + authentication_type, + billing, + shipping, + customer_present, + description, + return_url, + setup_future_usage, + apply_mit_exemption, + statement_descriptor, + order_details, + allowed_payment_method_types, + metadata, + connector_metadata, + feature_metadata, + payment_link_config, + request_incremental_authorization, + session_expiry, + frm_metadata, + request_external_three_ds_authentication, + } = request.clone(); + + let batch_encrypted_data = domain_types::crypto_operation( + key_manager_state, + common_utils::type_name!(hyperswitch_domain_models::payments::PaymentIntent), + domain_types::CryptoOperation::BatchEncrypt( + hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::to_encryptable( + hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent { + shipping_address: shipping.map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode shipping address")?.map(masking::Secret::new), + billing_address: billing.map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode billing address")?.map(masking::Secret::new), + customer_details: None, + }, + ), + ), + common_utils::types::keymanager::Identifier::Merchant(merchant_account.get_id().to_owned()), + key_store.key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encrypting payment intent details".to_string())?; + + let decrypted_payment_intent = + hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::from_encryptable(batch_encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encrypting payment intent details")?; + + let order_details = order_details.clone().map(|order_details| { + order_details + .into_iter() + .map(|order_detail| { + masking::Secret::new( + diesel_models::types::OrderDetailsWithAmount::convert_from(order_detail), + ) + }) + .collect() + }); + + let session_expiry = session_expiry.map(|expiry| { + payment_intent + .created_at + .saturating_add(time::Duration::seconds(i64::from(expiry))) + }); + + let updated_amount_details = match amount_details { + Some(details) => payment_intent.amount_details.update_from_request(&details), + None => payment_intent.amount_details, + }; + + let payment_intent = hyperswitch_domain_models::payments::PaymentIntent { + amount_details: updated_amount_details, + description: description.or(payment_intent.description), + return_url: return_url.or(payment_intent.return_url), + metadata: metadata.or(payment_intent.metadata), + statement_descriptor: statement_descriptor.or(payment_intent.statement_descriptor), + modified_at: common_utils::date_time::now(), + order_details, + connector_metadata: connector_metadata.or(payment_intent.connector_metadata), + feature_metadata: (feature_metadata + .map(FeatureMetadata::convert_from) + .or(payment_intent.feature_metadata)), + updated_by: storage_scheme.to_string(), + request_incremental_authorization: request_incremental_authorization + .unwrap_or(payment_intent.request_incremental_authorization), + session_expiry: session_expiry.unwrap_or(payment_intent.session_expiry), + request_external_three_ds_authentication: request_external_three_ds_authentication + .unwrap_or(payment_intent.request_external_three_ds_authentication), + frm_metadata: frm_metadata.or(payment_intent.frm_metadata), + billing_address: decrypted_payment_intent + .billing_address + .as_ref() + .map(|data| { + data.clone() + .deserialize_inner_value(|value| value.parse_value("Address")) + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to decode billing address")?, + shipping_address: decrypted_payment_intent + .shipping_address + .as_ref() + .map(|data| { + data.clone() + .deserialize_inner_value(|value| value.parse_value("Address")) + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to decode shipping address")?, + capture_method: capture_method.unwrap_or(payment_intent.capture_method), + authentication_type: authentication_type.unwrap_or(payment_intent.authentication_type), + payment_link_config: payment_link_config + .map(ApiModelToDieselModelConvertor::convert_from) + .or(payment_intent.payment_link_config), + apply_mit_exemption: apply_mit_exemption.unwrap_or(payment_intent.apply_mit_exemption), + customer_present: customer_present.unwrap_or(payment_intent.customer_present), + routing_algorithm_id: routing_algorithm_id.or(payment_intent.routing_algorithm_id), + allowed_payment_method_types: allowed_payment_method_types + .or(payment_intent.allowed_payment_method_types), + ..payment_intent + }; + + let payment_data = payments::PaymentIntentData { + flow: PhantomData, + payment_intent, + sessions_token: vec![], + }; + + let get_trackers_response = operations::GetTrackerResponse { payment_data }; + + Ok(get_trackers_response) + } +} + +#[async_trait] +impl<F: Clone> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateIntentRequest> + for PaymentUpdateIntent +{ + #[instrument(skip_all)] + async fn update_trackers<'b>( + &'b self, + state: &'b SessionState, + _req_state: ReqState, + mut payment_data: payments::PaymentIntentData<F>, + _customer: Option<domain::Customer>, + storage_scheme: enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, + key_store: &domain::MerchantKeyStore, + _frm_suggestion: Option<FrmSuggestion>, + _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + ) -> RouterResult<( + PaymentsUpdateIntentOperation<'b, F>, + payments::PaymentIntentData<F>, + )> + where + F: 'b + Send, + { + let db = &*state.store; + let key_manager_state = &state.into(); + + let intent = payment_data.payment_intent.clone(); + + let payment_intent_update = + PaymentIntentUpdate::UpdateIntent(Box::new(PaymentIntentUpdateFields { + amount: Some(intent.amount_details.order_amount), + currency: Some(intent.amount_details.currency), + shipping_cost: intent.amount_details.shipping_cost, + skip_external_tax_calculation: Some( + intent.amount_details.skip_external_tax_calculation, + ), + skip_surcharge_calculation: Some(intent.amount_details.skip_surcharge_calculation), + surcharge_amount: intent.amount_details.surcharge_amount, + tax_on_surcharge: intent.amount_details.tax_on_surcharge, + routing_algorithm_id: intent.routing_algorithm_id, + capture_method: Some(intent.capture_method), + authentication_type: Some(intent.authentication_type), + billing_address: intent.billing_address, + shipping_address: intent.shipping_address, + customer_present: Some(intent.customer_present), + description: intent.description, + return_url: intent.return_url, + setup_future_usage: Some(intent.setup_future_usage), + apply_mit_exemption: Some(intent.apply_mit_exemption), + statement_descriptor: intent.statement_descriptor, + order_details: intent.order_details, + allowed_payment_method_types: intent.allowed_payment_method_types, + metadata: intent.metadata, + connector_metadata: intent.connector_metadata, + feature_metadata: intent.feature_metadata, + payment_link_config: intent.payment_link_config, + request_incremental_authorization: Some(intent.request_incremental_authorization), + session_expiry: Some(intent.session_expiry), + frm_metadata: intent.frm_metadata, + request_external_three_ds_authentication: Some( + intent.request_external_three_ds_authentication, + ), + updated_by: intent.updated_by, + tax_details: intent.amount_details.tax_details, + })); + + let new_payment_intent = db + .update_payment_intent( + key_manager_state, + payment_data.payment_intent, + payment_intent_update, + key_store, + storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not update Intent")?; + + payment_data.payment_intent = new_payment_intent; + + Ok((Box::new(self), payment_data)) + } +} + +impl<F: Send + Clone> + ValidateRequest<F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>> + for PaymentUpdateIntent +{ + #[instrument(skip_all)] + fn validate_request<'a, 'b>( + &'b self, + _request: &PaymentsUpdateIntentRequest, + merchant_account: &'a domain::MerchantAccount, + ) -> RouterResult<operations::ValidateResult> { + Ok(operations::ValidateResult { + merchant_id: merchant_account.get_id().to_owned(), + storage_scheme: merchant_account.storage_scheme, + requeue: false, + }) + } +} + +#[async_trait] +impl<F: Clone + Send> Domain<F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>> + for PaymentUpdateIntent +{ + #[instrument(skip_all)] + async fn get_customer_details<'a>( + &'a self, + _state: &SessionState, + _payment_data: &mut payments::PaymentIntentData<F>, + _merchant_key_store: &domain::MerchantKeyStore, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult< + ( + BoxedOperation<'a, F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>, + Option<domain::Customer>, + ), + errors::StorageError, + > { + Ok((Box::new(self), None)) + } + + #[instrument(skip_all)] + async fn make_pm_data<'a>( + &'a self, + _state: &'a SessionState, + _payment_data: &mut payments::PaymentIntentData<F>, + _storage_scheme: enums::MerchantStorageScheme, + _merchant_key_store: &domain::MerchantKeyStore, + _customer: &Option<domain::Customer>, + _business_profile: &domain::Profile, + ) -> RouterResult<( + PaymentsUpdateIntentOperation<'a, F>, + Option<domain::PaymentMethodData>, + Option<String>, + )> { + Ok((Box::new(self), None, None)) + } + + #[instrument(skip_all)] + async fn perform_routing<'a>( + &'a self, + _merchant_account: &domain::MerchantAccount, + _business_profile: &domain::Profile, + _state: &SessionState, + _payment_data: &mut payments::PaymentIntentData<F>, + _mechant_key_store: &domain::MerchantKeyStore, + ) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> { + Ok(api::ConnectorCallType::Skip) + } + + #[instrument(skip_all)] + async fn guard_payment_against_blocklist<'a>( + &'a self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _payment_data: &mut payments::PaymentIntentData<F>, + ) -> CustomResult<bool, errors::ApiErrorResponse> { + Ok(false) + } +} diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index fb8962117c1..6e277ed460f 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -3526,12 +3526,8 @@ impl currency: intent_amount_details.currency, shipping_cost: attempt_amount_details.shipping_cost, order_tax_amount: attempt_amount_details.order_tax_amount, - external_tax_calculation: common_enums::TaxCalculationOverride::foreign_from( - intent_amount_details.skip_external_tax_calculation, - ), - surcharge_calculation: common_enums::SurchargeCalculationOverride::foreign_from( - intent_amount_details.skip_surcharge_calculation, - ), + external_tax_calculation: intent_amount_details.skip_external_tax_calculation, + surcharge_calculation: intent_amount_details.skip_surcharge_calculation, surcharge_amount: attempt_amount_details.surcharge_amount, tax_on_surcharge: attempt_amount_details.tax_on_surcharge, net_amount: attempt_amount_details.net_amount, @@ -3569,12 +3565,8 @@ impl .tax_details .as_ref() .and_then(|tax_details| tax_details.get_default_tax_amount())), - external_tax_calculation: common_enums::TaxCalculationOverride::foreign_from( - intent_amount_details.skip_external_tax_calculation, - ), - surcharge_calculation: common_enums::SurchargeCalculationOverride::foreign_from( - intent_amount_details.skip_surcharge_calculation, - ), + external_tax_calculation: intent_amount_details.skip_external_tax_calculation, + surcharge_calculation: intent_amount_details.skip_surcharge_calculation, surcharge_amount: attempt_amount_details .and_then(|attempt| attempt.surcharge_amount) .or(intent_amount_details.surcharge_amount), @@ -3629,76 +3621,14 @@ impl ForeignFrom<hyperswitch_domain_models::payments::AmountDetails> order_tax_amount: amount_details.tax_details.and_then(|tax_details| { tax_details.default.map(|default| default.order_tax_amount) }), - external_tax_calculation: common_enums::TaxCalculationOverride::foreign_from( - amount_details.skip_external_tax_calculation, - ), - surcharge_calculation: common_enums::SurchargeCalculationOverride::foreign_from( - amount_details.skip_surcharge_calculation, - ), + external_tax_calculation: amount_details.skip_external_tax_calculation, + surcharge_calculation: amount_details.skip_surcharge_calculation, surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, } } } -#[cfg(feature = "v2")] -impl ForeignFrom<common_enums::TaxCalculationOverride> - for hyperswitch_domain_models::payments::TaxCalculationOverride -{ - fn foreign_from(tax_calculation_override: common_enums::TaxCalculationOverride) -> Self { - match tax_calculation_override { - common_enums::TaxCalculationOverride::Calculate => Self::Calculate, - common_enums::TaxCalculationOverride::Skip => Self::Skip, - } - } -} - -#[cfg(feature = "v2")] -impl ForeignFrom<hyperswitch_domain_models::payments::TaxCalculationOverride> - for common_enums::TaxCalculationOverride -{ - fn foreign_from( - tax_calculation_override: hyperswitch_domain_models::payments::TaxCalculationOverride, - ) -> Self { - match tax_calculation_override { - hyperswitch_domain_models::payments::TaxCalculationOverride::Calculate => { - Self::Calculate - } - hyperswitch_domain_models::payments::TaxCalculationOverride::Skip => Self::Skip, - } - } -} - -#[cfg(feature = "v2")] -impl ForeignFrom<common_enums::SurchargeCalculationOverride> - for hyperswitch_domain_models::payments::SurchargeCalculationOverride -{ - fn foreign_from( - surcharge_calculation_override: common_enums::SurchargeCalculationOverride, - ) -> Self { - match surcharge_calculation_override { - common_enums::SurchargeCalculationOverride::Calculate => Self::Calculate, - common_enums::SurchargeCalculationOverride::Skip => Self::Skip, - } - } -} - -#[cfg(feature = "v2")] -impl ForeignFrom<hyperswitch_domain_models::payments::SurchargeCalculationOverride> - for common_enums::SurchargeCalculationOverride -{ - fn foreign_from( - surcharge_calculation_override: hyperswitch_domain_models::payments::SurchargeCalculationOverride, - ) -> Self { - match surcharge_calculation_override { - hyperswitch_domain_models::payments::SurchargeCalculationOverride::Calculate => { - Self::Calculate - } - hyperswitch_domain_models::payments::SurchargeCalculationOverride::Skip => Self::Skip, - } - } -} - #[cfg(feature = "v2")] impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> for diesel_models::PaymentLinkConfigRequestForPayments diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index be24084bcc0..75b06e7f813 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -555,6 +555,10 @@ impl Payments { web::resource("/get-intent") .route(web::get().to(payments::payments_get_intent)), ) + .service( + web::resource("/update-intent") + .route(web::put().to(payments::payments_update_intent)), + ) .service( web::resource("/create-external-sdk-tokens") .route(web::post().to(payments::payments_connector_session)), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 762a5227207..614676e203f 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -142,6 +142,7 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentsCreateIntent | Flow::PaymentsGetIntent | Flow::PaymentsPostSessionTokens + | Flow::PaymentsUpdateIntent | Flow::PaymentStartRedirection => Self::Payments, Flow::PayoutsCreate diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 27a5462c05e..7a8e65e0604 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -118,6 +118,9 @@ pub async fn payments_create_intent( return api::log_and_return_error_response(err); } }; + let global_payment_id = + common_utils::id_type::GlobalPaymentId::generate(&state.conf.cell_information.id.clone()); + Box::pin(api::server_wrap( flow, state, @@ -138,6 +141,7 @@ pub async fn payments_create_intent( auth.key_store, payments::operations::PaymentIntentCreate, req, + global_payment_id.clone(), header_payload.clone(), ) }, @@ -178,6 +182,8 @@ pub async fn payments_get_intent( id: path.into_inner(), }; + let global_payment_id = payload.id.clone(); + Box::pin(api::server_wrap( flow, state, @@ -198,6 +204,62 @@ pub async fn payments_get_intent( auth.key_store, payments::operations::PaymentGetIntent, req, + global_payment_id.clone(), + header_payload.clone(), + ) + }, + &auth::HeaderAuth(auth::ApiKeyAuth), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdateIntent, payment_id))] +pub async fn payments_update_intent( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<payment_types::PaymentsUpdateIntentRequest>, + path: web::Path<common_utils::id_type::GlobalPaymentId>, +) -> impl Responder { + use hyperswitch_domain_models::payments::PaymentIntentData; + + let flow = Flow::PaymentsUpdateIntent; + let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { + Ok(headers) => headers, + Err(err) => { + return api::log_and_return_error_response(err); + } + }; + + let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { + global_payment_id: path.into_inner(), + payload: json_payload.into_inner(), + }; + + let global_payment_id = internal_payload.global_payment_id.clone(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + internal_payload, + |state, auth: auth::AuthenticationData, req, req_state| { + payments::payments_intent_core::< + api_types::PaymentUpdateIntent, + payment_types::PaymentsIntentResponse, + _, + _, + PaymentIntentData<api_types::PaymentUpdateIntent>, + >( + state, + req_state, + auth.merchant_account, + auth.profile, + auth.key_store, + payments::operations::PaymentUpdateIntent, + req.payload, + global_payment_id.clone(), header_payload.clone(), ) }, diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 524712f1ca0..8be423c037b 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -19,13 +19,15 @@ pub use api_models::payments::{ VerifyResponse, WalletData, }; #[cfg(feature = "v2")] -pub use api_models::payments::{PaymentsCreateIntentRequest, PaymentsIntentResponse}; +pub use api_models::payments::{ + PaymentsCreateIntentRequest, PaymentsIntentResponse, PaymentsUpdateIntentRequest, +}; 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, PostProcessing, PostSessionTokens, PreProcessing, Reject, - SdkSessionUpdate, Session, SetupMandate, Void, + PaymentGetIntent, PaymentMethodToken, PaymentUpdateIntent, PostProcessing, PostSessionTokens, + PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, Void, }; pub use hyperswitch_interfaces::api::payments::{ ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 27ddc10766d..3ae2de9ffdf 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -168,6 +168,8 @@ pub enum Flow { PaymentsCreateIntent, /// Payments Get Intent flow PaymentsGetIntent, + /// Payments Update Intent flow + PaymentsUpdateIntent, #[cfg(feature = "payouts")] /// Payouts create flow PayoutsCreate, diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index ebf75a58b2c..fe64136b743 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -10,6 +10,8 @@ use common_utils::{ }; #[cfg(feature = "olap")] use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl}; +#[cfg(feature = "v1")] +use diesel_models::payment_intent::PaymentIntentUpdate as DieselPaymentIntentUpdate; #[cfg(feature = "olap")] use diesel_models::query::generics::db_metrics; #[cfg(all(feature = "v1", feature = "olap"))] @@ -23,11 +25,7 @@ use diesel_models::schema_v2::{ payment_intent::dsl as pi_dsl, }; use diesel_models::{ - enums::MerchantStorageScheme, - kv, - payment_intent::{ - PaymentIntent as DieselPaymentIntent, PaymentIntentUpdate as DieselPaymentIntentUpdate, - }, + enums::MerchantStorageScheme, kv, payment_intent::PaymentIntent as DieselPaymentIntent, }; use error_stack::ResultExt; #[cfg(feature = "olap")]
2024-11-06T09:26:24Z
## Description <!-- Describe your changes in detail --> Added `update-intent` API for payments ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Intent Create Response: ```json { "id": "12345_pay_01930aca908b76b086927c61ad1fb724", "status": "requires_payment_method", "amount_details": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "skip_external_tax_calculation": "Skip", "skip_surcharge_calculation": "Skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "12345_pay_01930aca908b76b086927c61ad1fb724_secret_01930aca908c71c3b6233716f1caede1", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "no_three_ds", "billing": null, "shipping": null, "customer_id": null, "customer_present": "Present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2024-11-08T08:16:07.724Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` 2a. Update Intent Request ``` curl --location --request PUT 'http://localhost:8080/v2/payments/12345_pay_0193921b3f687473ae7aa7e2b2cabc83/update-intent' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_tUJFXjqpFC8MaEF5t8zE' \ --header 'api-key: dev_FW2koArhbGpoUIZNrRPHNIbdgi7TZuCq5V3OHNlQYZOMuy8gU4hu5mrR5IivoOwh' \ --data-raw '{ "amount_details": { "order_amount": 6590, "currency": "AED", "shipping_cost": 123, "order_tax_amount": 123, "skip_external_tax_calculation": "skip", "skip_surcharge_calculation": "skip", "surcharge_amount": 123, "tax_on_surcharge": 123 }, "capture_method": "automatic", "authentication_type": "three_ds", "billing": { "address": { "city": "New York", "country": "AF", "line1": "123, King Street", "line2": "Powelson Avenue", "line3": "Bridgewater", "zip": "08807", "state": "New York", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" }, "email": "blue@blue.com" }, "shipping": { "address": { "city": "New York", "country": "AF", "line1": "123, King Street", "line2": "Powelson Avenue", "line3": "Bridgewater", "zip": "08807", "state": "New York", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" }, "email": "blue@blue.com" }, "customer_present": "present", "description": "It'\''s my first payment request", "return_url": "https://hyperswitch.io", "setup_future_usage": "off_session", "apply_mit_exemption": "Apply", "statement_descriptor": "Hyperswitch Router", "order_details": [{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000, "product_img_link": "https://dummy-img-link.com" }], "allowed_payment_method_types": [ "ach" ], "metadata": {}, "connector_metadata": { "apple_pay": { "session_token_data": { "payment_processing_certificate": "<string>", "payment_processing_certificate_key": "<string>", "payment_processing_details_at": "Hyperswitch", "certificate": "<string>", "certificate_keys": "<string>", "merchant_identifier": "<string>", "display_name": "<string>", "initiative": "web", "initiative_context": "<string>", "merchant_business_country": "AF" } }, "airwallex": { "payload": "<string>" }, "noon": { "order_category": "<string>" } }, "feature_metadata": { "redirect_response": { "param": "<string>", "json_payload": {} }, "search_tags": [ "<string>" ] }, "payment_link_config": { "theme": "#4E6ADD", "logo": "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg", "seller_name": "hyperswitch", "sdk_layout": "accordion", "display_sdk_only": true, "enabled_saved_payment_method": true, "transaction_details": [ { "key": "Policy-Number", "value": "297472368473924", "ui_configuration": { "position": 5, "is_key_bold": true, "is_value_bold": true } } ] }, "request_incremental_authorization": "true", "session_expiry": 1000, "frm_metadata": {}, "request_external_three_ds_authentication": "Enable" }' ``` 2b. Update Intent Response ```json { "id": "12345_pay_0193921b3f687473ae7aa7e2b2cabc83", "status": "requires_payment_method", "amount_details": { "order_amount": 6590, "currency": "AED", "shipping_cost": 123, "order_tax_amount": 123, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": 123, "tax_on_surcharge": 123 }, "client_secret": "12345_pay_0193921b3f687473ae7aa7e2b2cabc83_secret_0193921b3f727390b03af88afb886f68", "profile_id": "pro_tUJFXjqpFC8MaEF5t8zE", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "three_ds", "billing": { "address": { "city": "New York", "country": "AF", "line1": "123, King Street", "line2": "Powelson Avenue", "line3": "Bridgewater", "zip": "08807", "state": "New York", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" }, "email": "blue@blue.com" }, "shipping": { "address": { "city": "New York", "country": "AF", "line1": "123, King Street", "line2": "Powelson Avenue", "line3": "Bridgewater", "zip": "08807", "state": "New York", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" }, "email": "blue@blue.com" }, "customer_id": null, "customer_present": "present", "description": "It's my first payment request", "return_url": "https://hyperswitch.io/", "setup_future_usage": "on_session", "apply_mit_exemption": "Apply", "statement_descriptor": "Hyperswitch Router", "order_details": [ { "product_name": "Apple iPhone 16", "quantity": 1, "amount": 69000, "requires_shipping": null, "product_img_link": "https://dummy-img-link.com", "product_id": null, "category": null, "sub_category": null, "brand": null, "product_type": null, "product_tax_code": null } ], "allowed_payment_method_types": [ "ach" ], "metadata": {}, "connector_metadata": { "apple_pay": { "session_token_data": { "payment_processing_certificate": "<string>", "payment_processing_certificate_key": "<string>", "payment_processing_details_at": "Hyperswitch", "certificate": "<string>", "certificate_keys": "<string>", "merchant_identifier": "<string>", "display_name": "<string>", "initiative": "web", "initiative_context": "<string>", "merchant_business_country": "AF" } }, "airwallex": { "payload": "<string>" }, "noon": { "order_category": "<string>" } }, "feature_metadata": { "redirect_response": { "param": "<string>", "json_payload": {} }, "search_tags": [ "e3846ee6d6368937023c2bbd84565e5fee999118fb8f5e16a31d1129471d130a" ] }, "payment_link_enabled": "Enable", "payment_link_config": { "theme": "#4E6ADD", "logo": "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg", "seller_name": "hyperswitch", "sdk_layout": "accordion", "display_sdk_only": true, "enabled_saved_payment_method": true, "hide_card_nickname_field": null, "show_card_form_by_default": null, "transaction_details": [ { "key": "Policy-Number", "value": "297472368473924", "ui_configuration": { "position": 5, "is_key_bold": true, "is_value_bold": true } } ] }, "request_incremental_authorization": "true", "expires_on": "2024-12-04T14:54:39.539Z", "frm_metadata": {}, "request_external_three_ds_authentication": "Enable" } ```
15f873bd1296169149987041f4008b0afe2ac2aa
1. Intent Create Response: ```json { "id": "12345_pay_01930aca908b76b086927c61ad1fb724", "status": "requires_payment_method", "amount_details": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "skip_external_tax_calculation": "Skip", "skip_surcharge_calculation": "Skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "12345_pay_01930aca908b76b086927c61ad1fb724_secret_01930aca908c71c3b6233716f1caede1", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "no_three_ds", "billing": null, "shipping": null, "customer_id": null, "customer_present": "Present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2024-11-08T08:16:07.724Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` 2a. Update Intent Request ``` curl --location --request PUT 'http://localhost:8080/v2/payments/12345_pay_0193921b3f687473ae7aa7e2b2cabc83/update-intent' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_tUJFXjqpFC8MaEF5t8zE' \ --header 'api-key: dev_FW2koArhbGpoUIZNrRPHNIbdgi7TZuCq5V3OHNlQYZOMuy8gU4hu5mrR5IivoOwh' \ --data-raw '{ "amount_details": { "order_amount": 6590, "currency": "AED", "shipping_cost": 123, "order_tax_amount": 123, "skip_external_tax_calculation": "skip", "skip_surcharge_calculation": "skip", "surcharge_amount": 123, "tax_on_surcharge": 123 }, "capture_method": "automatic", "authentication_type": "three_ds", "billing": { "address": { "city": "New York", "country": "AF", "line1": "123, King Street", "line2": "Powelson Avenue", "line3": "Bridgewater", "zip": "08807", "state": "New York", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" }, "email": "blue@blue.com" }, "shipping": { "address": { "city": "New York", "country": "AF", "line1": "123, King Street", "line2": "Powelson Avenue", "line3": "Bridgewater", "zip": "08807", "state": "New York", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" }, "email": "blue@blue.com" }, "customer_present": "present", "description": "It'\''s my first payment request", "return_url": "https://hyperswitch.io", "setup_future_usage": "off_session", "apply_mit_exemption": "Apply", "statement_descriptor": "Hyperswitch Router", "order_details": [{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000, "product_img_link": "https://dummy-img-link.com" }], "allowed_payment_method_types": [ "ach" ], "metadata": {}, "connector_metadata": { "apple_pay": { "session_token_data": { "payment_processing_certificate": "<string>", "payment_processing_certificate_key": "<string>", "payment_processing_details_at": "Hyperswitch", "certificate": "<string>", "certificate_keys": "<string>", "merchant_identifier": "<string>", "display_name": "<string>", "initiative": "web", "initiative_context": "<string>", "merchant_business_country": "AF" } }, "airwallex": { "payload": "<string>" }, "noon": { "order_category": "<string>" } }, "feature_metadata": { "redirect_response": { "param": "<string>", "json_payload": {} }, "search_tags": [ "<string>" ] }, "payment_link_config": { "theme": "#4E6ADD", "logo": "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg", "seller_name": "hyperswitch", "sdk_layout": "accordion", "display_sdk_only": true, "enabled_saved_payment_method": true, "transaction_details": [ { "key": "Policy-Number", "value": "297472368473924", "ui_configuration": { "position": 5, "is_key_bold": true, "is_value_bold": true } } ] }, "request_incremental_authorization": "true", "session_expiry": 1000, "frm_metadata": {}, "request_external_three_ds_authentication": "Enable" }' ``` 2b. Update Intent Response ```json { "id": "12345_pay_0193921b3f687473ae7aa7e2b2cabc83", "status": "requires_payment_method", "amount_details": { "order_amount": 6590, "currency": "AED", "shipping_cost": 123, "order_tax_amount": 123, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": 123, "tax_on_surcharge": 123 }, "client_secret": "12345_pay_0193921b3f687473ae7aa7e2b2cabc83_secret_0193921b3f727390b03af88afb886f68", "profile_id": "pro_tUJFXjqpFC8MaEF5t8zE", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "three_ds", "billing": { "address": { "city": "New York", "country": "AF", "line1": "123, King Street", "line2": "Powelson Avenue", "line3": "Bridgewater", "zip": "08807", "state": "New York", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" }, "email": "blue@blue.com" }, "shipping": { "address": { "city": "New York", "country": "AF", "line1": "123, King Street", "line2": "Powelson Avenue", "line3": "Bridgewater", "zip": "08807", "state": "New York", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" }, "email": "blue@blue.com" }, "customer_id": null, "customer_present": "present", "description": "It's my first payment request", "return_url": "https://hyperswitch.io/", "setup_future_usage": "on_session", "apply_mit_exemption": "Apply", "statement_descriptor": "Hyperswitch Router", "order_details": [ { "product_name": "Apple iPhone 16", "quantity": 1, "amount": 69000, "requires_shipping": null, "product_img_link": "https://dummy-img-link.com", "product_id": null, "category": null, "sub_category": null, "brand": null, "product_type": null, "product_tax_code": null } ], "allowed_payment_method_types": [ "ach" ], "metadata": {}, "connector_metadata": { "apple_pay": { "session_token_data": { "payment_processing_certificate": "<string>", "payment_processing_certificate_key": "<string>", "payment_processing_details_at": "Hyperswitch", "certificate": "<string>", "certificate_keys": "<string>", "merchant_identifier": "<string>", "display_name": "<string>", "initiative": "web", "initiative_context": "<string>", "merchant_business_country": "AF" } }, "airwallex": { "payload": "<string>" }, "noon": { "order_category": "<string>" } }, "feature_metadata": { "redirect_response": { "param": "<string>", "json_payload": {} }, "search_tags": [ "e3846ee6d6368937023c2bbd84565e5fee999118fb8f5e16a31d1129471d130a" ] }, "payment_link_enabled": "Enable", "payment_link_config": { "theme": "#4E6ADD", "logo": "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg", "seller_name": "hyperswitch", "sdk_layout": "accordion", "display_sdk_only": true, "enabled_saved_payment_method": true, "hide_card_nickname_field": null, "show_card_form_by_default": null, "transaction_details": [ { "key": "Policy-Number", "value": "297472368473924", "ui_configuration": { "position": 5, "is_key_bold": true, "is_value_bold": true } } ] }, "request_incremental_authorization": "true", "expires_on": "2024-12-04T14:54:39.539Z", "frm_metadata": {}, "request_external_three_ds_authentication": "Enable" } ```
[ "api-reference-v2/api-reference/payments/payments--update-intent.mdx", "api-reference-v2/mint.json", "api-reference-v2/openapi_spec.json", "crates/api_models/src/payments.rs", "crates/common_enums/src/enums.rs", "crates/diesel_models/src/kv.rs", "crates/diesel_models/src/payment_intent.rs", "crates/hyperswitch_domain_models/src/lib.rs", "crates/hyperswitch_domain_models/src/payments.rs", "crates/hyperswitch_domain_models/src/payments/payment_intent.rs", "crates/hyperswitch_domain_models/src/router_flow_types/payments.rs", "crates/openapi/src/openapi_v2.rs", "crates/openapi/src/routes/payments.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/operations.rs", "crates/router/src/core/payments/operations/payment_update_intent.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/payments.rs", "crates/router/src/types/api/payments.rs", "crates/router_env/src/logger/types.rs", "crates/storage_impl/src/payments/payment_intent.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6482
Bug: feat(users): Force users to reset password on first login for non-email flow Currently in non-email flow, users who are invited are not forced to change their password. This is being forced in email flow, this should also be present in non-email flow as well.
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 8331dff95c1..c48fe3320f3 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -1,4 +1,8 @@ -use std::{collections::HashSet, ops, str::FromStr}; +use std::{ + collections::HashSet, + ops::{Deref, Not}, + str::FromStr, +}; use api_models::{ admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api, @@ -153,7 +157,7 @@ impl TryFrom<pii::Email> for UserEmail { } } -impl ops::Deref for UserEmail { +impl Deref for UserEmail { type Target = Secret<String, pii::EmailStrategy>; fn deref(&self) -> &Self::Target { @@ -565,10 +569,24 @@ pub struct NewUser { user_id: String, name: UserName, email: UserEmail, - password: Option<UserPassword>, + password: Option<NewUserPassword>, new_merchant: NewUserMerchant, } +#[derive(Clone)] +pub struct NewUserPassword { + password: UserPassword, + is_temporary: bool, +} + +impl Deref for NewUserPassword { + type Target = UserPassword; + + fn deref(&self) -> &Self::Target { + &self.password + } +} + impl NewUser { pub fn get_user_id(&self) -> String { self.user_id.clone() @@ -587,7 +605,9 @@ impl NewUser { } pub fn get_password(&self) -> Option<UserPassword> { - self.password.clone() + self.password + .as_ref() + .map(|password| password.deref().clone()) } pub async fn insert_user_in_db( @@ -697,7 +717,9 @@ impl TryFrom<NewUser> for storage_user::UserNew { totp_status: TotpStatus::NotSet, totp_secret: None, totp_recovery_codes: None, - last_password_modified_at: value.password.is_some().then_some(now), + last_password_modified_at: value + .password + .and_then(|password_inner| password_inner.is_temporary.not().then_some(now)), }) } } @@ -708,7 +730,10 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUser { fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> { let email = value.email.clone().try_into()?; let name = UserName::new(value.name.clone())?; - let password = UserPassword::new(value.password.clone())?; + let password = NewUserPassword { + password: UserPassword::new(value.password.clone())?, + is_temporary: false, + }; let user_id = uuid::Uuid::new_v4().to_string(); let new_merchant = NewUserMerchant::try_from(value)?; @@ -729,7 +754,10 @@ impl TryFrom<user_api::SignUpRequest> for NewUser { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::try_from(value.email.clone())?; - let password = UserPassword::new(value.password.clone())?; + let password = NewUserPassword { + password: UserPassword::new(value.password.clone())?, + is_temporary: false, + }; let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { @@ -770,7 +798,10 @@ impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::new(value.name.clone())?; - let password = UserPassword::new(value.password.clone())?; + let password = NewUserPassword { + password: UserPassword::new(value.password.clone())?, + is_temporary: false, + }; let new_merchant = NewUserMerchant::try_from((value, org_id))?; Ok(Self { @@ -789,16 +820,21 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUser { fn try_from(value: UserMerchantCreateRequestWithToken) -> Result<Self, Self::Error> { let user = value.0.clone(); let new_merchant = NewUserMerchant::try_from(value)?; + let password = user + .0 + .password + .map(UserPassword::new_password_without_validation) + .transpose()? + .map(|password| NewUserPassword { + password, + is_temporary: false, + }); Ok(Self { user_id: user.0.user_id, name: UserName::new(user.0.name)?, email: user.0.email.clone().try_into()?, - password: user - .0 - .password - .map(UserPassword::new_password_without_validation) - .transpose()?, + password, new_merchant, }) } @@ -810,8 +846,10 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.0.email.clone().try_into()?; let name = UserName::new(value.0.name.clone())?; - let password = cfg!(not(feature = "email")) - .then_some(UserPassword::new(password::get_temp_password())?); + let password = cfg!(not(feature = "email")).then_some(NewUserPassword { + password: UserPassword::new(password::get_temp_password())?, + is_temporary: true, + }); let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self {
2024-11-05T13:01:02Z
## Description <!-- Describe your changes in detail --> Currently in non-email flow, users who are invited are not forced to change their password. This PR will add that. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes [#6482](https://github.com/juspay/hyperswitch/issues/6482). ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Invite a new user in non-email flow ``` curl --location 'http://localhost:8080/user/user/invite_multiple?token_only=true' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiN2I2NTA1NGQtNjgzNC00NzU2LTgyNDYtN2RkOWM1ZmQzMzRmIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI5MTc4MDgzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDk4MzEyOSwib3JnX2lkIjoib3JnXzRiYWFjbHZxUklJTEl2a25NdnZQIiwicHJvZmlsZV9pZCI6InByb18yOUFWY0ltVnFDYTV1UHdMMzlQWCJ9.E5ZfkG5y0tqGa_vzGXe5LTJlyljqP8tKs1T2qokRtr0' \ --data-raw '[ { "email": "new email", "name": "name", "role_id": "merchant_view_only" } ]' ``` ```json [ { "email": "email from request", "is_email_sent": false, "password": "4724b955-bc1d-4565-bbb6-1a09b2372bfaA" } ] ``` 2. Sign in as the new user ``` curl --location 'http://localhost:8080/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email used in invite", "password": "password from invite API response" }' ``` ```json { "token": "TOTP SPT", "token_type": "totp" } ``` 3. Terminate 2FA (This API should give reset password SPT) ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: TOTP SPT' \ ``` ```json { "token": "Force set password SPT", "token_type": "force_set_password" } ```
01c5216fdd6f1d841082868cccea6054b64e9e07
1. Invite a new user in non-email flow ``` curl --location 'http://localhost:8080/user/user/invite_multiple?token_only=true' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiN2I2NTA1NGQtNjgzNC00NzU2LTgyNDYtN2RkOWM1ZmQzMzRmIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI5MTc4MDgzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDk4MzEyOSwib3JnX2lkIjoib3JnXzRiYWFjbHZxUklJTEl2a25NdnZQIiwicHJvZmlsZV9pZCI6InByb18yOUFWY0ltVnFDYTV1UHdMMzlQWCJ9.E5ZfkG5y0tqGa_vzGXe5LTJlyljqP8tKs1T2qokRtr0' \ --data-raw '[ { "email": "new email", "name": "name", "role_id": "merchant_view_only" } ]' ``` ```json [ { "email": "email from request", "is_email_sent": false, "password": "4724b955-bc1d-4565-bbb6-1a09b2372bfaA" } ] ``` 2. Sign in as the new user ``` curl --location 'http://localhost:8080/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email used in invite", "password": "password from invite API response" }' ``` ```json { "token": "TOTP SPT", "token_type": "totp" } ``` 3. Terminate 2FA (This API should give reset password SPT) ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: TOTP SPT' \ ``` ```json { "token": "Force set password SPT", "token_type": "force_set_password" } ```
[ "crates/router/src/types/domain/user.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6508
Bug: [FEATURE] Add support for payout connector integrations for connectors crate ### Feature Description To be able to support connector integrations in router and the new hyperswitch_connectors crate. ### Possible Implementation Move payout API traits to a common place - in hyperswitch_interfaces crate. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 418d58eb54b..81c079d5d52 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -1049,6 +1049,56 @@ default_imp_for_file_upload!( connectors::Zsl ); +macro_rules! default_imp_for_payouts { + ($($path:ident::$connector:ident),*) => { + $( + impl api::Payouts for $path::$connector {} + )* + }; +} + +default_imp_for_payouts!( + connectors::Airwallex, + connectors::Amazonpay, + connectors::Bambora, + connectors::Billwerk, + connectors::Bitpay, + connectors::Cashtocode, + connectors::Cryptopay, + connectors::Coinbase, + connectors::Deutschebank, + connectors::Digitalvirgo, + connectors::Dlocal, + connectors::Elavon, + connectors::Fiserv, + connectors::Fiservemea, + connectors::Fiuu, + connectors::Forte, + connectors::Globepay, + connectors::Helcim, + connectors::Jpmorgan, + connectors::Mollie, + connectors::Multisafepay, + connectors::Nexinets, + connectors::Nexixpay, + connectors::Nomupay, + connectors::Novalnet, + connectors::Payeezy, + connectors::Payu, + connectors::Powertranz, + connectors::Razorpay, + connectors::Shift4, + connectors::Square, + connectors::Stax, + connectors::Taxjar, + connectors::Tsys, + connectors::Volt, + connectors::Worldline, + connectors::Worldpay, + connectors::Zen, + connectors::Zsl +); + #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_create { ($($path:ident::$connector:ident),*) => { diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs index 7205865f24a..0ea8996cb4c 100644 --- a/crates/hyperswitch_interfaces/src/api.rs +++ b/crates/hyperswitch_interfaces/src/api.rs @@ -38,6 +38,8 @@ use masking::Maskable; use router_env::metrics::add_attributes; use serde_json::json; +#[cfg(feature = "payouts")] +pub use self::payouts::*; pub use self::{payments::*, refunds::*}; use crate::{ configs::Connectors, connector_integration_v2::ConnectorIntegrationV2, consts, errors, @@ -410,3 +412,7 @@ pub trait ConnectorRedirectResponse { Ok(CallConnectorAction::Avoid) } } + +/// Empty trait for when payouts feature is disabled +#[cfg(not(feature = "payouts"))] +pub trait Payouts {} diff --git a/crates/hyperswitch_interfaces/src/api/payouts.rs b/crates/hyperswitch_interfaces/src/api/payouts.rs index 894f636707a..5fc0280f19c 100644 --- a/crates/hyperswitch_interfaces/src/api/payouts.rs +++ b/crates/hyperswitch_interfaces/src/api/payouts.rs @@ -1,13 +1,15 @@ //! Payouts interface -use hyperswitch_domain_models::router_flow_types::payouts::{ - PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, -}; -#[cfg(feature = "payouts")] use hyperswitch_domain_models::{ - router_request_types::PayoutsData, router_response_types::PayoutsResponseData, + router_flow_types::payouts::{ + PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, + PoSync, + }, + router_request_types::PayoutsData, + router_response_types::PayoutsResponseData, }; +use super::ConnectorCommon; use crate::api::ConnectorIntegration; /// trait PayoutCancel @@ -42,3 +44,17 @@ pub trait PayoutRecipientAccount: /// trait PayoutSync pub trait PayoutSync: ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> {} + +/// trait Payouts +pub trait Payouts: + ConnectorCommon + + PayoutCancel + + PayoutCreate + + PayoutEligibility + + PayoutFulfill + + PayoutQuote + + PayoutRecipient + + PayoutRecipientAccount + + PayoutSync +{ +} diff --git a/crates/hyperswitch_interfaces/src/api/payouts_v2.rs b/crates/hyperswitch_interfaces/src/api/payouts_v2.rs index 40e0726ce80..9027152f02d 100644 --- a/crates/hyperswitch_interfaces/src/api/payouts_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/payouts_v2.rs @@ -1,13 +1,15 @@ //! Payouts V2 interface -use hyperswitch_domain_models::router_flow_types::payouts::{ - PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, -}; -#[cfg(feature = "payouts")] use hyperswitch_domain_models::{ - router_data_v2::flow_common_types::PayoutFlowData, router_request_types::PayoutsData, + router_data_v2::flow_common_types::PayoutFlowData, + router_flow_types::payouts::{ + PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, + PoSync, + }, + router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; +use super::ConnectorCommon; use crate::api::ConnectorIntegrationV2; /// trait PayoutCancelV2 @@ -57,3 +59,21 @@ pub trait PayoutSyncV2: ConnectorIntegrationV2<PoSync, PayoutFlowData, PayoutsData, PayoutsResponseData> { } + +/// trait Payouts +pub trait PayoutsV2: + ConnectorCommon + + PayoutCancelV2 + + PayoutCreateV2 + + PayoutEligibilityV2 + + PayoutFulfillV2 + + PayoutQuoteV2 + + PayoutRecipientV2 + + PayoutRecipientAccountV2 + + PayoutSyncV2 +{ +} + +/// Empty trait for when payouts feature is disabled +#[cfg(not(feature = "payouts"))] +pub trait PayoutsV2 {} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index a6894502996..1358bcedba1 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -12,6 +12,7 @@ pub mod session_update_flow; pub mod setup_mandate_flow; use async_trait::async_trait; +use hyperswitch_interfaces::api::payouts::Payouts; #[cfg(feature = "frm")] use crate::types::fraud_check as frm_types; @@ -969,88 +970,49 @@ default_imp_for_post_processing_steps!( macro_rules! default_imp_for_payouts { ($($path:ident::$connector:ident),*) => { $( - impl api::Payouts for $path::$connector {} + impl Payouts for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] -impl<const T: u8> api::Payouts for connector::DummyConnector<T> {} +impl<const T: u8> Payouts for connector::DummyConnector<T> {} default_imp_for_payouts!( connector::Aci, - connector::Airwallex, - connector::Amazonpay, connector::Authorizedotnet, - connector::Bambora, connector::Bamboraapac, connector::Bankofamerica, - connector::Billwerk, - connector::Bitpay, connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Datatrans, - connector::Deutschebank, - connector::Digitalvirgo, - connector::Dlocal, - connector::Elavon, - connector::Fiserv, - connector::Fiservemea, - connector::Fiuu, - connector::Forte, connector::Globalpay, - connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, - connector::Jpmorgan, connector::Klarna, connector::Mifinity, - connector::Mollie, - connector::Multisafepay, connector::Netcetera, - connector::Nexinets, - connector::Nexixpay, connector::Nmi, - connector::Nomupay, connector::Noon, - connector::Novalnet, connector::Nuvei, connector::Opayo, connector::Opennode, connector::Paybox, - connector::Payeezy, connector::Payme, - connector::Payu, connector::Placetopay, connector::Plaid, - connector::Powertranz, connector::Prophetpay, connector::Rapyd, - connector::Razorpay, connector::Riskified, - connector::Shift4, connector::Signifyd, - connector::Square, - connector::Stax, - connector::Taxjar, connector::Threedsecureio, connector::Trustpay, - connector::Tsys, - connector::Volt, connector::Wellsfargo, - connector::Wellsfargopayout, - connector::Worldline, - connector::Worldpay, - connector::Zen, - connector::Zsl + connector::Wellsfargopayout ); #[cfg(feature = "payouts")] diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index e3c311710d5..985a6644524 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -568,25 +568,6 @@ pub trait FraudCheck {} #[cfg(not(feature = "frm"))] pub trait FraudCheckV2 {} -#[cfg(feature = "payouts")] -pub trait Payouts: - ConnectorCommon - + PayoutCancel - + PayoutCreate - + PayoutEligibility - + PayoutFulfill - + PayoutQuote - + PayoutRecipient - + PayoutRecipientAccount - + PayoutSync -{ -} -#[cfg(not(feature = "payouts"))] -pub trait Payouts {} - -#[cfg(not(feature = "payouts"))] -pub trait PayoutsV2 {} - #[cfg(test)] mod test { #![allow(clippy::unwrap_used)] diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rs index a9630beb25a..b5a6ac24ca9 100644 --- a/crates/router/src/types/api/payouts.rs +++ b/crates/router/src/types/api/payouts.rs @@ -11,7 +11,7 @@ pub use hyperswitch_domain_models::router_flow_types::payouts::{ }; pub use hyperswitch_interfaces::api::payouts::{ PayoutCancel, PayoutCreate, PayoutEligibility, PayoutFulfill, PayoutQuote, PayoutRecipient, - PayoutRecipientAccount, PayoutSync, + PayoutRecipientAccount, PayoutSync, Payouts, }; pub use super::payouts_v2::{
2024-11-05T11:21:51Z
## Description Described in #6508 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context This helps us implement new payout connector integrations in `hyperswitch_connectors` crate ## How did you test it? Not needed as it's only a refactor. New connectors being added in `hyperswitch_connectors` crate can be tested
20a3a1c2d6bb93fb4dae7f7eb669ebd85e631c96
Not needed as it's only a refactor. New connectors being added in `hyperswitch_connectors` crate can be tested
[ "crates/hyperswitch_connectors/src/default_implementations.rs", "crates/hyperswitch_interfaces/src/api.rs", "crates/hyperswitch_interfaces/src/api/payouts.rs", "crates/hyperswitch_interfaces/src/api/payouts_v2.rs", "crates/router/src/core/payments/flows.rs", "crates/router/src/types/api.rs", "crates/router/src/types/api/payouts.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6475
Bug: feat(opensearch): refactor global search querybuilder and add case insensitivity opensearch filters - Currently the global search query builder logic is entirely present in a single function. - With more and more features getting added on, it is better to separate out the logic to build the query into separate modules. - Also, with the enhancement of global search, it is better to give out some fields as case sensitive and others as case insensitive. Case Sensitive filters: - customer_email - payment_id - card_last_4 - search_tags Case Insensitive filters: - payment_method - payment_method_type - card_network - currency - connector - status The new structure would be divided into separate functions for the respective modules as follows: - Free Search Query + Time Range + Filters (case sensitive) - Filters (case insensitive) - Authentication and Search Params
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index a6e6c486ebe..84a2b9db3d4 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::{ analytics::search::SearchIndex, errors::types::{ApiError, ApiErrorResponse}, @@ -456,7 +458,8 @@ pub struct OpenSearchQueryBuilder { pub count: Option<i64>, pub filters: Vec<(String, Vec<String>)>, pub time_range: Option<OpensearchTimeRange>, - pub search_params: Vec<AuthInfo>, + search_params: Vec<AuthInfo>, + case_sensitive_fields: HashSet<&'static str>, } impl OpenSearchQueryBuilder { @@ -469,6 +472,12 @@ impl OpenSearchQueryBuilder { count: Default::default(), filters: Default::default(), time_range: Default::default(), + case_sensitive_fields: HashSet::from([ + "customer_email.keyword", + "search_tags.keyword", + "card_last_4.keyword", + "payment_id.keyword", + ]), } } @@ -490,48 +499,16 @@ impl OpenSearchQueryBuilder { pub fn get_status_field(&self, index: &SearchIndex) -> &str { match index { - SearchIndex::Refunds => "refund_status.keyword", - SearchIndex::Disputes => "dispute_status.keyword", + SearchIndex::Refunds | SearchIndex::SessionizerRefunds => "refund_status.keyword", + SearchIndex::Disputes | SearchIndex::SessionizerDisputes => "dispute_status.keyword", _ => "status.keyword", } } - pub fn replace_status_field(&self, filters: &[Value], index: &SearchIndex) -> Vec<Value> { - filters - .iter() - .map(|filter| { - if let Some(terms) = filter.get("terms").and_then(|v| v.as_object()) { - let mut new_filter = filter.clone(); - if let Some(new_terms) = - new_filter.get_mut("terms").and_then(|v| v.as_object_mut()) - { - let key = "status.keyword"; - if let Some(status_terms) = terms.get(key) { - new_terms.remove(key); - new_terms.insert( - self.get_status_field(index).to_string(), - status_terms.clone(), - ); - } - } - new_filter - } else { - filter.clone() - } - }) - .collect() - } - - /// # Panics - /// - /// This function will panic if: - /// - /// * The structure of the JSON query is not as expected (e.g., missing keys or incorrect types). - /// - /// Ensure that the input data and the structure of the query are valid and correctly handled. - pub fn construct_payload(&self, indexes: &[SearchIndex]) -> QueryResult<Vec<Value>> { - let mut query_obj = Map::new(); - let mut bool_obj = Map::new(); + pub fn build_filter_array( + &self, + case_sensitive_filters: Vec<&(String, Vec<String>)>, + ) -> Vec<Value> { let mut filter_array = Vec::new(); filter_array.push(json!({ @@ -542,13 +519,12 @@ impl OpenSearchQueryBuilder { } })); - let mut filters = self - .filters - .iter() + let case_sensitive_json_filters = case_sensitive_filters + .into_iter() .map(|(k, v)| json!({"terms": {k: v}})) .collect::<Vec<Value>>(); - filter_array.append(&mut filters); + filter_array.extend(case_sensitive_json_filters); if let Some(ref time_range) = self.time_range { let range = json!(time_range); @@ -559,8 +535,72 @@ impl OpenSearchQueryBuilder { })); } - let should_array = self - .search_params + filter_array + } + + pub fn build_case_insensitive_filters( + &self, + mut payload: Value, + case_insensitive_filters: &[&(String, Vec<String>)], + auth_array: Vec<Value>, + index: &SearchIndex, + ) -> Value { + let mut must_array = case_insensitive_filters + .iter() + .map(|(k, v)| { + let key = if *k == "status.keyword" { + self.get_status_field(index).to_string() + } else { + k.clone() + }; + json!({ + "bool": { + "must": [ + { + "bool": { + "should": v.iter().map(|value| { + json!({ + "term": { + format!("{}", key): { + "value": value, + "case_insensitive": true + } + } + }) + }).collect::<Vec<Value>>(), + "minimum_should_match": 1 + } + } + ] + } + }) + }) + .collect::<Vec<Value>>(); + + must_array.push(json!({ "bool": { + "must": [ + { + "bool": { + "should": auth_array, + "minimum_should_match": 1 + } + } + ] + }})); + + if let Some(query) = payload.get_mut("query") { + if let Some(bool_obj) = query.get_mut("bool") { + if let Some(bool_map) = bool_obj.as_object_mut() { + bool_map.insert("must".to_string(), Value::Array(must_array)); + } + } + } + + payload + } + + pub fn build_auth_array(&self) -> Vec<Value> { + self.search_params .iter() .map(|user_level| match user_level { AuthInfo::OrgLevel { org_id } => { @@ -579,11 +619,17 @@ impl OpenSearchQueryBuilder { }) } AuthInfo::MerchantLevel { - org_id: _, + org_id, merchant_ids, } => { let must_clauses = vec![ - // TODO: Add org_id field to the filters + json!({ + "term": { + "organization_id.keyword": { + "value": org_id + } + } + }), json!({ "terms": { "merchant_id.keyword": merchant_ids @@ -598,12 +644,18 @@ impl OpenSearchQueryBuilder { }) } AuthInfo::ProfileLevel { - org_id: _, + org_id, merchant_id, profile_ids, } => { let must_clauses = vec![ - // TODO: Add org_id field to the filters + json!({ + "term": { + "organization_id.keyword": { + "value": org_id + } + } + }), json!({ "term": { "merchant_id.keyword": { @@ -625,55 +677,60 @@ impl OpenSearchQueryBuilder { }) } }) - .collect::<Vec<Value>>(); + .collect::<Vec<Value>>() + } + + /// # Panics + /// + /// This function will panic if: + /// + /// * The structure of the JSON query is not as expected (e.g., missing keys or incorrect types). + /// + /// Ensure that the input data and the structure of the query are valid and correctly handled. + pub fn construct_payload(&self, indexes: &[SearchIndex]) -> QueryResult<Vec<Value>> { + let mut query_obj = Map::new(); + let mut bool_obj = Map::new(); + + let (case_sensitive_filters, case_insensitive_filters): (Vec<_>, Vec<_>) = self + .filters + .iter() + .partition(|(k, _)| self.case_sensitive_fields.contains(k.as_str())); + + let filter_array = self.build_filter_array(case_sensitive_filters); if !filter_array.is_empty() { bool_obj.insert("filter".to_string(), Value::Array(filter_array)); } + + let should_array = self.build_auth_array(); + if !bool_obj.is_empty() { query_obj.insert("bool".to_string(), Value::Object(bool_obj)); } - let mut query = Map::new(); - query.insert("query".to_string(), Value::Object(query_obj)); + let mut sort_obj = Map::new(); + sort_obj.insert( + "@timestamp".to_string(), + json!({ + "order": "desc" + }), + ); Ok(indexes .iter() .map(|index| { - let updated_query = query - .get("query") - .and_then(|q| q.get("bool")) - .and_then(|b| b.get("filter")) - .and_then(|f| f.as_array()) - .map(|filters| self.replace_status_field(filters, index)) - .unwrap_or_default(); - let mut final_bool_obj = Map::new(); - if !updated_query.is_empty() { - final_bool_obj.insert("filter".to_string(), Value::Array(updated_query)); - } - if !should_array.is_empty() { - final_bool_obj.insert("should".to_string(), Value::Array(should_array.clone())); - final_bool_obj - .insert("minimum_should_match".to_string(), Value::Number(1.into())); - } - let mut final_query = Map::new(); - if !final_bool_obj.is_empty() { - final_query.insert("bool".to_string(), Value::Object(final_bool_obj)); - } - - let mut sort_obj = Map::new(); - sort_obj.insert( - "@timestamp".to_string(), - json!({ - "order": "desc" - }), - ); - let payload = json!({ - "query": Value::Object(final_query), + let mut payload = json!({ + "query": query_obj.clone(), "sort": [ - Value::Object(sort_obj) + Value::Object(sort_obj.clone()) ] }); + payload = self.build_case_insensitive_filters( + payload, + &case_insensitive_filters, + should_array.clone(), + index, + ); payload }) .collect::<Vec<Value>>()) diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs index f53b07b1232..9be0200030d 100644 --- a/crates/analytics/src/search.rs +++ b/crates/analytics/src/search.rs @@ -190,7 +190,17 @@ pub async fn search_results( search_params: Vec<AuthInfo>, ) -> CustomResult<GetSearchResponse, OpenSearchError> { let search_req = req.search_req; - + if search_req.query.trim().is_empty() + && search_req + .filters + .as_ref() + .map_or(true, |filters| filters.is_all_none()) + { + return Err(OpenSearchError::BadRequestError( + "Both query and filters are empty".to_string(), + ) + .into()); + } let mut query_builder = OpenSearchQueryBuilder::new( OpenSearchQuery::Search(req.index), search_req.query,
2024-11-04T11:59:47Z
## Description <!-- Describe your changes in detail --> - Currently the global search query builder logic is entirely present in a single function. - With more and more features getting added on, it is better to separate out the logic to build the query into separate modules. - Also, with the enhancement of global search, it is better to give out some fields as case sensitive and others as case insensitive. Case Sensitive filters: - customer_email - payment_id - card_last_4 - search_tags Case Insensitive filters: - payment_method - payment_method_type - card_network - currency - connector - status The new structure would be divided into separate functions for the respective modules as follows: - Free Search Query + Time Range + Filters (case sensitive) - Filters (case insensitive) - Authentication and Search Params The query generated to hit opensearch will now look like the following: ```json { "query": { "bool": { "filter": [ { "multi_match": { "type": "phrase", "query": "merchant_1726046328", "lenient": true } }, { "terms": { "customer_email.keyword": [ "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303" ] } }, { "terms": { "card_last_4.keyword": [ "4242" ] } }, { "terms": { "payment_id.keyword": [ "pay_QdstJpRVAcRKHzRIRK4d" ] } }, { "range": { "@timestamp": { "gte": "2024-09-13T00:30:00.000Z", "lte": "2024-10-30T21:45:00.000Z" } } } ], "must": [ { "bool": { "must": [ { "bool": { "should": [ { "term": { "currency.keyword": { "value": "UsD", "case_insensitive": true } } } ], "minimum_should_match": 1 } } ] } }, { "bool": { "must": [ { "bool": { "should": [ { "term": { "status.keyword": { "value": "CharGed", "case_insensitive": true } } }, { "term": { "status.keyword": { "value": "succeeded", "case_insensitive": true } } } ], "minimum_should_match": 1 } } ] } }, { "bool": { "must": [ { "bool": { "should": [ { "term": { "payment_method.keyword": { "value": "cArd", "case_insensitive": true } } }, { "term": { "payment_method.keyword": { "value": "iwubefi", "case_insensitive": true } } } ], "minimum_should_match": 1 } } ] } }, { "bool": { "must": [ { "bool": { "should": [ { "term": { "connector.keyword": { "value": "striPe_Test", "case_insensitive": true } } } ], "minimum_should_match": 1 } } ] } }, { "bool": { "must": [ { "bool": { "should": [ { "term": { "payment_method_type.keyword": { "value": "credit", "case_insensitive": true } } } ], "minimum_should_match": 1 } } ] } }, { "bool": { "must": [ { "bool": { "should": [ { "bool": { "must": [ { "term": { "organization_id.keyword": { "value": "org_VpSHOjsYfDvabVYJgCAJ" } } } ] } } ], "minimum_should_match": 1 } } ] } } ] } }, "sort": [ { "@timestamp": { "order": "desc" } } ] } ``` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - Enhanced search experience based on free search and specific filters using global search. - Can now search via filters in a case-insensitive manner for some common filters. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Can send the following filters in any case: - payment_method - payment_method_type - card_network - currency - connector - status Must send the following filters in the exact case: - customer_email - payment_id - card_last_4 - search_tags #### Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/search' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDg3MDI4Niwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.luU7VDVnDVz7xuHLKEY5UWfxU78sGvzysZ99R8-1Bxo' \ --header 'Referer: http://localhost:9000/' \ --header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --data-raw '{ "query": "merchant_1726046328", "filters": { "currency": [ "UsD" ], "connector": [ "striPe_Test" ], "customer_email": [ "test@test14.com" ], "payment_method_type": [ "credit" ], "payment_method": [ "cArd", "iwubefi" ], "payment_id": [ "pay_QdstJpRVAcRKHzRIRK4d" ], "card_last_4": [ "4242" ], "status": [ "CharGed", "succeeded" ] }, "timeRange": { "startTime": "2024-09-13T00:30:00Z", "endTime": "2024-10-30T21:45:00Z" } }' ``` Expected response: ```json [ { "count": 0, "index": "payment_attempts", "hits": [], "status": "Success" }, { "count": 0, "index": "payment_intents", "hits": [], "status": "Success" }, { "count": 0, "index": "refunds", "hits": [], "status": "Success" }, { "count": 0, "index": "disputes", "hits": [], "status": "Failure" }, { "count": 1, "index": "sessionizer_payment_attempts", "hits": [ { "@timestamp": "2024-10-24T07:59:12.887Z", "amount": 6540, "amount_capturable": 0, "amount_to_capture": 6540, "attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1", "authentication_type": "no_three_ds", "capture_method": "automatic", "capture_on": 1662804672000, "card_last_4": "4242", "confirm": true, "connector": "stripe_test", "connector_transaction_id": "pay_BV1cUypv6paxZvJl2SiQ", "created_at": 1729756752887, "currency": "USD", "customer_email": "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303", "customer_id": "StripeCustomer", "first_attempt": true, "headers": {}, "log_count": 9, "merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6", "merchant_id": "merchant_1726046328", "modified_at": 1729756754123, "net_amount": 6540, "organization_id": "org_VpSHOjsYfDvabVYJgCAJ", "payment_id": "pay_QdstJpRVAcRKHzRIRK4d", "payment_method": "card", "payment_method_data": "{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":null,\"card_extended_bin\":null,\"authentication_data\":null,\"card_issuing_country\":null}}", "payment_method_type": "credit", "profile_id": "pro_v5sFoHe80OeiUlIonocM", "source_type": "kafka", "status": "charged", "tenant_id": "public", "timestamp": "2024-10-24T07:59:12.887Z" } ], "status": "Success" }, { "count": 1, "index": "sessionizer_payment_intents", "hits": [ { "@timestamp": "2024-10-24T07:59:12.886Z", "active_attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1", "amount": 6540, "amount_captured": 6540, "attempt_count": 1, "attempts_list": [ { "amount": 6540, "amount_capturable": 0, "amount_to_capture": 6540, "attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1", "authentication_type": "no_three_ds", "capture_method": "automatic", "capture_on": 1662804672000, "confirm": true, "connector": "stripe_test", "connector_transaction_id": "pay_BV1cUypv6paxZvJl2SiQ", "created_at": 1729756752887, "currency": "USD", "last_synced": 1729756752887, "merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6", "merchant_id": "merchant_1726046328", "modified_at": 1729756754123, "net_amount": 6540, "organization_id": "org_VpSHOjsYfDvabVYJgCAJ", "payment_id": "pay_QdstJpRVAcRKHzRIRK4d", "payment_method": "card", "payment_method_data": "{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":null,\"card_extended_bin\":null,\"authentication_data\":null,\"card_issuing_country\":null}}", "payment_method_type": "credit", "profile_id": "pro_v5sFoHe80OeiUlIonocM", "status": "charged", "tenant_id": "public" } ], "authentication_type": "no_three_ds", "business_label": "default", "card_last_4": "4242", "client_secret": "pay_QdstJpRVAcRKHzRIRK4d_secret_u2WJTHVO3BmpJfkzdXaY", "connector": "stripe_test", "created_at": 1729756752886, "currency": "USD", "customer_email": "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303", "customer_id": "StripeCustomer", "description": "Its my first payment request", "dispute_list": [], "headers": {}, "log_count": 9, "merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6", "merchant_id": "merchant_1726046328", "metadata": "{\"data2\":\"camel\",\"login_date\":\"2019-09-10T10:11:12Z\",\"new_customer\":\"true\"}", "modified_at": 1729756754123, "organization_id": "org_VpSHOjsYfDvabVYJgCAJ", "payment_id": "pay_QdstJpRVAcRKHzRIRK4d", "payment_method": "card", "payment_method_data": "{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":null,\"card_extended_bin\":null,\"authentication_data\":null,\"card_issuing_country\":null}}", "payment_method_type": "credit", "profile_id": "pro_v5sFoHe80OeiUlIonocM", "refund_list": [ { "attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1", "connector": "stripe_test", "connector_refund_id": "dummy_ref_6HyIEJcmDyE75QiFnv76", "connector_transaction_id": "pay_BV1cUypv6paxZvJl2SiQ", "created_at": 1729756766669, "currency": "USD", "description": "Customer returned product", "external_reference_id": "ref_Tc3KfBVm5HEuzECytr9g", "internal_reference_id": "refid_vDztMj3wI0ETCFXEoWUG", "merchant_id": "merchant_1726046328", "modified_at": 1729756767668, "organization_id": "org_VpSHOjsYfDvabVYJgCAJ", "payment_id": "pay_QdstJpRVAcRKHzRIRK4d", "profile_id": "pro_v5sFoHe80OeiUlIonocM", "refund_amount": 600, "refund_arn": "", "refund_id": "ref_Tc3KfBVm5HEuzECytr9g", "refund_reason": "Customer returned product", "refund_status": "success", "refund_type": "instant_refund", "sent_to_gateway": true, "tenant_id": "public", "total_amount": 6540 } ], "refunds_status": "partial_refunded", "return_url": "https://google.com/", "source_type": "kafka", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "status": "succeeded", "tenant_id": "public", "timestamp": "2024-10-24T07:59:12.886Z" } ], "status": "Success" }, { "count": 0, "index": "sessionizer_refunds", "hits": [], "status": "Success" }, { "count": 0, "index": "sessionizer_disputes", "hits": [], "status": "Failure" } ] ```
72ee434003eef744d516343a2f803264f226d92a
Can send the following filters in any case: - payment_method - payment_method_type - card_network - currency - connector - status Must send the following filters in the exact case: - customer_email - payment_id - card_last_4 - search_tags #### Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/search' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDg3MDI4Niwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.luU7VDVnDVz7xuHLKEY5UWfxU78sGvzysZ99R8-1Bxo' \ --header 'Referer: http://localhost:9000/' \ --header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --data-raw '{ "query": "merchant_1726046328", "filters": { "currency": [ "UsD" ], "connector": [ "striPe_Test" ], "customer_email": [ "test@test14.com" ], "payment_method_type": [ "credit" ], "payment_method": [ "cArd", "iwubefi" ], "payment_id": [ "pay_QdstJpRVAcRKHzRIRK4d" ], "card_last_4": [ "4242" ], "status": [ "CharGed", "succeeded" ] }, "timeRange": { "startTime": "2024-09-13T00:30:00Z", "endTime": "2024-10-30T21:45:00Z" } }' ``` Expected response: ```json [ { "count": 0, "index": "payment_attempts", "hits": [], "status": "Success" }, { "count": 0, "index": "payment_intents", "hits": [], "status": "Success" }, { "count": 0, "index": "refunds", "hits": [], "status": "Success" }, { "count": 0, "index": "disputes", "hits": [], "status": "Failure" }, { "count": 1, "index": "sessionizer_payment_attempts", "hits": [ { "@timestamp": "2024-10-24T07:59:12.887Z", "amount": 6540, "amount_capturable": 0, "amount_to_capture": 6540, "attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1", "authentication_type": "no_three_ds", "capture_method": "automatic", "capture_on": 1662804672000, "card_last_4": "4242", "confirm": true, "connector": "stripe_test", "connector_transaction_id": "pay_BV1cUypv6paxZvJl2SiQ", "created_at": 1729756752887, "currency": "USD", "customer_email": "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303", "customer_id": "StripeCustomer", "first_attempt": true, "headers": {}, "log_count": 9, "merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6", "merchant_id": "merchant_1726046328", "modified_at": 1729756754123, "net_amount": 6540, "organization_id": "org_VpSHOjsYfDvabVYJgCAJ", "payment_id": "pay_QdstJpRVAcRKHzRIRK4d", "payment_method": "card", "payment_method_data": "{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":null,\"card_extended_bin\":null,\"authentication_data\":null,\"card_issuing_country\":null}}", "payment_method_type": "credit", "profile_id": "pro_v5sFoHe80OeiUlIonocM", "source_type": "kafka", "status": "charged", "tenant_id": "public", "timestamp": "2024-10-24T07:59:12.887Z" } ], "status": "Success" }, { "count": 1, "index": "sessionizer_payment_intents", "hits": [ { "@timestamp": "2024-10-24T07:59:12.886Z", "active_attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1", "amount": 6540, "amount_captured": 6540, "attempt_count": 1, "attempts_list": [ { "amount": 6540, "amount_capturable": 0, "amount_to_capture": 6540, "attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1", "authentication_type": "no_three_ds", "capture_method": "automatic", "capture_on": 1662804672000, "confirm": true, "connector": "stripe_test", "connector_transaction_id": "pay_BV1cUypv6paxZvJl2SiQ", "created_at": 1729756752887, "currency": "USD", "last_synced": 1729756752887, "merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6", "merchant_id": "merchant_1726046328", "modified_at": 1729756754123, "net_amount": 6540, "organization_id": "org_VpSHOjsYfDvabVYJgCAJ", "payment_id": "pay_QdstJpRVAcRKHzRIRK4d", "payment_method": "card", "payment_method_data": "{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":null,\"card_extended_bin\":null,\"authentication_data\":null,\"card_issuing_country\":null}}", "payment_method_type": "credit", "profile_id": "pro_v5sFoHe80OeiUlIonocM", "status": "charged", "tenant_id": "public" } ], "authentication_type": "no_three_ds", "business_label": "default", "card_last_4": "4242", "client_secret": "pay_QdstJpRVAcRKHzRIRK4d_secret_u2WJTHVO3BmpJfkzdXaY", "connector": "stripe_test", "created_at": 1729756752886, "currency": "USD", "customer_email": "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303", "customer_id": "StripeCustomer", "description": "Its my first payment request", "dispute_list": [], "headers": {}, "log_count": 9, "merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6", "merchant_id": "merchant_1726046328", "metadata": "{\"data2\":\"camel\",\"login_date\":\"2019-09-10T10:11:12Z\",\"new_customer\":\"true\"}", "modified_at": 1729756754123, "organization_id": "org_VpSHOjsYfDvabVYJgCAJ", "payment_id": "pay_QdstJpRVAcRKHzRIRK4d", "payment_method": "card", "payment_method_data": "{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":null,\"card_extended_bin\":null,\"authentication_data\":null,\"card_issuing_country\":null}}", "payment_method_type": "credit", "profile_id": "pro_v5sFoHe80OeiUlIonocM", "refund_list": [ { "attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1", "connector": "stripe_test", "connector_refund_id": "dummy_ref_6HyIEJcmDyE75QiFnv76", "connector_transaction_id": "pay_BV1cUypv6paxZvJl2SiQ", "created_at": 1729756766669, "currency": "USD", "description": "Customer returned product", "external_reference_id": "ref_Tc3KfBVm5HEuzECytr9g", "internal_reference_id": "refid_vDztMj3wI0ETCFXEoWUG", "merchant_id": "merchant_1726046328", "modified_at": 1729756767668, "organization_id": "org_VpSHOjsYfDvabVYJgCAJ", "payment_id": "pay_QdstJpRVAcRKHzRIRK4d", "profile_id": "pro_v5sFoHe80OeiUlIonocM", "refund_amount": 600, "refund_arn": "", "refund_id": "ref_Tc3KfBVm5HEuzECytr9g", "refund_reason": "Customer returned product", "refund_status": "success", "refund_type": "instant_refund", "sent_to_gateway": true, "tenant_id": "public", "total_amount": 6540 } ], "refunds_status": "partial_refunded", "return_url": "https://google.com/", "source_type": "kafka", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "status": "succeeded", "tenant_id": "public", "timestamp": "2024-10-24T07:59:12.886Z" } ], "status": "Success" }, { "count": 0, "index": "sessionizer_refunds", "hits": [], "status": "Success" }, { "count": 0, "index": "sessionizer_disputes", "hits": [], "status": "Failure" } ] ```
[ "crates/analytics/src/opensearch.rs", "crates/analytics/src/search.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6121
Bug: [REFACTOR]: [WISE] Add amount conversion framework to Wise ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://docs.wise.com/api-docs/api-reference/card) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [ ] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :package: Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rs index 8123ae7ec79..9f41651b2f9 100644 --- a/crates/router/src/connector/wise.rs +++ b/crates/router/src/connector/wise.rs @@ -1,8 +1,8 @@ pub mod transformers; -use std::fmt::Debug; #[cfg(feature = "payouts")] use common_utils::request::RequestContent; +use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector}; use error_stack::{report, ResultExt}; #[cfg(feature = "payouts")] use masking::PeekInterface; @@ -10,6 +10,7 @@ use masking::PeekInterface; use router_env::{instrument, tracing}; use self::transformers as wise; +use super::utils::convert_amount; use crate::{ configs::settings, core::errors::{self, CustomResult}, @@ -27,8 +28,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Wise; +#[derive(Clone)] +pub struct Wise { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} + +impl Wise { + pub fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wise where @@ -362,7 +373,13 @@ impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::Pay req: &types::PayoutsRouterData<api::PoQuote>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = wise::WisePayoutQuoteRequest::try_from(req)?; + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.source_currency, + )?; + let connector_router_data = wise::WiseRouterData::from((amount, req)); + let connector_req = wise::WisePayoutQuoteRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -441,7 +458,13 @@ impl req: &types::PayoutsRouterData<api::PoRecipient>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = wise::WiseRecipientCreateRequest::try_from(req)?; + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.source_currency, + )?; + let connector_router_data = wise::WiseRouterData::from((amount, req)); + let connector_req = wise::WiseRecipientCreateRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/router/src/connector/wise/transformers.rs b/crates/router/src/connector/wise/transformers.rs index fe82ffa5954..94849f2b1ca 100644 --- a/crates/router/src/connector/wise/transformers.rs +++ b/crates/router/src/connector/wise/transformers.rs @@ -2,6 +2,7 @@ use api_models::payouts::PayoutMethodData; #[cfg(feature = "payouts")] use common_utils::pii::Email; +use common_utils::types::MinorUnit; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -16,6 +17,20 @@ use crate::{ }, }; use crate::{core::errors, types}; +#[derive(Debug, Serialize)] +pub struct WiseRouterData<T> { + pub amount: MinorUnit, + pub router_data: T, +} + +impl<T> From<(MinorUnit, T)> for WiseRouterData<T> { + fn from((amount, router_data): (MinorUnit, T)) -> Self { + Self { + amount, + router_data, + } + } +} pub struct WiseAuthType { pub(super) api_key: Secret<String>, @@ -156,8 +171,8 @@ pub struct WiseRecipientCreateResponse { pub struct WisePayoutQuoteRequest { source_currency: String, target_currency: String, - source_amount: Option<i64>, - target_amount: Option<i64>, + source_amount: Option<MinorUnit>, + target_amount: Option<MinorUnit>, pay_out: WisePayOutOption, } @@ -348,9 +363,12 @@ fn get_payout_bank_details( // Payouts recipient create request transform #[cfg(feature = "payouts")] -impl<F> TryFrom<&types::PayoutsRouterData<F>> for WiseRecipientCreateRequest { +impl<F> TryFrom<&WiseRouterData<&types::PayoutsRouterData<F>>> for WiseRecipientCreateRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from( + item_data: &WiseRouterData<&types::PayoutsRouterData<F>>, + ) -> Result<Self, Self::Error> { + let item = item_data.router_data; let request = item.request.to_owned(); let customer_details = request.customer_details.to_owned(); let payout_method_data = item.get_payout_method_data()?; @@ -420,14 +438,17 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseRecipientCreateResponse> // Payouts quote request transform #[cfg(feature = "payouts")] -impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutQuoteRequest { +impl<F> TryFrom<&WiseRouterData<&types::PayoutsRouterData<F>>> for WisePayoutQuoteRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from( + item_data: &WiseRouterData<&types::PayoutsRouterData<F>>, + ) -> Result<Self, Self::Error> { + let item = item_data.router_data; let request = item.request.to_owned(); let payout_type = request.get_payout_type()?; match payout_type { storage_enums::PayoutType::Bank => Ok(Self { - source_amount: Some(request.amount), + source_amount: Some(item_data.amount), source_currency: request.source_currency.to_string(), target_amount: None, target_currency: request.destination_currency.to_string(), diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index a3046213272..681dd8ee2b0 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -480,7 +480,7 @@ impl ConnectorData { enums::Connector::Stripe => { Ok(ConnectorEnum::Old(Box::new(connector::Stripe::new()))) } - enums::Connector::Wise => Ok(ConnectorEnum::Old(Box::new(&connector::Wise))), + enums::Connector::Wise => Ok(ConnectorEnum::Old(Box::new(connector::Wise::new()))), enums::Connector::Worldline => { Ok(ConnectorEnum::Old(Box::new(&connector::Worldline))) } diff --git a/crates/router/tests/connectors/wise.rs b/crates/router/tests/connectors/wise.rs index 76167804670..984a43d48a7 100644 --- a/crates/router/tests/connectors/wise.rs +++ b/crates/router/tests/connectors/wise.rs @@ -28,7 +28,7 @@ impl utils::Connector for WiseTest { fn get_payout_data(&self) -> Option<api::ConnectorData> { use router::connector::Wise; Some(utils::construct_connector_data_old( - Box::new(&Wise), + Box::new(Wise::new()), types::Connector::Wise, api::GetToken::Connector, None,
2024-10-30T14:13:48Z
## Description <!-- Describe your changes in detail --> This pull request introduces significant changes to the Wise connector in the `crates/router` module, focusing on the integration of a new amount conversion utility and refactoring to utilize a new `WiseRouterData` struct. The changes enhance how amounts are handled and improve the overall structure and clarity of the code. ### Refactoring and Enhancements: * **Amount Conversion Utility Integration:** - Added `amount_converter` to the `Wise` struct and integrated it into the `new` method. - Updated `convert_amount` usage in `WisePayoutQuoteRequest` and `WiseRecipientCreateRequest` implementations to use the new `amount_converter`. [[1]](diffhunk://#diff-a149ab1c35f89dd3b0eed2fca15df170708e81962550226b958ae6c367515043L365-R382) [[2]](diffhunk://#diff-a149ab1c35f89dd3b0eed2fca15df170708e81962550226b958ae6c367515043L444-R467) * **Introduction of `WiseRouterData` Struct:** - Added `WiseRouterData` struct to encapsulate amount and router data, and implemented conversion from a tuple. - Modified `WisePayoutQuoteRequest` and `WiseRecipientCreateRequest` to use `WiseRouterData` for transformations. [[1]](diffhunk://#diff-1e46db110c015ea743fbbe850bf756011b4311a1ef56fe5ee75c911bb4960b15L351-R371) [[2]](diffhunk://#diff-1e46db110c015ea743fbbe850bf756011b4311a1ef56fe5ee75c911bb4960b15L423-R451) ### Codebase Simplification: * **Removal of Unnecessary Debug Trait:** - Removed the `Debug` trait from the `Wise` struct. * **Update in Connector Initialization:** - Updated the initialization of the `Wise` connector to use the `new` method in `api.rs` and test files. [[1]](diffhunk://#diff-71935350b305eb696195bc45f26e6f2a16097fb17bd5ac55192eb1d03558bf9aL483-R483) [[2]](diffhunk://#diff-0177b5efcc163c3f657a8c60b0162bf272a68a5e22beb13f6eb309bd34d54166L31-R31) ### Minor Enhancements: * **Type Adjustments:** - Changed various fields in `WiseRecipientCreateRequest` and `WisePayoutQuoteRequest` to use `StringMajorUnit` instead of `String` or `i64`. [[1]](diffhunk://#diff-1e46db110c015ea743fbbe850bf756011b4311a1ef56fe5ee75c911bb4960b15L64-R79) [[2]](diffhunk://#diff-1e46db110c015ea743fbbe850bf756011b4311a1ef56fe5ee75c911bb4960b15L159-R175) These changes collectively improve the robustness and maintainability of the Wise connector, ensuring better handling of amount conversions and a cleaner code structure. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #6121 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
72ee434003eef744d516343a2f803264f226d92a
[ "crates/router/src/connector/wise.rs", "crates/router/src/connector/wise/transformers.rs", "crates/router/src/types/api.rs", "crates/router/tests/connectors/wise.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4774
Bug: feat: Add config to force 2FA for users Currently 2FA is skippable in all the environments. We need to force 2FA in prod later at some point, so there should be config to which forces 2FA is enabled.
diff --git a/config/config.example.toml b/config/config.example.toml index b0d3c743673..5aa45af85ac 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -395,6 +395,7 @@ password_validity_in_days = 90 # Number of days after which password shoul two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside totp_issuer_name = "Hyperswitch" # Name of the issuer for TOTP base_url = "" # Base url used for user specific redirects and emails +force_two_factor_auth = false # Whether to force two factor authentication for all users #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 780af87383f..b99577c7f06 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -138,6 +138,7 @@ password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Integ" base_url = "https://integ.hyperswitch.io" +force_two_factor_auth = false [frm] enabled = true @@ -394,4 +395,4 @@ connector_list = "" card_networks = "Visa, AmericanExpress, Mastercard" [network_tokenization_supported_connectors] -connector_list = "cybersource" \ No newline at end of file +connector_list = "cybersource" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 430475b9e5c..5aaae800e32 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -145,6 +145,7 @@ password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Production" base_url = "https://live.hyperswitch.io" +force_two_factor_auth = false [frm] enabled = false @@ -408,4 +409,4 @@ connector_list = "" card_networks = "Visa, AmericanExpress, Mastercard" [network_tokenization_supported_connectors] -connector_list = "cybersource" \ No newline at end of file +connector_list = "cybersource" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 99d4253aea3..d6868eb94b1 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -145,6 +145,7 @@ password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Sandbox" base_url = "https://app.hyperswitch.io" +force_two_factor_auth = false [frm] enabled = true diff --git a/config/development.toml b/config/development.toml index cbc4573e555..18df92797bc 100644 --- a/config/development.toml +++ b/config/development.toml @@ -316,6 +316,7 @@ password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch Dev" base_url = "http://localhost:8080" +force_two_factor_auth = false [bank_config.eps] stripe = { banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index cf07a1bf9be..760d6e370f7 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -56,6 +56,7 @@ password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch" base_url = "http://localhost:8080" +force_two_factor_auth = false [locker] host = "" diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 089089038b8..089426c68ba 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -211,6 +211,7 @@ pub struct TwoFactorAuthStatusResponseWithAttempts { #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorStatus { pub status: Option<TwoFactorAuthStatusResponseWithAttempts>, + pub is_skippable: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 61e026ae2c5..f675aad11a7 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -556,6 +556,7 @@ pub struct UserSettings { pub two_factor_auth_expiry_in_secs: i64, pub totp_issuer_name: String, pub base_url: String, + pub force_two_factor_auth: bool, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 822c29b21d9..35b26926ed2 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1319,7 +1319,7 @@ pub async fn list_user_roles_details( )) .await .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to construct proifle map")? + .attach_printable("Failed to construct profile map")? .into_iter() .map(|profile| (profile.get_id().to_owned(), profile.profile_name)) .collect::<HashMap<_, _>>(); @@ -1927,7 +1927,7 @@ pub async fn terminate_two_factor_auth( .change_context(UserErrors::InternalServerError)? .into(); - if !skip_two_factor_auth { + if state.conf.user.force_two_factor_auth || !skip_two_factor_auth { if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? && !tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await? { @@ -1997,9 +1997,12 @@ pub async fn check_two_factor_auth_status_with_attempts( .await .change_context(UserErrors::InternalServerError)? .into(); + + let is_skippable = state.conf.user.force_two_factor_auth.not(); if user_from_db.get_totp_status() == TotpStatus::NotSet { return Ok(ApplicationResponse::Json(user_api::TwoFactorStatus { status: None, + is_skippable, })); }; @@ -2018,6 +2021,7 @@ pub async fn check_two_factor_auth_status_with_attempts( totp, recovery_code, }), + is_skippable, })) } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 11268e15e54..1e9f355a5e6 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -35,6 +35,7 @@ jwt_secret = "secret" password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch" +force_two_factor_auth = false [locker] host = ""
2024-10-30T08:44:07Z
## Description <!-- Describe your changes in detail --> This PR will add force 2fa environment variable. When enabled it will force users to complete 2FA to access the control center. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> `config/config.example.toml` `config/deployments/integration_test.toml` `config/deployments/production.toml` `config/deployments/sandbox.toml` `config/development.toml` `config/docker_compose.toml` `loadtest/config/development.toml` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #4774. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. 2FA Status API - `is_skippable` field is added in the response. ``` curl --location 'http://localhost:8080/user/2fa/v2' \ --header 'Authorization: JWT' \ ``` ``` { "status": null, "is_skippable": true } ``` 2. Terminate 2FA API - This API will now not allow skip 2FA if the `force_two_factor_auth` ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: JWT' \ ``` ``` { "error": { "type": "invalid_request", "message": "Two factor auth required", "code": "UR_40" } } ```
19cf0f7437a8d16ee4da254d2a3e2659879be68c
1. 2FA Status API - `is_skippable` field is added in the response. ``` curl --location 'http://localhost:8080/user/2fa/v2' \ --header 'Authorization: JWT' \ ``` ``` { "status": null, "is_skippable": true } ``` 2. Terminate 2FA API - This API will now not allow skip 2FA if the `force_two_factor_auth` ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: JWT' \ ``` ``` { "error": { "type": "invalid_request", "message": "Two factor auth required", "code": "UR_40" } } ```
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/user.rs", "crates/router/src/configs/settings.rs", "crates/router/src/core/user.rs", "loadtest/config/development.toml" ]
juspay/hyperswitch
juspay__hyperswitch-4669
Bug: Adding events for Payment Reject Created from #4525 This covers adding events for Payment Reject operation This event should include the payment data similar to [PaymentCancel](https://github.com/juspay/hyperswitch/pull/4166) It should also include any metadata for the event e.g reason for payment rejection, error codes, rejection source etc
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 55b93501275..23531d2342d 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -12,6 +12,7 @@ use crate::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentAddress, PaymentData}, }, + events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ @@ -209,7 +210,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for Payme async fn update_trackers<'b>( &'b self, state: &'b SessionState, - _req_state: ReqState, + req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, @@ -264,6 +265,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for Payme ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + let error_code = payment_data.payment_attempt.error_code.clone(); + let error_message = payment_data.payment_attempt.error_message.clone(); + req_state + .event_context + .event(AuditEvent::new(AuditEventType::PaymentReject { + error_code, + error_message, + })) + .with(payment_data.to_event()) + .emit(); Ok((Box::new(self), payment_data)) } diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs index a6b0884d21d..5f2ed10bc5f 100644 --- a/crates/router/src/events/audit_events.rs +++ b/crates/router/src/events/audit_events.rs @@ -33,6 +33,10 @@ pub enum AuditEventType { }, PaymentApprove, PaymentCreate, + PaymentReject { + error_code: Option<String>, + error_message: Option<String>, + }, } #[derive(Debug, Clone, Serialize)] @@ -74,6 +78,7 @@ impl Event for AuditEvent { AuditEventType::PaymentUpdate { .. } => "payment_update", AuditEventType::PaymentApprove { .. } => "payment_approve", AuditEventType::PaymentCreate { .. } => "payment_create", + AuditEventType::PaymentReject { .. } => "payment_rejected", }; format!( "{event_type}-{}",
2024-10-29T18:10:34Z
## Description <!-- Describe your changes in detail --> Pass along request_state to payment_core Modify the UpdateTracker trait to accept request state Modify the PaymentReject implementation of UpdateTracker to generate an event ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> Files changed 1. `crates/router/src/core/payments/operations/payment_reject.rs` 2. `crates/router/src/events/audit_events.rs` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Resolves #4669 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This requires FRM related flows to be tested, and may not be tested locally.
ce95b6538dca4515b04ac65c2b1063bdd0a9c3a7
This requires FRM related flows to be tested, and may not be tested locally.
[ "crates/router/src/core/payments/operations/payment_reject.rs", "crates/router/src/events/audit_events.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6461
Bug: fix(analytics): add dynamic limit by clause in failure reasons metric query Currently, the `limit by` clause in query_builder of `failure_reasons` metric has only `connector` hardcoded. Should change this behaviour to enable dynamic addition of `group by` fields to the `limit by `clause as well.
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs index 70ae64e0115..bcbce0502d2 100644 --- a/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs @@ -148,17 +148,20 @@ where .attach_printable("Error adding order by clause") .switch()?; - for dim in dimensions.iter() { - if dim != &PaymentDimensions::ErrorReason { - outer_query_builder - .add_order_by_clause(dim, Order::Ascending) - .attach_printable("Error adding order by clause") - .switch()?; - } + let filtered_dimensions: Vec<&PaymentDimensions> = dimensions + .iter() + .filter(|&&dim| dim != PaymentDimensions::ErrorReason) + .collect(); + + for dim in &filtered_dimensions { + outer_query_builder + .add_order_by_clause(*dim, Order::Ascending) + .attach_printable("Error adding order by clause") + .switch()?; } outer_query_builder - .set_limit_by(5, &[PaymentDimensions::Connector]) + .set_limit_by(5, &filtered_dimensions) .attach_printable("Error adding limit clause") .switch()?;
2024-10-29T10:33:52Z
## Description <!-- Describe your changes in detail --> - Currently, the `limit by` clause in query_builder of `failure_reasons` metric has only `connector` hardcoded. - Changed this behaviour to enable dynamic addition of `group` by fields to the `limit by` clause as well. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Prevent errors when connector is not passed as a group by and also provide dynamic combination of error_reason with other filters like connector, payment_method, payment_method_type, etc. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: test_admin' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDI2NjUwMCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.p6u5u3k6-80GBh7_0Kri9VmIvZc3h2bx48UEQraeLA8' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-09-11T18:30:00Z", "endTime": "2024-10-30T09:22:00Z" }, "groupByNames": [ "connector", "payment_method", "payment_method_type", "error_reason" ], "filters": { "merchant_id": ["merchant_1726046328"] }, "source": "BATCH", "metrics": [ "failure_reasons" ], "delta": true } ]' ``` Sample response: ```bash { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "failure_reason_count": 1, "failure_reason_count_without_smart_retries": 1, "currency": null, "status": null, "connector": "stripe_test", "authentication_type": null, "payment_method": "card", "payment_method_type": "credit", "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": "TEST FAILURE - 1", "time_range": { "start_time": "2024-09-11T18:30:00.000Z", "end_time": "2024-10-30T09:22:00.000Z" }, "time_bucket": "2024-09-11 18:30:00" } ], "metaData": [ { "total_payment_processed_amount": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 1, "total_failure_reasons_count_without_smart_retries": 1 } ] } ```
55a81eb4692979036d0bfd43e445d3e1db6601e7
Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: test_admin' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDI2NjUwMCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.p6u5u3k6-80GBh7_0Kri9VmIvZc3h2bx48UEQraeLA8' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-09-11T18:30:00Z", "endTime": "2024-10-30T09:22:00Z" }, "groupByNames": [ "connector", "payment_method", "payment_method_type", "error_reason" ], "filters": { "merchant_id": ["merchant_1726046328"] }, "source": "BATCH", "metrics": [ "failure_reasons" ], "delta": true } ]' ``` Sample response: ```bash { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "failure_reason_count": 1, "failure_reason_count_without_smart_retries": 1, "currency": null, "status": null, "connector": "stripe_test", "authentication_type": null, "payment_method": "card", "payment_method_type": "credit", "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": "TEST FAILURE - 1", "time_range": { "start_time": "2024-09-11T18:30:00.000Z", "end_time": "2024-10-30T09:22:00.000Z" }, "time_bucket": "2024-09-11 18:30:00" } ], "metaData": [ { "total_payment_processed_amount": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 1, "total_failure_reasons_count_without_smart_retries": 1 } ] } ```
[ "crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6457
Bug: feat(users): add tenant_id in user roles - Use global interface for user roles - Add column tenant_id in user_roles - Handle insertion of tenant_id - Hadle token validation, a token issued in one tenant should not work in other tenancy
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index e2ab676b2d3..782d7f50eac 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1343,6 +1343,8 @@ diesel::table! { #[max_length = 64] entity_type -> Nullable<Varchar>, version -> UserRoleVersion, + #[max_length = 64] + tenant_id -> Varchar, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 5651bf95dd9..73d2de8c573 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1289,6 +1289,8 @@ diesel::table! { #[max_length = 64] entity_type -> Nullable<Varchar>, version -> UserRoleVersion, + #[max_length = 64] + tenant_id -> Varchar, } } diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs index 71caa41deac..ceddbfd61e4 100644 --- a/crates/diesel_models/src/user_role.rs +++ b/crates/diesel_models/src/user_role.rs @@ -24,6 +24,7 @@ pub struct UserRole { pub entity_id: Option<String>, pub entity_type: Option<EntityType>, pub version: enums::UserRoleVersion, + pub tenant_id: String, } impl UserRole { @@ -87,6 +88,7 @@ pub struct UserRoleNew { pub entity_id: Option<String>, pub entity_type: Option<EntityType>, pub version: enums::UserRoleVersion, + pub tenant_id: String, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index ed25725358a..2c9aec39b04 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -1853,7 +1853,7 @@ pub mod routes { return Err(OpenSearchError::AccessForbiddenError)?; } let user_roles: HashSet<UserRole> = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, org_id: Some(&auth.org_id), @@ -1976,7 +1976,7 @@ pub mod routes { return Err(OpenSearchError::AccessForbiddenError)?; } let user_roles: HashSet<UserRole> = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, org_id: Some(&auth.org_id), diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index df4ce1d8148..5c7b77246e2 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -94,6 +94,8 @@ pub enum UserErrors { MaxTotpAttemptsReached, #[error("Maximum attempts reached for Recovery Code")] MaxRecoveryCodeAttemptsReached, + #[error("Forbidden tenant id")] + ForbiddenTenantId, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -239,6 +241,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::MaxRecoveryCodeAttemptsReached => { AER::BadRequest(ApiError::new(sub_code, 49, self.get_error_message(), None)) } + Self::ForbiddenTenantId => { + AER::BadRequest(ApiError::new(sub_code, 50, self.get_error_message(), None)) + } } } } @@ -289,6 +294,7 @@ impl UserErrors { Self::AuthConfigParsingError => "Auth config parsing error", Self::SSOFailed => "Invalid SSO request", Self::JwtProfileIdMissing => "profile_id missing in JWT", + Self::ForbiddenTenantId => "Forbidden tenant id", } } } diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs index ea3459709c6..521c978e3c2 100644 --- a/crates/router/src/core/recon.rs +++ b/crates/router/src/core/recon.rs @@ -94,6 +94,7 @@ pub async fn generate_recon_token( &state.conf, user.org_id.clone(), user.profile_id.clone(), + user.tenant_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 35b26926ed2..aad2537c3d9 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -598,7 +598,7 @@ async fn handle_existing_user_invitation( let now = common_utils::date_time::now(); if state - .store + .global_store .find_user_role_by_user_id_and_lineage( invitee_user_from_db.get_user_id(), &user_from_token.org_id, @@ -614,7 +614,7 @@ async fn handle_existing_user_invitation( } if state - .store + .global_store .find_user_role_by_user_id_and_lineage( invitee_user_from_db.get_user_id(), &user_from_token.org_id, @@ -650,6 +650,10 @@ async fn handle_existing_user_invitation( EntityType::Organization => { user_role .add_entity(domain::OrganizationLevel { + tenant_id: user_from_token + .tenant_id + .clone() + .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), }) .insert_in_v2(state) @@ -658,6 +662,10 @@ async fn handle_existing_user_invitation( EntityType::Merchant => { user_role .add_entity(domain::MerchantLevel { + tenant_id: user_from_token + .tenant_id + .clone() + .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), }) @@ -671,6 +679,10 @@ async fn handle_existing_user_invitation( .ok_or(UserErrors::InternalServerError)?; user_role .add_entity(domain::ProfileLevel { + tenant_id: user_from_token + .tenant_id + .clone() + .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), profile_id: profile_id.clone(), @@ -777,6 +789,10 @@ async fn handle_new_user_invitation( EntityType::Organization => { user_role .add_entity(domain::OrganizationLevel { + tenant_id: user_from_token + .tenant_id + .clone() + .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), }) .insert_in_v2(state) @@ -785,6 +801,10 @@ async fn handle_new_user_invitation( EntityType::Merchant => { user_role .add_entity(domain::MerchantLevel { + tenant_id: user_from_token + .tenant_id + .clone() + .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), }) @@ -798,6 +818,10 @@ async fn handle_new_user_invitation( .ok_or(UserErrors::InternalServerError)?; user_role .add_entity(domain::ProfileLevel { + tenant_id: user_from_token + .tenant_id + .clone() + .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), profile_id: profile_id.clone(), @@ -864,6 +888,7 @@ async fn handle_new_user_invitation( org_id: user_from_token.org_id.clone(), role_id: request.role_id.clone(), profile_id: None, + tenant_id: user_from_token.tenant_id.clone(), }; let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired; @@ -909,7 +934,7 @@ pub async fn resend_invite( .into(); let user_role = match state - .store + .global_store .find_user_role_by_user_id_and_lineage( user.get_user_id(), &user_from_token.org_id, @@ -932,7 +957,7 @@ pub async fn resend_invite( let user_role = match user_role { Some(user_role) => user_role, None => state - .store + .global_store .find_user_role_by_user_id_and_lineage( user.get_user_id(), &user_from_token.org_id, @@ -1102,6 +1127,13 @@ pub async fn create_internal_user( } })?; + let default_tenant_id = common_utils::consts::DEFAULT_TENANT.to_string(); + + if state.tenant.tenant_id != default_tenant_id { + return Err(UserErrors::ForbiddenTenantId) + .attach_printable("Operation allowed only for the default tenant."); + } + let internal_merchant_id = common_utils::id_type::MerchantId::get_internal_user_merchant_id( consts::user_role::INTERNAL_USER_MERCHANT_ID, ); @@ -1142,6 +1174,7 @@ pub async fn create_internal_user( UserStatus::Active, ) .add_entity(domain::MerchantLevel { + tenant_id: default_tenant_id, org_id: internal_merchant.organization_id, merchant_id: internal_merchant_id, }) @@ -1195,7 +1228,7 @@ pub async fn list_user_roles_details( } let user_roles_set = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: required_user.get_user_id(), org_id: Some(&user_from_token.org_id), @@ -2372,7 +2405,7 @@ pub async fn list_orgs_for_user( } let orgs = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_token.user_id.as_str(), org_id: None, @@ -2437,7 +2470,7 @@ pub async fn list_merchants_for_user_in_org( .change_context(UserErrors::InternalServerError)?, EntityType::Merchant | EntityType::Profile => { let merchant_ids = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_token.user_id.as_str(), org_id: Some(&user_from_token.org_id), @@ -2516,7 +2549,7 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account( .change_context(UserErrors::InternalServerError)?, EntityType::Profile => { let profile_ids = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_token.user_id.as_str(), org_id: Some(&user_from_token.org_id), @@ -2592,7 +2625,7 @@ pub async fn switch_org_for_user( } let user_role = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, org_id: Some(&request.org_id), @@ -2621,6 +2654,7 @@ pub async fn switch_org_for_user( request.org_id.clone(), user_role.role_id.clone(), profile_id.clone(), + user_from_token.tenant_id, ) .await?; @@ -2764,7 +2798,7 @@ pub async fn switch_merchant_for_user_in_org( EntityType::Merchant | EntityType::Profile => { let user_role = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, org_id: Some(&user_from_token.org_id), @@ -2805,6 +2839,7 @@ pub async fn switch_merchant_for_user_in_org( org_id.clone(), role_id.clone(), profile_id, + user_from_token.tenant_id, ) .await?; @@ -2879,7 +2914,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant( EntityType::Profile => { let user_role = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload{ user_id:&user_from_token.user_id, org_id: Some(&user_from_token.org_id), @@ -2910,6 +2945,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant( user_from_token.org_id.clone(), role_id.clone(), profile_id, + user_from_token.tenant_id, ) .await?; diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 27c1e2ae494..95a8b7d51d1 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -156,7 +156,7 @@ pub async fn update_user_role( let mut is_updated = false; let v2_user_role_to_be_updated = match state - .store + .global_store .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), &user_from_token.org_id, @@ -210,7 +210,7 @@ pub async fn update_user_role( } state - .store + .global_store .update_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), &user_from_token.org_id, @@ -229,7 +229,7 @@ pub async fn update_user_role( } let v1_user_role_to_be_updated = match state - .store + .global_store .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), &user_from_token.org_id, @@ -283,7 +283,7 @@ pub async fn update_user_role( } state - .store + .global_store .update_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), &user_from_token.org_id, @@ -470,7 +470,7 @@ pub async fn delete_user_role( // Find in V2 let user_role_v2 = match state - .store + .global_store .find_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), &user_from_token.org_id, @@ -517,7 +517,7 @@ pub async fn delete_user_role( user_role_deleted_flag = true; state - .store + .global_store .delete_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), &user_from_token.org_id, @@ -532,7 +532,7 @@ pub async fn delete_user_role( // Find in V1 let user_role_v1 = match state - .store + .global_store .find_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), &user_from_token.org_id, @@ -579,7 +579,7 @@ pub async fn delete_user_role( user_role_deleted_flag = true; state - .store + .global_store .delete_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), &user_from_token.org_id, @@ -599,7 +599,7 @@ pub async fn delete_user_role( // Check if user has any more role associations let remaining_roles = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_db.get_user_id(), org_id: None, @@ -780,7 +780,7 @@ pub async fn list_invitations_for_user( user_from_token: auth::UserIdFromAuth, ) -> UserResponse<Vec<user_role_api::ListInvitationForUserResponse>> { let user_roles = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, org_id: None, diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 81319ae4c0b..de0c6282fc2 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -123,7 +123,6 @@ pub trait StorageInterface: + routing_algorithm::RoutingAlgorithmInterface + gsm::GsmInterface + unified_translations::UnifiedTranslationsInterface - + user_role::UserRoleInterface + authorization::AuthorizationInterface + user::sample_data::BatchSampleDataInterface + health_check::HealthCheckDbInterface @@ -144,6 +143,7 @@ pub trait GlobalStorageInterface: + Sync + dyn_clone::DynClone + user::UserInterface + + user_role::UserRoleInterface + user_key_store::UserKeyStoreInterface + 'static { diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index d32c6b254eb..2d9a949879a 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -234,6 +234,7 @@ impl UserRoleInterface for MockDb { entity_id: None, entity_type: None, version: enums::UserRoleVersion::V1, + tenant_id: user_role.tenant_id, }; db_user_roles.push(user_role.clone()); Ok(user_role) diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index cbd694f3acd..b80ade89178 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -179,6 +179,7 @@ pub struct UserFromSinglePurposeToken { pub user_id: String, pub origin: domain::Origin, pub path: Vec<TokenPurpose>, + pub tenant_id: Option<String>, } #[cfg(feature = "olap")] @@ -189,6 +190,7 @@ pub struct SinglePurposeToken { pub origin: domain::Origin, pub path: Vec<TokenPurpose>, pub exp: u64, + pub tenant_id: Option<String>, } #[cfg(feature = "olap")] @@ -199,6 +201,7 @@ impl SinglePurposeToken { origin: domain::Origin, settings: &Settings, path: Vec<TokenPurpose>, + tenant_id: Option<String>, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::SINGLE_PURPOSE_TOKEN_TIME_IN_SECS); @@ -209,6 +212,7 @@ impl SinglePurposeToken { origin, exp, path, + tenant_id, }; jwt::generate_jwt(&token_payload, settings).await } @@ -222,6 +226,7 @@ pub struct AuthToken { pub exp: u64, pub org_id: id_type::OrganizationId, pub profile_id: Option<id_type::ProfileId>, + pub tenant_id: Option<String>, } #[cfg(feature = "olap")] @@ -233,6 +238,7 @@ impl AuthToken { settings: &Settings, org_id: id_type::OrganizationId, profile_id: Option<id_type::ProfileId>, + tenant_id: Option<String>, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(exp_duration)?.as_secs(); @@ -243,6 +249,7 @@ impl AuthToken { exp, org_id, profile_id, + tenant_id, }; jwt::generate_jwt(&token_payload, settings).await } @@ -255,6 +262,7 @@ pub struct UserFromToken { pub role_id: String, pub org_id: id_type::OrganizationId, pub profile_id: Option<id_type::ProfileId>, + pub tenant_id: Option<String>, } pub struct UserIdFromAuth { @@ -268,6 +276,7 @@ pub struct SinglePurposeOrLoginToken { pub role_id: Option<String>, pub purpose: Option<TokenPurpose>, pub exp: u64, + pub tenant_id: Option<String>, } pub trait AuthInfo { @@ -751,6 +760,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; if self.0 != payload.purpose { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); @@ -761,6 +774,7 @@ where user_id: payload.user_id.clone(), origin: payload.origin.clone(), path: payload.path, + tenant_id: payload.tenant_id, }, AuthenticationType::SinglePurposeJwt { user_id: payload.user_id, @@ -785,6 +799,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; if self.0 != payload.purpose { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); @@ -795,6 +813,7 @@ where user_id: payload.user_id.clone(), origin: payload.origin.clone(), path: payload.path, + tenant_id: payload.tenant_id, }), AuthenticationType::SinglePurposeJwt { user_id: payload.user_id, @@ -824,6 +843,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let is_purpose_equal = payload .purpose @@ -1396,6 +1419,11 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; + let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; @@ -1424,6 +1452,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; @@ -1435,6 +1467,7 @@ where org_id: payload.org_id, role_id: payload.role_id, profile_id: payload.profile_id, + tenant_id: payload.tenant_id, }, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, @@ -1459,6 +1492,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; @@ -1518,6 +1555,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; @@ -1559,6 +1600,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; @@ -1595,6 +1640,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; @@ -1740,6 +1789,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; @@ -1773,6 +1826,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; if payload.merchant_id != self.merchant_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); @@ -1912,6 +1969,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; if payload.merchant_id != self.merchant_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); @@ -1987,6 +2048,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; @@ -2153,6 +2218,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; @@ -2210,6 +2279,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let profile_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?; @@ -2282,6 +2355,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; @@ -2341,6 +2418,11 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; + Ok(( UserFromToken { user_id: payload.user_id.clone(), @@ -2348,6 +2430,7 @@ where org_id: payload.org_id, role_id: payload.role_id, profile_id: payload.profile_id, + tenant_id: payload.tenant_id, }, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, @@ -2372,6 +2455,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; Ok(((), AuthenticationType::NoAuth)) } @@ -2389,6 +2476,11 @@ where state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() @@ -2709,6 +2801,10 @@ where if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } + authorization::check_tenant( + payload.tenant_id.clone(), + &state.session_state().tenant.tenant_id, + )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index fe6ffac6ffc..35a0b159ab2 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -112,6 +112,18 @@ pub fn check_permission( ) } +pub fn check_tenant(token_tenant_id: Option<String>, header_tenant_id: &str) -> RouterResult<()> { + if let Some(tenant_id) = token_tenant_id { + if tenant_id != header_tenant_id { + return Err(ApiErrorResponse::InvalidJwtToken).attach_printable(format!( + "Token tenant ID: '{}' does not match Header tenant ID: '{}'", + tenant_id, header_tenant_id + )); + } + } + Ok(()) +} + fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { state .store() diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index c48fe3320f3..5a881728b07 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -689,7 +689,10 @@ impl NewUser { let org_user_role = self .get_no_level_user_role(role_id, user_status) - .add_entity(OrganizationLevel { org_id }); + .add_entity(OrganizationLevel { + tenant_id: state.tenant.tenant_id.clone(), + org_id, + }); org_user_role.insert_in_v2(&state).await } @@ -1116,17 +1119,20 @@ pub struct NoLevel; #[derive(Clone)] pub struct OrganizationLevel { + pub tenant_id: String, pub org_id: id_type::OrganizationId, } #[derive(Clone)] pub struct MerchantLevel { + pub tenant_id: String, pub org_id: id_type::OrganizationId, pub merchant_id: id_type::MerchantId, } #[derive(Clone)] pub struct ProfileLevel { + pub tenant_id: String, pub org_id: id_type::OrganizationId, pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, @@ -1163,6 +1169,7 @@ impl NewUserRole<NoLevel> { } pub struct EntityInfo { + tenant_id: String, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, @@ -1175,6 +1182,7 @@ impl From<OrganizationLevel> for EntityInfo { Self { entity_id: value.org_id.get_string_repr().to_owned(), entity_type: EntityType::Organization, + tenant_id: value.tenant_id, org_id: value.org_id, merchant_id: None, profile_id: None, @@ -1187,6 +1195,7 @@ impl From<MerchantLevel> for EntityInfo { Self { entity_id: value.merchant_id.get_string_repr().to_owned(), entity_type: EntityType::Merchant, + tenant_id: value.tenant_id, org_id: value.org_id, profile_id: None, merchant_id: Some(value.merchant_id), @@ -1199,6 +1208,7 @@ impl From<ProfileLevel> for EntityInfo { Self { entity_id: value.profile_id.get_string_repr().to_owned(), entity_type: EntityType::Profile, + tenant_id: value.tenant_id, org_id: value.org_id, merchant_id: Some(value.merchant_id), profile_id: Some(value.profile_id), @@ -1225,6 +1235,7 @@ where entity_id: Some(entity.entity_id), entity_type: Some(entity.entity_type), version: UserRoleVersion::V2, + tenant_id: entity.tenant_id, } } @@ -1234,7 +1245,7 @@ where let new_v2_role = self.convert_to_new_v2_role(entity.into()); state - .store + .global_store .insert_user_role(new_v2_role) .await .change_context(UserErrors::InternalServerError) diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index 3fc05285ea8..86f10f1ceb7 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -65,7 +65,7 @@ impl SPTFlow { .is_password_rotate_required(state) .map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)), Self::MerchantSelect => Ok(state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user.get_user_id(), org_id: None, @@ -93,6 +93,7 @@ impl SPTFlow { next_flow.origin.clone(), &state.conf, next_flow.path.to_vec(), + Some(state.tenant.tenant_id.clone()), ) .await .map(|token| token.into()) @@ -132,6 +133,7 @@ impl JWTFlow { .ok_or(report!(UserErrors::InternalServerError)) .attach_printable("org_id not found")?, Some(profile_id), + Some(user_role.tenant_id.clone()), ) .await .map(|token| token.into()) @@ -299,7 +301,7 @@ impl NextFlow { self.user.get_verification_days_left(state)?; } let user_role = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: self.user.get_user_id(), org_id: None, diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 8975519fd97..c4647907ff9 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -92,6 +92,7 @@ pub async fn generate_jwt_auth_token_with_attributes( org_id: id_type::OrganizationId, role_id: String, profile_id: id_type::ProfileId, + tenant_id: Option<String>, ) -> UserResult<Secret<String>> { let token = AuthToken::new_token( user_id, @@ -100,6 +101,7 @@ pub async fn generate_jwt_auth_token_with_attributes( &state.conf, org_id, Some(profile_id), + tenant_id, ) .await?; Ok(Secret::new(token)) diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 6f0d94d2927..aaf313a196e 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -142,7 +142,7 @@ pub async fn update_v1_and_v2_user_roles_in_db( Result<UserRole, Report<StorageError>>, ) { let updated_v1_role = state - .store + .global_store .update_user_role_by_user_id_and_lineage( user_id, org_id, @@ -158,7 +158,7 @@ pub async fn update_v1_and_v2_user_roles_in_db( }); let updated_v2_role = state - .store + .global_store .update_user_role_by_user_id_and_lineage( user_id, org_id, @@ -228,7 +228,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( }; let user_roles = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, org_id: Some(&org_id), @@ -272,7 +272,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( }; let user_roles = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, org_id: None, @@ -317,7 +317,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( }; let user_roles = state - .store + .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, org_id: None, @@ -407,7 +407,7 @@ pub async fn fetch_user_roles_by_payload( request_entity_type: Option<EntityType>, ) -> UserResult<HashSet<UserRole>> { Ok(state - .store + .global_store .list_user_roles_by_org_id(payload) .await .change_context(UserErrors::InternalServerError)? diff --git a/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/down.sql b/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/down.sql new file mode 100644 index 00000000000..fb9a32c0767 --- /dev/null +++ b/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE user_roles DROP COLUMN IF EXISTS tenant_id; \ No newline at end of file diff --git a/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/up.sql b/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/up.sql new file mode 100644 index 00000000000..68e75f7f5d8 --- /dev/null +++ b/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE user_roles ADD COLUMN IF NOT EXISTS tenant_id VARCHAR(64) NOT NULL DEFAULT 'public';
2024-10-28T21:08:20Z
## Description This PR includes - Use of global interface for user roles table - Add tenant_id column in user_roles table - Handle user_role insertions with correct value for tenant_id - Auth Changes: Token validation, token issued in one tenancy should not be valid in other ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#6457](https://github.com/juspay/hyperswitch/issues/6457) ## How did you test it? With the multi -tenancy feature flag enabled, when trying to signup by sending different headers for different tenancies> ``` curl --location 'http://localhost:8080/user/signup?token_only=true' \ --header 'x-tenant-id: test' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "global_test@juspay.in", "password": "Hyper@123" }' ``` ``` curl --location 'http://localhost:8080/user/signup?token_only=true' \ --header 'x-tenant-id: public' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "global_public@juspay.in", "password": "Hyper@123" }' ``` The user role is getting inserted properly, with correct values of tenant_id. <img width="1473" alt="Screenshot 2024-10-29 at 2 42 08 AM" src="https://github.com/user-attachments/assets/f312adce-b405-4684-8891-16caf324cbb4"> When Trying to use one JWT token with some other header that doesn't match with origin tenancy where it is issued it is authentication part is throwing error. Which is correct.
a5ac69d1a77e772e430df8c4187942de44f23079
With the multi -tenancy feature flag enabled, when trying to signup by sending different headers for different tenancies> ``` curl --location 'http://localhost:8080/user/signup?token_only=true' \ --header 'x-tenant-id: test' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "global_test@juspay.in", "password": "Hyper@123" }' ``` ``` curl --location 'http://localhost:8080/user/signup?token_only=true' \ --header 'x-tenant-id: public' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "global_public@juspay.in", "password": "Hyper@123" }' ``` The user role is getting inserted properly, with correct values of tenant_id. <img width="1473" alt="Screenshot 2024-10-29 at 2 42 08 AM" src="https://github.com/user-attachments/assets/f312adce-b405-4684-8891-16caf324cbb4"> When Trying to use one JWT token with some other header that doesn't match with origin tenancy where it is issued it is authentication part is throwing error. Which is correct.
[ "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/schema_v2.rs", "crates/diesel_models/src/user_role.rs", "crates/router/src/analytics.rs", "crates/router/src/core/errors/user.rs", "crates/router/src/core/recon.rs", "crates/router/src/core/user.rs", "crates/router/src/core/user_role.rs", "crates/router/src/db.rs", "crates/router/src/db/user_role.rs", "crates/router/src/services/authentication.rs", "crates/router/src/services/authorization.rs", "crates/router/src/types/domain/user.rs", "crates/router/src/types/domain/user/decision_manager.rs", "crates/router/src/utils/user.rs", "crates/router/src/utils/user_role.rs", "migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/down.sql", "migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-6456
Bug: reduce cargo build jobs to 3 from 4 try reducing cargo build jobs to 3
2024-10-28T12:41:02Z
## Description <!-- Describe your changes in detail --> This PR reduces build jobs to 3 to see if it helps pass Cypress CI checks ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> NA ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> CI should work
cd6265887adf7c17136e9fb608e97e6dd535e360
CI should work
[]
juspay/hyperswitch
juspay__hyperswitch-6484
Bug: Refactor: interpolate success based routing params with their specific values
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 47d75b2e835..389af3dab7b 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -615,8 +615,11 @@ impl Default for SuccessBasedRoutingConfig { pub enum SuccessBasedRoutingConfigParams { PaymentMethod, PaymentMethodType, - Currency, AuthenticationType, + Currency, + Country, + CardNetwork, + CardBin, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs index 5afd3024551..e7b229a8070 100644 --- a/crates/external_services/src/grpc_client.rs +++ b/crates/external_services/src/grpc_client.rs @@ -5,7 +5,6 @@ use std::{fmt::Debug, sync::Arc}; #[cfg(feature = "dynamic_routing")] use dynamic_routing::{DynamicRoutingClientConfig, RoutingStrategy}; -use router_env::logger; use serde; /// Struct contains all the gRPC Clients @@ -38,8 +37,6 @@ impl GrpcClientSettings { .await .expect("Failed to establish a connection with the Dynamic Routing Server"); - logger::info!("Connection established with gRPC Server"); - Arc::new(GrpcClients { #[cfg(feature = "dynamic_routing")] dynamic_routing: dynamic_routing_connection, diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs index 343dd80e951..0546d05ba7c 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing.rs @@ -9,6 +9,7 @@ use error_stack::ResultExt; use http_body_util::combinators::UnsyncBoxBody; use hyper::body::Bytes; use hyper_util::client::legacy::connect::HttpConnector; +use router_env::logger; use serde; use success_rate::{ success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig, @@ -80,6 +81,7 @@ impl DynamicRoutingClientConfig { let success_rate_client = match self { Self::Enabled { host, port } => { let uri = format!("http://{}:{}", host, port).parse::<tonic::transport::Uri>()?; + logger::info!("Connection established with dynamic routing gRPC Server"); Some(SuccessRateCalculatorClient::with_origin(client, uri)) } Self::Disabled => None, @@ -98,6 +100,7 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { &self, id: String, success_rate_based_config: SuccessBasedRoutingConfig, + params: String, label_input: Vec<RoutableConnectorChoice>, ) -> DynamicRoutingResult<CalSuccessRateResponse>; /// To update the success rate with the given label @@ -105,6 +108,7 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { &self, id: String, success_rate_based_config: SuccessBasedRoutingConfig, + params: String, response: Vec<RoutableConnectorChoiceWithStatus>, ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse>; } @@ -115,24 +119,9 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { &self, id: String, success_rate_based_config: SuccessBasedRoutingConfig, + params: String, label_input: Vec<RoutableConnectorChoice>, ) -> DynamicRoutingResult<CalSuccessRateResponse> { - let params = success_rate_based_config - .params - .map(|vec| { - vec.into_iter().fold(String::new(), |mut acc_str, params| { - if !acc_str.is_empty() { - acc_str.push(':') - } - acc_str.push_str(params.to_string().as_str()); - acc_str - }) - }) - .get_required_value("params") - .change_context(DynamicRoutingError::MissingRequiredField { - field: "params".to_string(), - })?; - let labels = label_input .into_iter() .map(|conn_choice| conn_choice.to_string()) @@ -167,6 +156,7 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { &self, id: String, success_rate_based_config: SuccessBasedRoutingConfig, + params: String, label_input: Vec<RoutableConnectorChoiceWithStatus>, ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse> { let config = success_rate_based_config @@ -182,22 +172,6 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { }) .collect(); - let params = success_rate_based_config - .params - .map(|vec| { - vec.into_iter().fold(String::new(), |mut acc_str, params| { - if !acc_str.is_empty() { - acc_str.push(':') - } - acc_str.push_str(params.to_string().as_str()); - acc_str - }) - }) - .get_required_value("params") - .change_context(DynamicRoutingError::MissingRequiredField { - field: "params".to_string(), - })?; - let request = tonic::Request::new(UpdateSuccessRateWindowRequest { id, params, diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index d095b471e2d..96321d09794 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -330,6 +330,8 @@ pub enum RoutingError { MetadataParsingError, #[error("Unable to retrieve success based routing config")] SuccessBasedRoutingConfigError, + #[error("Params not found in success based routing config")] + SuccessBasedRoutingParamsNotFoundError, #[error("Unable to calculate success based routing config from dynamic routing service")] SuccessRateCalculationError, #[error("Success rate client from dynamic routing gRPC service not initialized")] diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 5d75001b118..4ad00df9c24 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -72,6 +72,8 @@ use super::{ #[cfg(feature = "frm")] use crate::core::fraud_check as frm_core; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use crate::core::routing::helpers as routing_helpers; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] use crate::types::api::convert_connector_data_to_routable_connectors; use crate::{ configs::settings::{ApplePayPreDecryptFlow, PaymentMethodTypeTokenFilter}, @@ -5580,10 +5582,46 @@ where #[cfg(all(feature = "v1", feature = "dynamic_routing"))] let connectors = { if business_profile.dynamic_routing_algorithm.is_some() { - routing::perform_success_based_routing(state, connectors.clone(), business_profile) - .await - .map_err(|e| logger::error!(success_rate_routing_error=?e)) - .unwrap_or(connectors) + let success_based_routing_config_params_interpolator = + routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new( + payment_data.get_payment_attempt().payment_method, + payment_data.get_payment_attempt().payment_method_type, + payment_data.get_payment_attempt().authentication_type, + payment_data.get_payment_attempt().currency, + payment_data + .get_billing_address() + .and_then(|address| address.address) + .and_then(|address| address.country), + payment_data + .get_payment_attempt() + .payment_method_data + .as_ref() + .and_then(|data| data.as_object()) + .and_then(|card| card.get("card")) + .and_then(|data| data.as_object()) + .and_then(|card| card.get("card_network")) + .and_then(|network| network.as_str()) + .map(|network| network.to_string()), + payment_data + .get_payment_attempt() + .payment_method_data + .as_ref() + .and_then(|data| data.as_object()) + .and_then(|card| card.get("card")) + .and_then(|data| data.as_object()) + .and_then(|card| card.get("card_isin")) + .and_then(|card_isin| card_isin.as_str()) + .map(|card_isin| card_isin.to_string()), + ); + routing::perform_success_based_routing( + state, + connectors.clone(), + business_profile, + success_based_routing_config_params_interpolator, + ) + .await + .map_err(|e| logger::error!(success_rate_routing_error=?e)) + .unwrap_or(connectors) } else { connectors } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 0234b97032c..f0381dbf822 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -21,7 +21,7 @@ use tracing_futures::Instrument; use super::{Operation, OperationSessionSetters, PostUpdateTracker}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use crate::core::routing::helpers::push_metrics_for_success_based_routing; +use crate::core::routing::helpers as routing_helpers; use crate::{ connector::utils::PaymentResponseRouterData, consts, @@ -1968,13 +1968,44 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( let state = state.clone(); let business_profile = business_profile.clone(); let payment_attempt = payment_attempt.clone(); + let success_based_routing_config_params_interpolator = + routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new( + payment_attempt.payment_method, + payment_attempt.payment_method_type, + payment_attempt.authentication_type, + payment_attempt.currency, + payment_data + .address + .get_payment_billing() + .and_then(|address| address.clone().address) + .and_then(|address| address.country), + payment_attempt + .payment_method_data + .as_ref() + .and_then(|data| data.as_object()) + .and_then(|card| card.get("card")) + .and_then(|data| data.as_object()) + .and_then(|card| card.get("card_network")) + .and_then(|network| network.as_str()) + .map(|network| network.to_string()), + payment_attempt + .payment_method_data + .as_ref() + .and_then(|data| data.as_object()) + .and_then(|card| card.get("card")) + .and_then(|data| data.as_object()) + .and_then(|card| card.get("card_isin")) + .and_then(|card_isin| card_isin.as_str()) + .map(|card_isin| card_isin.to_string()), + ); tokio::spawn( async move { - push_metrics_for_success_based_routing( + routing_helpers::push_metrics_with_update_window_for_success_based_routing( &state, &payment_attempt, routable_connectors, &business_profile, + success_based_routing_config_params_interpolator, ) .await .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e)) @@ -1984,6 +2015,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( ); } } + payment_data.payment_intent = payment_intent; payment_data.payment_attempt = payment_attempt; router_data.payment_method_status.and_then(|status| { diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 40721e9b4c3..28321529ef2 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1240,6 +1240,7 @@ pub async fn perform_success_based_routing( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, business_profile: &domain::Profile, + success_based_routing_config_params_interpolator: routing::helpers::SuccessBasedRoutingConfigParamsInterpolator, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { let success_based_dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = business_profile @@ -1293,6 +1294,14 @@ pub async fn perform_success_based_routing( .change_context(errors::RoutingError::SuccessBasedRoutingConfigError) .attach_printable("unable to fetch success_rate based dynamic routing configs")?; + let success_based_routing_config_params = success_based_routing_config_params_interpolator + .get_string_val( + success_based_routing_configs + .params + .as_ref() + .ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)?, + ); + let tenant_business_profile_id = routing::helpers::generate_tenant_business_profile_id( &state.tenant.redis_key_prefix, business_profile.get_id().get_string_repr(), @@ -1302,6 +1311,7 @@ pub async fn perform_success_based_routing( .calculate_success_rate( tenant_business_profile_id, success_based_routing_configs, + success_based_routing_config_params, routable_connectors, ) .await diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 31cd4234714..0250d00d1bb 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -640,11 +640,12 @@ pub async fn fetch_success_based_routing_configs( /// metrics for success based dynamic routing #[cfg(all(feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] -pub async fn push_metrics_for_success_based_routing( +pub async fn push_metrics_with_update_window_for_success_based_routing( state: &SessionState, payment_attempt: &storage::PaymentAttempt, routable_connectors: Vec<routing_types::RoutableConnectorChoice>, business_profile: &domain::Profile, + success_based_routing_config_params_interpolator: SuccessBasedRoutingConfigParamsInterpolator, ) -> RouterResult<()> { let success_based_dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile @@ -697,10 +698,20 @@ pub async fn push_metrics_for_success_based_routing( business_profile.get_id().get_string_repr(), ); + let success_based_routing_config_params = success_based_routing_config_params_interpolator + .get_string_val( + success_based_routing_configs + .params + .as_ref() + .ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError) + .change_context(errors::ApiErrorResponse::InternalServerError)?, + ); + let success_based_connectors = client .calculate_success_rate( tenant_business_profile_id.clone(), success_based_routing_configs.clone(), + success_based_routing_config_params.clone(), routable_connectors.clone(), ) .await @@ -725,9 +736,10 @@ pub async fn push_metrics_for_success_based_routing( let (first_success_based_connector, merchant_connector_id) = first_success_based_connector_label .split_once(':') .ok_or(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "unable to split connector_name and mca_id from the first connector obtained from dynamic routing service", - )?; + .attach_printable(format!( + "unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service", + first_success_based_connector_label + ))?; let outcome = get_success_based_metrics_outcome_for_payment( &payment_status_attribute, @@ -802,6 +814,7 @@ pub async fn push_metrics_for_success_based_routing( .update_success_rate( tenant_business_profile_id, success_based_routing_configs, + success_based_routing_config_params, vec![routing_types::RoutableConnectorChoiceWithStatus::new( routing_types::RoutableConnectorChoice { choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, @@ -956,3 +969,76 @@ pub async fn default_success_based_routing_setup( ); Ok(ApplicationResponse::Json(new_record)) } + +pub struct SuccessBasedRoutingConfigParamsInterpolator { + pub payment_method: Option<common_enums::PaymentMethod>, + pub payment_method_type: Option<common_enums::PaymentMethodType>, + pub authentication_type: Option<common_enums::AuthenticationType>, + pub currency: Option<common_enums::Currency>, + pub country: Option<common_enums::CountryAlpha2>, + pub card_network: Option<String>, + pub card_bin: Option<String>, +} + +impl SuccessBasedRoutingConfigParamsInterpolator { + pub fn new( + payment_method: Option<common_enums::PaymentMethod>, + payment_method_type: Option<common_enums::PaymentMethodType>, + authentication_type: Option<common_enums::AuthenticationType>, + currency: Option<common_enums::Currency>, + country: Option<common_enums::CountryAlpha2>, + card_network: Option<String>, + card_bin: Option<String>, + ) -> Self { + Self { + payment_method, + payment_method_type, + authentication_type, + currency, + country, + card_network, + card_bin, + } + } + + pub fn get_string_val( + &self, + params: &Vec<routing_types::SuccessBasedRoutingConfigParams>, + ) -> String { + let mut parts: Vec<String> = Vec::new(); + for param in params { + let val = match param { + routing_types::SuccessBasedRoutingConfigParams::PaymentMethod => self + .payment_method + .as_ref() + .map_or(String::new(), |pm| pm.to_string()), + routing_types::SuccessBasedRoutingConfigParams::PaymentMethodType => self + .payment_method_type + .as_ref() + .map_or(String::new(), |pmt| pmt.to_string()), + routing_types::SuccessBasedRoutingConfigParams::AuthenticationType => self + .authentication_type + .as_ref() + .map_or(String::new(), |at| at.to_string()), + routing_types::SuccessBasedRoutingConfigParams::Currency => self + .currency + .as_ref() + .map_or(String::new(), |cur| cur.to_string()), + routing_types::SuccessBasedRoutingConfigParams::Country => self + .country + .as_ref() + .map_or(String::new(), |cn| cn.to_string()), + routing_types::SuccessBasedRoutingConfigParams::CardNetwork => { + self.card_network.clone().unwrap_or_default() + } + routing_types::SuccessBasedRoutingConfigParams::CardBin => { + self.card_bin.clone().unwrap_or_default() + } + }; + if !val.is_empty() { + parts.push(val); + } + } + parts.join(":") + } +}
2024-10-28T08:12:03Z
## Description <!-- Describe your changes in detail --> This will interpolate the success_based_routing config params with the specific payment's values: So for now the redis key was something like PaymentMethod:Currency After this change it will be something like Card:USD ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This is tested locally can't be tested on sbx or integ as it requires access for redis. <img width="1292" alt="Screenshot 2024-11-07 at 5 14 06 PM" src="https://github.com/user-attachments/assets/b5a096ae-3ab7-4e94-9aa0-502b7ab94417">
90d9ffc1d2e13b83931762b05632056520eea07f
This is tested locally can't be tested on sbx or integ as it requires access for redis. <img width="1292" alt="Screenshot 2024-11-07 at 5 14 06 PM" src="https://github.com/user-attachments/assets/b5a096ae-3ab7-4e94-9aa0-502b7ab94417">
[ "crates/api_models/src/routing.rs", "crates/external_services/src/grpc_client.rs", "crates/external_services/src/grpc_client/dynamic_routing.rs", "crates/router/src/core/errors.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/operations/payment_response.rs", "crates/router/src/core/payments/routing.rs", "crates/router/src/core/routing/helpers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6449
Bug: Update broken readme icon Updating broken readme icon along with reposition of the hero image
diff --git a/README.md b/README.md index ccdd6e19b6d..10fdb6afc76 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ The single API to access payment ecosystems across 130+ countries</div> <p align="center"> <a href="https://github.com/juspay/hyperswitch/actions?query=workflow%3ACI+branch%3Amain"> - <img src="https://github.com/juspay/hyperswitch/workflows/CI/badge.svg" /> + <img src="https://github.com/juspay/hyperswitch/workflows/CI-push/badge.svg" /> </a> <a href="https://github.com/juspay/hyperswitch/blob/main/LICENSE"> <img src="https://img.shields.io/github/license/juspay/hyperswitch" /> @@ -44,7 +44,6 @@ The single API to access payment ecosystems across 130+ countries</div> </p> <hr> -<img src="./docs/imgs/switch.png" /> Hyperswitch is a community-led, open payments switch designed to empower digital businesses by providing fast, reliable, and affordable access to the best payments infrastructure. @@ -58,7 +57,8 @@ Here are the components of Hyperswitch that deliver the whole solution: Jump in and contribute to these repositories to help improve and expand Hyperswitch! -<br> +<img src="./docs/imgs/switch.png" /> + <a href="#Quick Setup"> <h2 id="quick-setup">⚡️ Quick Setup</h2>
2024-10-28T05:20:16Z
TOC icon and reposition of the hero image in readme ## Description <!-- Describe your changes in detail --> Updated the icon of CI Push and repositioned the hero image closes #6449 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
cd6265887adf7c17136e9fb608e97e6dd535e360
[ "README.md" ]
juspay/hyperswitch
juspay__hyperswitch-6751
Bug: [BUG] Description for refunds - list is not apt ### Bug Description https://api-reference.hyperswitch.io/api-reference/refunds/refunds--list This should be - `Lists all the refunds associated with the merchant, or for a specific payment if payment_id is provided` Current one implies that it'll return refunds of a payment_id if it is not provided. ### Expected Behavior It should reflect that refunds accociated with a merchant will be returned if payment_id is missing, otherwise only for that payment_id. ### Actual Behavior Incorrect message being shown. ### Steps To Reproduce Visit - https://api-reference.hyperswitch.io/api-reference/refunds/refunds--list ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/openapi/src/routes/refunds.rs b/crates/openapi/src/routes/refunds.rs index 4e096e243a8..0ff0891ee54 100644 --- a/crates/openapi/src/routes/refunds.rs +++ b/crates/openapi/src/routes/refunds.rs @@ -115,7 +115,7 @@ pub async fn refunds_update() {} /// Refunds - List /// -/// Lists all the refunds associated with the merchant or a payment_id if payment_id is not provided +/// Lists all the refunds associated with the merchant, or for a specific payment if payment_id is provided #[utoipa::path( post, path = "/refunds/list",
2024-10-27T18:30:36Z
## Description The current description for refund - list is incorrect. Newer one looks more apt. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6751. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
086115f47379b06185a1753979fc6dd9dc945afd
[ "crates/openapi/src/routes/refunds.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6354
Bug: Refactor: add deep health check for dynamic routing
diff --git a/config/config.example.toml b/config/config.example.toml index 191f2ba7f8b..12df81d82c9 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -789,3 +789,4 @@ connector_list = "cybersource" # Supported connectors for network tokenization [grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration host = "localhost" # Client Host port = 7000 # Client Port +service = "dynamo" # Service name diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 0eab330652a..fa0c0484a77 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -326,3 +326,4 @@ check_token_status_url= "" # base url to check token status from token servic [grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration host = "localhost" # Client Host port = 7000 # Client Port +service = "dynamo" # Service name diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index e8668aab502..a5d702e26fb 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -20,6 +20,7 @@ v1 = ["common_utils/v1"] v2 = ["common_utils/v2", "customer_v2"] customer_v2 = ["common_utils/customer_v2"] payment_methods_v2 = ["common_utils/payment_methods_v2"] +dynamic_routing = [] [dependencies] actix-web = { version = "4.5.1", optional = true } diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs index 1e86e2964c7..4a1c009e43e 100644 --- a/crates/api_models/src/health_check.rs +++ b/crates/api_models/src/health_check.rs @@ -1,3 +1,4 @@ +use std::collections::hash_map::HashMap; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RouterHealthCheckResponse { pub database: bool, @@ -9,10 +10,22 @@ pub struct RouterHealthCheckResponse { #[cfg(feature = "olap")] pub opensearch: bool, pub outgoing_request: bool, + #[cfg(feature = "dynamic_routing")] + pub grpc_health_check: HealthCheckMap, } impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} +/// gRPC based services eligible for Health check +#[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HealthCheckServices { + /// Dynamic routing service + DynamicRoutingService, +} + +pub type HealthCheckMap = HashMap<HealthCheckServices, bool>; + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SchedulerHealthCheckResponse { pub database: bool, diff --git a/crates/external_services/build.rs b/crates/external_services/build.rs index 605ef699715..0a4938e94b4 100644 --- a/crates/external_services/build.rs +++ b/crates/external_services/build.rs @@ -3,11 +3,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { #[cfg(feature = "dynamic_routing")] { // Get the directory of the current crate - let proto_file = router_env::workspace_path() - .join("proto") - .join("success_rate.proto"); + + let proto_path = router_env::workspace_path().join("proto"); + let success_rate_proto_file = proto_path.join("success_rate.proto"); + + let health_check_proto_file = proto_path.join("health_check.proto"); + let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?); + // Compile the .proto file - tonic_build::compile_protos(proto_file).expect("Failed to compile success rate proto file"); + tonic_build::configure() + .out_dir(out_dir) + .compile( + &[success_rate_proto_file, health_check_proto_file], + &[proto_path], + ) + .expect("Failed to compile proto files"); } Ok(()) } diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs index e7b229a8070..8981a1094d6 100644 --- a/crates/external_services/src/grpc_client.rs +++ b/crates/external_services/src/grpc_client.rs @@ -1,11 +1,28 @@ /// Dyanimc Routing Client interface implementation #[cfg(feature = "dynamic_routing")] pub mod dynamic_routing; +/// gRPC based Heath Check Client interface implementation +#[cfg(feature = "dynamic_routing")] +pub mod health_check_client; use std::{fmt::Debug, sync::Arc}; #[cfg(feature = "dynamic_routing")] use dynamic_routing::{DynamicRoutingClientConfig, RoutingStrategy}; +#[cfg(feature = "dynamic_routing")] +use health_check_client::HealthCheckClient; +#[cfg(feature = "dynamic_routing")] +use http_body_util::combinators::UnsyncBoxBody; +#[cfg(feature = "dynamic_routing")] +use hyper::body::Bytes; +#[cfg(feature = "dynamic_routing")] +use hyper_util::client::legacy::connect::HttpConnector; use serde; +#[cfg(feature = "dynamic_routing")] +use tonic::Status; + +#[cfg(feature = "dynamic_routing")] +/// Hyper based Client type for maintaining connection pool for all gRPC services +pub type Client = hyper_util::client::legacy::Client<HttpConnector, UnsyncBoxBody<Bytes, Status>>; /// Struct contains all the gRPC Clients #[derive(Debug, Clone)] @@ -13,6 +30,9 @@ pub struct GrpcClients { /// The routing client #[cfg(feature = "dynamic_routing")] pub dynamic_routing: RoutingStrategy, + /// Health Check client for all gRPC services + #[cfg(feature = "dynamic_routing")] + pub health_client: HealthCheckClient, } /// Type that contains the configs required to construct a gRPC client with its respective services. #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, Default)] @@ -29,17 +49,30 @@ impl GrpcClientSettings { /// This function will be called at service startup. #[allow(clippy::expect_used)] pub async fn get_grpc_client_interface(&self) -> Arc<GrpcClients> { + #[cfg(feature = "dynamic_routing")] + let client = + hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) + .http2_only(true) + .build_http(); + #[cfg(feature = "dynamic_routing")] let dynamic_routing_connection = self .dynamic_routing_client .clone() - .get_dynamic_routing_connection() + .get_dynamic_routing_connection(client.clone()) .await .expect("Failed to establish a connection with the Dynamic Routing Server"); + #[cfg(feature = "dynamic_routing")] + let health_client = HealthCheckClient::build_connections(self, client) + .await + .expect("Failed to build gRPC connections"); + Arc::new(GrpcClients { #[cfg(feature = "dynamic_routing")] dynamic_routing: dynamic_routing_connection, + #[cfg(feature = "dynamic_routing")] + health_client, }) } } diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs index 3264f065b51..7ec42de0d7c 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing.rs @@ -6,9 +6,6 @@ use api_models::routing::{ }; use common_utils::{errors::CustomResult, ext_traits::OptionExt, transformers::ForeignTryFrom}; use error_stack::ResultExt; -use http_body_util::combinators::UnsyncBoxBody; -use hyper::body::Bytes; -use hyper_util::client::legacy::connect::HttpConnector; use router_env::logger; use serde; use success_rate::{ @@ -18,7 +15,8 @@ use success_rate::{ InvalidateWindowsResponse, LabelWithStatus, UpdateSuccessRateWindowConfig, UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse, }; -use tonic::Status; + +use super::Client; #[allow( missing_docs, unused_qualifications, @@ -45,8 +43,6 @@ pub enum DynamicRoutingError { SuccessRateBasedRoutingFailure(String), } -type Client = hyper_util::client::legacy::Client<HttpConnector, UnsyncBoxBody<Bytes, Status>>; - /// Type that consists of all the services provided by the client #[derive(Debug, Clone)] pub struct RoutingStrategy { @@ -64,6 +60,8 @@ pub enum DynamicRoutingClientConfig { host: String, /// The port of the client port: u16, + /// Service name + service: String, }, #[default] /// If the dynamic routing client config has been disabled @@ -74,13 +72,10 @@ impl DynamicRoutingClientConfig { /// establish connection with the server pub async fn get_dynamic_routing_connection( self, + client: Client, ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> { - let client = - hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) - .http2_only(true) - .build_http(); let success_rate_client = match self { - Self::Enabled { host, port } => { + Self::Enabled { host, port, .. } => { let uri = format!("http://{}:{}", host, port).parse::<tonic::transport::Uri>()?; logger::info!("Connection established with dynamic routing gRPC Server"); Some(SuccessRateCalculatorClient::with_origin(client, uri)) diff --git a/crates/external_services/src/grpc_client/health_check_client.rs b/crates/external_services/src/grpc_client/health_check_client.rs new file mode 100644 index 00000000000..94d78df7955 --- /dev/null +++ b/crates/external_services/src/grpc_client/health_check_client.rs @@ -0,0 +1,149 @@ +use std::{collections::HashMap, fmt::Debug}; + +use api_models::health_check::{HealthCheckMap, HealthCheckServices}; +use common_utils::{errors::CustomResult, ext_traits::AsyncExt}; +use error_stack::ResultExt; +pub use health_check::{ + health_check_response::ServingStatus, health_client::HealthClient, HealthCheckRequest, + HealthCheckResponse, +}; +use router_env::logger; + +#[allow( + missing_docs, + unused_qualifications, + clippy::unwrap_used, + clippy::as_conversions, + clippy::use_self +)] +pub mod health_check { + tonic::include_proto!("grpc.health.v1"); +} + +use super::{Client, DynamicRoutingClientConfig, GrpcClientSettings}; + +/// Result type for Dynamic Routing +pub type HealthCheckResult<T> = CustomResult<T, HealthCheckError>; +/// Dynamic Routing Errors +#[derive(Debug, Clone, thiserror::Error)] +pub enum HealthCheckError { + /// The required input is missing + #[error("Missing fields: {0} for building the Health check connection")] + MissingFields(String), + /// Error from gRPC Server + #[error("Error from gRPC Server : {0}")] + ConnectionError(String), + /// status is invalid + #[error("Invalid Status from server")] + InvalidStatus, +} + +/// Health Check Client type +#[derive(Debug, Clone)] +pub struct HealthCheckClient { + /// Health clients for all gRPC based services + pub clients: HashMap<HealthCheckServices, HealthClient<Client>>, +} + +impl HealthCheckClient { + /// Build connections to all gRPC services + pub async fn build_connections( + config: &GrpcClientSettings, + client: Client, + ) -> Result<Self, Box<dyn std::error::Error>> { + let dynamic_routing_config = &config.dynamic_routing_client; + let connection = match dynamic_routing_config { + DynamicRoutingClientConfig::Enabled { + host, + port, + service, + } => Some((host.clone(), *port, service.clone())), + _ => None, + }; + + let mut client_map = HashMap::new(); + + if let Some(conn) = connection { + let uri = format!("http://{}:{}", conn.0, conn.1).parse::<tonic::transport::Uri>()?; + let health_client = HealthClient::with_origin(client, uri); + + client_map.insert(HealthCheckServices::DynamicRoutingService, health_client); + } + + Ok(Self { + clients: client_map, + }) + } + /// Perform health check for all services involved + pub async fn perform_health_check( + &self, + config: &GrpcClientSettings, + ) -> HealthCheckResult<HealthCheckMap> { + let dynamic_routing_config = &config.dynamic_routing_client; + let connection = match dynamic_routing_config { + DynamicRoutingClientConfig::Enabled { + host, + port, + service, + } => Some((host.clone(), *port, service.clone())), + _ => None, + }; + + let health_client = self + .clients + .get(&HealthCheckServices::DynamicRoutingService); + + // SAFETY : This is a safe cast as there exists a valid + // integer value for this variant + #[allow(clippy::as_conversions)] + let expected_status = ServingStatus::Serving as i32; + + let mut service_map = HealthCheckMap::new(); + + let health_check_succeed = connection + .as_ref() + .async_map(|conn| self.get_response_from_grpc_service(conn.2.clone(), health_client)) + .await + .transpose() + .change_context(HealthCheckError::ConnectionError( + "error calling dynamic routing service".to_string(), + )) + .map_err(|err| logger::error!(error=?err)) + .ok() + .flatten() + .is_some_and(|resp| resp.status == expected_status); + + connection.and_then(|_conn| { + service_map.insert( + HealthCheckServices::DynamicRoutingService, + health_check_succeed, + ) + }); + + Ok(service_map) + } + + async fn get_response_from_grpc_service( + &self, + service: String, + client: Option<&HealthClient<Client>>, + ) -> HealthCheckResult<HealthCheckResponse> { + let request = tonic::Request::new(HealthCheckRequest { service }); + + let mut client = client + .ok_or(HealthCheckError::MissingFields( + "[health_client]".to_string(), + ))? + .clone(); + + let response = client + .check(request) + .await + .change_context(HealthCheckError::ConnectionError( + "Failed to call dynamic routing service".to_string(), + ))? + .into_inner(); + + Ok(response) + } +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index b794443a047..f6e1f0efc69 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -37,7 +37,7 @@ v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "d v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] -dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing"] +dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"] # Partial Auth # The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request. diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs index 83faee677d4..31e8cc75f5b 100644 --- a/crates/router/src/core/health_check.rs +++ b/crates/router/src/core/health_check.rs @@ -1,5 +1,7 @@ #[cfg(feature = "olap")] use analytics::health_check::HealthCheck; +#[cfg(feature = "dynamic_routing")] +use api_models::health_check::HealthCheckMap; use api_models::health_check::HealthState; use error_stack::ResultExt; use router_env::logger; @@ -28,6 +30,11 @@ pub trait HealthCheckInterface { async fn health_check_opensearch( &self, ) -> CustomResult<HealthState, errors::HealthCheckDBError>; + + #[cfg(feature = "dynamic_routing")] + async fn health_check_grpc( + &self, + ) -> CustomResult<HealthCheckMap, errors::HealthCheckGRPCServiceError>; } #[async_trait::async_trait] @@ -158,4 +165,20 @@ impl HealthCheckInterface for app::SessionState { logger::debug!("Outgoing request successful"); Ok(HealthState::Running) } + + #[cfg(feature = "dynamic_routing")] + async fn health_check_grpc( + &self, + ) -> CustomResult<HealthCheckMap, errors::HealthCheckGRPCServiceError> { + let health_client = &self.grpc_client.health_client; + let grpc_config = &self.conf.grpc_client; + + let health_check_map = health_client + .perform_health_check(grpc_config) + .await + .change_context(errors::HealthCheckGRPCServiceError::FailedToCallService)?; + + logger::debug!("Health check successful"); + Ok(health_check_map) + } } diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs index c1cf28d00ad..0f2e6333647 100644 --- a/crates/router/src/routes/health.rs +++ b/crates/router/src/routes/health.rs @@ -95,6 +95,19 @@ async fn deep_health_check_func( logger::debug!("Analytics health check end"); + logger::debug!("gRPC health check begin"); + + #[cfg(feature = "dynamic_routing")] + let grpc_health_check = state.health_check_grpc().await.map_err(|error| { + let message = error.to_string(); + error.change_context(errors::ApiErrorResponse::HealthCheckError { + component: "gRPC services", + message, + }) + })?; + + logger::debug!("gRPC health check end"); + logger::debug!("Opensearch health check begin"); #[cfg(feature = "olap")] @@ -129,6 +142,8 @@ async fn deep_health_check_func( #[cfg(feature = "olap")] opensearch: opensearch_status.into(), outgoing_request: outgoing_check.into(), + #[cfg(feature = "dynamic_routing")] + grpc_health_check, }; Ok(api::ApplicationResponse::Json(response)) diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index 1cee96f49eb..10d7f4dc8e8 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -292,3 +292,9 @@ pub enum HealthCheckLockerError { #[error("Failed to establish Locker connection")] FailedToCallLocker, } + +#[derive(Debug, Clone, thiserror::Error)] +pub enum HealthCheckGRPCServiceError { + #[error("Failed to establish connection with gRPC service")] + FailedToCallService, +} diff --git a/proto/health_check.proto b/proto/health_check.proto new file mode 100644 index 00000000000..b246f59f690 --- /dev/null +++ b/proto/health_check.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; + +package grpc.health.v1; + +message HealthCheckRequest { + string service = 1; +} + +message HealthCheckResponse { + enum ServingStatus { + UNKNOWN = 0; + SERVING = 1; + NOT_SERVING = 2; + SERVICE_UNKNOWN = 3; // Used only by the Watch method. + } + ServingStatus status = 1; +} + +service Health { + rpc Check(HealthCheckRequest) returns (HealthCheckResponse); +} \ No newline at end of file
2024-10-25T19:11:21Z
## Description <!-- Describe your changes in detail --> Implemented gRPC based health check ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested locally ``` curl --location --request GET 'http://localhost:8080/health/ready' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Li5BLbzNIHjf2t0J6kYgS7sQurtmLubs1sGAxTE6MVo59aMBEMDSK6Qt8me7kJZQ' ``` Response ``` { "database": true, "redis": true, "analytics": true, "opensearch": true, "outgoing_request": true, "grpc_health_check": { "dynamic_routing_service": true } } ``` <img width="1345" alt="image" src="https://github.com/user-attachments/assets/aaae7e48-63b4-4dfc-b9c0-832dfe569469"> Response when runtime config is disabled ``` { "database": true, "redis": true, "analytics": true, "opensearch": true, "outgoing_request": true, "grpc_health_check": {} } ```
ea81432e3eb72d9a2e139e26741a42cdd8d31202
Tested locally ``` curl --location --request GET 'http://localhost:8080/health/ready' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Li5BLbzNIHjf2t0J6kYgS7sQurtmLubs1sGAxTE6MVo59aMBEMDSK6Qt8me7kJZQ' ``` Response ``` { "database": true, "redis": true, "analytics": true, "opensearch": true, "outgoing_request": true, "grpc_health_check": { "dynamic_routing_service": true } } ``` <img width="1345" alt="image" src="https://github.com/user-attachments/assets/aaae7e48-63b4-4dfc-b9c0-832dfe569469"> Response when runtime config is disabled ``` { "database": true, "redis": true, "analytics": true, "opensearch": true, "outgoing_request": true, "grpc_health_check": {} } ```
[ "config/config.example.toml", "config/deployments/env_specific.toml", "crates/api_models/Cargo.toml", "crates/api_models/src/health_check.rs", "crates/external_services/build.rs", "crates/external_services/src/grpc_client.rs", "crates/external_services/src/grpc_client/dynamic_routing.rs", "crates/external_services/src/grpc_client/health_check_client.rs", "crates/router/Cargo.toml", "crates/router/src/core/health_check.rs", "crates/router/src/routes/health.rs", "crates/storage_impl/src/errors.rs", "proto/health_check.proto" ]
juspay/hyperswitch
juspay__hyperswitch-6439
Bug: fix(authz): Proper descriptions for parents Currently descriptions for parent groups in invite page of control center are not entity specific. That means, customers in description will be visible for profile level users when it shouldn't.
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index a2c76ecc394..e0df36a3349 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -2,8 +2,9 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ role::{ - CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesRequest, - RoleInfoResponseNew, RoleInfoWithGroupsResponse, UpdateRoleRequest, + CreateRoleRequest, GetRoleRequest, GroupsAndResources, ListRolesAtEntityLevelRequest, + ListRolesRequest, RoleInfoResponseNew, RoleInfoWithGroupsResponse, RoleInfoWithParents, + UpdateRoleRequest, }, AuthorizationInfoResponse, DeleteUserRoleRequest, ListUsersInEntityRequest, UpdateUserRoleRequest, @@ -22,6 +23,8 @@ common_utils::impl_api_event_type!( RoleInfoResponseNew, RoleInfoWithGroupsResponse, ListUsersInEntityRequest, - ListRolesRequest + ListRolesRequest, + GroupsAndResources, + RoleInfoWithParents ) ); diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs index 885ec455e4c..7c877cd7477 100644 --- a/crates/api_models/src/user_role/role.rs +++ b/crates/api_models/src/user_role/role.rs @@ -1,5 +1,6 @@ -pub use common_enums::PermissionGroup; -use common_enums::{EntityType, RoleScope}; +use common_enums::{ + EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource, RoleScope, +}; #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateRoleRequest { @@ -22,6 +23,21 @@ pub struct RoleInfoWithGroupsResponse { pub role_scope: RoleScope, } +#[derive(Debug, serde::Serialize)] +pub struct RoleInfoWithParents { + pub role_id: String, + pub parent_groups: Vec<ParentGroupInfo>, + pub role_name: String, + pub role_scope: RoleScope, +} + +#[derive(Debug, serde::Serialize)] +pub struct ParentGroupInfo { + pub name: ParentGroup, + pub description: String, + pub scopes: Vec<PermissionScope>, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ListRolesRequest { pub entity_type: Option<EntityType>, @@ -57,3 +73,9 @@ pub struct MinimalRoleInfo { pub role_id: String, pub role_name: String, } + +#[derive(Debug, serde::Serialize)] +pub struct GroupsAndResources { + pub groups: Vec<PermissionGroup>, + pub resources: Vec<Resource>, +} diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index c103153eec8..faae71eda22 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2884,10 +2884,15 @@ pub enum PermissionGroup { AnalyticsView, UsersView, UsersManage, + // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsView, + // TODO: To be deprecated, make sure DB is migrated before removing MerchantDetailsManage, + // TODO: To be deprecated, make sure DB is migrated before removing OrganizationManage, ReconOps, + AccountView, + AccountManage, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] @@ -2897,14 +2902,12 @@ pub enum ParentGroup { Workflows, Analytics, Users, - #[serde(rename = "MerchantAccess")] - Merchant, - #[serde(rename = "OrganizationAccess")] - Organization, Recon, + Account, } -#[derive(Clone, Copy, Eq, PartialEq, Hash)] +#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)] +#[serde(rename_all = "snake_case")] pub enum Resource { Payment, Refund, @@ -2925,10 +2928,11 @@ pub enum Resource { Recon, } -#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] +#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] +#[serde(rename_all = "snake_case")] pub enum PermissionScope { - Read, - Write, + Read = 0, + Write = 1, } /// Name of banks supported by Hyperswitch diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 284be4ab4ba..27c1e2ae494 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -1,6 +1,9 @@ use std::collections::{HashMap, HashSet}; -use api_models::{user as user_api, user_role as user_role_api}; +use api_models::{ + user as user_api, + user_role::{self as user_role_api, role as role_api}, +}; use diesel_models::{ enums::{UserRoleVersion, UserStatus}, organization::OrganizationBridge, @@ -16,7 +19,11 @@ use crate::{ routes::{app::ReqState, SessionState}, services::{ authentication as auth, - authorization::{info, permission_groups::PermissionGroupExt, roles}, + authorization::{ + info, + permission_groups::{ParentGroupExt, PermissionGroupExt}, + roles, + }, ApplicationResponse, }, types::domain, @@ -72,6 +79,40 @@ pub async fn get_authorization_info_with_group_tag( )) } +pub async fn get_parent_group_info( + state: SessionState, + user_from_token: auth::UserFromToken, +) -> UserResponse<Vec<role_api::ParentGroupInfo>> { + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( + &state, + &user_from_token.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; + + let parent_groups = ParentGroup::get_descriptions_for_groups( + role_info.get_entity_type(), + PermissionGroup::iter().collect(), + ) + .into_iter() + .map(|(parent_group, description)| role_api::ParentGroupInfo { + name: parent_group.clone(), + description, + scopes: PermissionGroup::iter() + .filter_map(|group| (group.parent() == parent_group).then_some(group.scope())) + // TODO: Remove this hashset conversion when merhant access + // and organization access groups are removed + .collect::<HashSet<_>>() + .into_iter() + .collect(), + }) + .collect::<Vec<_>>(); + + Ok(ApplicationResponse::Json(parent_groups)) +} + pub async fn update_user_role( state: SessionState, user_from_token: auth::UserFromToken, diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index b5b5cab421f..1d37f7ac8d1 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -1,5 +1,7 @@ +use std::collections::HashSet; + use api_models::user_role::role::{self as role_api}; -use common_enums::{EntityType, RoleScope}; +use common_enums::{EntityType, ParentGroup, PermissionGroup, RoleScope}; use common_utils::generate_id_with_default_len; use diesel_models::role::{RoleNew, RoleUpdate}; use error_stack::{report, ResultExt}; @@ -9,7 +11,10 @@ use crate::{ routes::{app::ReqState, SessionState}, services::{ authentication::{blacklist, UserFromToken}, - authorization::roles::{self, predefined_roles::PREDEFINED_ROLES}, + authorization::{ + permission_groups::{ParentGroupExt, PermissionGroupExt}, + roles::{self, predefined_roles::PREDEFINED_ROLES}, + }, ApplicationResponse, }, types::domain::user::RoleName, @@ -19,7 +24,7 @@ use crate::{ pub async fn get_role_from_token_with_groups( state: SessionState, user_from_token: UserFromToken, -) -> UserResponse<Vec<role_api::PermissionGroup>> { +) -> UserResponse<Vec<PermissionGroup>> { let role_info = user_from_token .get_role_info_from_db(&state) .await @@ -30,6 +35,29 @@ pub async fn get_role_from_token_with_groups( Ok(ApplicationResponse::Json(permissions)) } +pub async fn get_groups_and_resources_for_role_from_token( + state: SessionState, + user_from_token: UserFromToken, +) -> UserResponse<role_api::GroupsAndResources> { + let role_info = user_from_token.get_role_info_from_db(&state).await?; + + let groups = role_info + .get_permission_groups() + .into_iter() + .collect::<Vec<_>>(); + let resources = groups + .iter() + .flat_map(|group| group.resources()) + .collect::<HashSet<_>>() + .into_iter() + .collect(); + + Ok(ApplicationResponse::Json(role_api::GroupsAndResources { + groups, + resources, + })) +} + pub async fn create_role( state: SessionState, user_from_token: UserFromToken, @@ -111,6 +139,52 @@ pub async fn get_role_with_groups( )) } +pub async fn get_parent_info_for_role( + state: SessionState, + user_from_token: UserFromToken, + role: role_api::GetRoleRequest, +) -> UserResponse<role_api::RoleInfoWithParents> { + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( + &state, + &role.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; + + if role_info.is_internal() { + return Err(UserErrors::InvalidRoleId.into()); + } + + let parent_groups = ParentGroup::get_descriptions_for_groups( + role_info.get_entity_type(), + role_info.get_permission_groups().to_vec(), + ) + .into_iter() + .map(|(parent_group, description)| role_api::ParentGroupInfo { + name: parent_group.clone(), + description, + scopes: role_info + .get_permission_groups() + .iter() + .filter_map(|group| (group.parent() == parent_group).then_some(group.scope())) + // TODO: Remove this hashset conversion when merhant access + // and organization access groups are removed + .collect::<HashSet<_>>() + .into_iter() + .collect(), + }) + .collect(); + + Ok(ApplicationResponse::Json(role_api::RoleInfoWithParents { + role_id: role.role_id, + parent_groups, + role_name: role_info.get_role_name().to_string(), + role_scope: role_info.get_scope(), + })) +} + pub async fn update_role( state: SessionState, user_from_token: UserFromToken, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f11840edf63..f54895ce7da 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1819,9 +1819,14 @@ impl User { web::resource("/permission_info") .route(web::get().to(user_role::get_authorization_info)), ) + // TODO: To be deprecated .service( web::resource("/module/list").route(web::get().to(user_role::get_role_information)), ) + .service( + web::resource("/parent/list") + .route(web::get().to(user_role::get_parent_group_info)), + ) .service( web::resource("/update").route(web::post().to(user::update_user_account_details)), ) @@ -2017,6 +2022,9 @@ impl User { .route(web::get().to(user_role::get_role_from_token)) .route(web::post().to(user_role::create_role)), ) + .service(web::resource("/v2").route( + web::get().to(user_role::get_groups_and_resources_for_role_from_token), + )) // TODO: To be deprecated .service( web::resource("/v2/list") @@ -2039,6 +2047,10 @@ impl User { web::resource("/{role_id}") .route(web::get().to(user_role::get_role)) .route(web::put().to(user_role::update_role)), + ) + .service( + web::resource("/{role_id}/v2") + .route(web::get().to(user_role::get_parent_info_for_role)), ), ); diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index a0c5c0f9902..ac17cf80210 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -263,10 +263,13 @@ impl From<Flow> for ApiIdentifier { | Flow::ListInvitableRolesAtEntityLevel | Flow::ListUpdatableRolesAtEntityLevel | Flow::GetRole + | Flow::GetRoleV2 | Flow::GetRoleFromToken + | Flow::GetRoleFromTokenV2 | Flow::UpdateUserRole | Flow::GetAuthorizationInfo | Flow::GetRolesInfo + | Flow::GetParentGroupInfo | Flow::AcceptInvitationsV2 | Flow::AcceptInvitationsPreAuth | Flow::DeleteUserRole diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 74847f06474..9910cef3950 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -55,6 +55,26 @@ pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) - .await } +pub async fn get_groups_and_resources_for_role_from_token( + state: web::Data<AppState>, + req: HttpRequest, +) -> HttpResponse { + let flow = Flow::GetRoleFromTokenV2; + + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, user, _, _| async move { + role_core::get_groups_and_resources_for_role_from_token(state, user).await + }, + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn create_role( state: web::Data<AppState>, req: HttpRequest, @@ -100,6 +120,31 @@ pub async fn get_role( .await } +pub async fn get_parent_info_for_role( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, +) -> HttpResponse { + let flow = Flow::GetRoleV2; + let request_payload = user_role_api::role::GetRoleRequest { + role_id: path.into_inner(), + }; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + request_payload, + |state, user, payload, _| async move { + role_core::get_parent_info_for_role(state, user, payload).await + }, + &auth::JWTAuth { + permission: Permission::ProfileUserRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn update_role( state: web::Data<AppState>, req: HttpRequest, @@ -226,6 +271,28 @@ pub async fn get_role_information( .await } +pub async fn get_parent_group_info( + state: web::Data<AppState>, + http_req: HttpRequest, +) -> HttpResponse { + let flow = Flow::GetParentGroupInfo; + + Box::pin(api::server_wrap( + flow, + state.clone(), + &http_req, + (), + |state, user_from_token, _, _| async move { + user_role_core::get_parent_group_info(state, user_from_token).await + }, + &auth::JWTAuth { + permission: Permission::ProfileUserRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn list_users_in_lineage( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index dba96dac188..bd987e2fe9a 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -37,32 +37,13 @@ fn get_group_description(group: PermissionGroup) -> &'static str { PermissionGroup::AnalyticsView => "View Analytics", PermissionGroup::UsersView => "View Users", PermissionGroup::UsersManage => "Manage and invite Users to the Team", - PermissionGroup::MerchantDetailsView => "View Merchant Details", - PermissionGroup::MerchantDetailsManage => "Create, modify and delete Merchant Details like api keys, webhooks, etc", + PermissionGroup::MerchantDetailsView | PermissionGroup::AccountView => "View Merchant Details", + PermissionGroup::MerchantDetailsManage | PermissionGroup::AccountManage => "Create, modify and delete Merchant Details like api keys, webhooks, etc", PermissionGroup::OrganizationManage => "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc", PermissionGroup::ReconOps => "View and manage reconciliation reports", } } -pub fn get_parent_name(group: PermissionGroup) -> ParentGroup { - match group { - PermissionGroup::OperationsView | PermissionGroup::OperationsManage => { - ParentGroup::Operations - } - PermissionGroup::ConnectorsView | PermissionGroup::ConnectorsManage => { - ParentGroup::Connectors - } - PermissionGroup::WorkflowsView | PermissionGroup::WorkflowsManage => ParentGroup::Workflows, - PermissionGroup::AnalyticsView => ParentGroup::Analytics, - PermissionGroup::UsersView | PermissionGroup::UsersManage => ParentGroup::Users, - PermissionGroup::MerchantDetailsView | PermissionGroup::MerchantDetailsManage => { - ParentGroup::Merchant - } - PermissionGroup::OrganizationManage => ParentGroup::Organization, - PermissionGroup::ReconOps => ParentGroup::Recon, - } -} - pub fn get_parent_group_description(group: ParentGroup) -> &'static str { match group { ParentGroup::Operations => "Payments, Refunds, Payouts, Mandates, Disputes and Customers", @@ -70,8 +51,7 @@ pub fn get_parent_group_description(group: ParentGroup) -> &'static str { ParentGroup::Workflows => "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager", ParentGroup::Analytics => "View Analytics", ParentGroup::Users => "Manage and invite Users to the Team", - ParentGroup::Merchant => "Create, modify and delete Merchant Details like api keys, webhooks, etc", - ParentGroup::Organization =>"Manage organization level tasks like create new Merchant accounts, Organization level roles, etc", + ParentGroup::Account => "Create, modify and delete Merchant Details like api keys, webhooks, etc", ParentGroup::Recon => "View and manage reconciliation reports", } } diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs index 3d1a0c8ea5b..57c385565a8 100644 --- a/crates/router/src/services/authorization/permission_groups.rs +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -1,4 +1,9 @@ -use common_enums::{ParentGroup, PermissionGroup, PermissionScope, Resource}; +use std::collections::HashMap; + +use common_enums::{EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource}; +use strum::IntoEnumIterator; + +use super::permissions::{self, ResourceExt}; pub trait PermissionGroupExt { fn scope(&self) -> PermissionScope; @@ -15,7 +20,8 @@ impl PermissionGroupExt for PermissionGroup { | Self::WorkflowsView | Self::AnalyticsView | Self::UsersView - | Self::MerchantDetailsView => PermissionScope::Read, + | Self::MerchantDetailsView + | Self::AccountView => PermissionScope::Read, Self::OperationsManage | Self::ConnectorsManage @@ -23,7 +29,8 @@ impl PermissionGroupExt for PermissionGroup { | Self::UsersManage | Self::MerchantDetailsManage | Self::OrganizationManage - | Self::ReconOps => PermissionScope::Write, + | Self::ReconOps + | Self::AccountManage => PermissionScope::Write, } } @@ -34,9 +41,12 @@ impl PermissionGroupExt for PermissionGroup { Self::WorkflowsView | Self::WorkflowsManage => ParentGroup::Workflows, Self::AnalyticsView => ParentGroup::Analytics, Self::UsersView | Self::UsersManage => ParentGroup::Users, - Self::MerchantDetailsView | Self::MerchantDetailsManage => ParentGroup::Merchant, - Self::OrganizationManage => ParentGroup::Organization, Self::ReconOps => ParentGroup::Recon, + Self::MerchantDetailsView + | Self::OrganizationManage + | Self::MerchantDetailsManage + | Self::AccountView + | Self::AccountManage => ParentGroup::Account, } } @@ -52,10 +62,14 @@ impl PermissionGroupExt for PermissionGroup { Self::ConnectorsView => vec![Self::ConnectorsView], Self::ConnectorsManage => vec![Self::ConnectorsView, Self::ConnectorsManage], - Self::WorkflowsView => vec![Self::WorkflowsView], - Self::WorkflowsManage => vec![Self::WorkflowsView, Self::WorkflowsManage], + Self::WorkflowsView => vec![Self::WorkflowsView, Self::ConnectorsView], + Self::WorkflowsManage => vec![ + Self::WorkflowsView, + Self::WorkflowsManage, + Self::ConnectorsView, + ], - Self::AnalyticsView => vec![Self::AnalyticsView], + Self::AnalyticsView => vec![Self::AnalyticsView, Self::OperationsView], Self::UsersView => vec![Self::UsersView], Self::UsersManage => { @@ -70,12 +84,19 @@ impl PermissionGroupExt for PermissionGroup { } Self::OrganizationManage => vec![Self::OrganizationManage], + + Self::AccountView => vec![Self::AccountView], + Self::AccountManage => vec![Self::AccountView, Self::AccountManage], } } } pub trait ParentGroupExt { fn resources(&self) -> Vec<Resource>; + fn get_descriptions_for_groups( + entity_type: EntityType, + groups: Vec<PermissionGroup>, + ) -> HashMap<ParentGroup, String>; } impl ParentGroupExt for ParentGroup { @@ -86,10 +107,38 @@ impl ParentGroupExt for ParentGroup { Self::Workflows => WORKFLOWS.to_vec(), Self::Analytics => ANALYTICS.to_vec(), Self::Users => USERS.to_vec(), - Self::Merchant | Self::Organization => ACCOUNT.to_vec(), + Self::Account => ACCOUNT.to_vec(), Self::Recon => RECON.to_vec(), } } + + fn get_descriptions_for_groups( + entity_type: EntityType, + groups: Vec<PermissionGroup>, + ) -> HashMap<Self, String> { + Self::iter() + .filter_map(|parent| { + let scopes = groups + .iter() + .filter(|group| group.parent() == parent) + .map(|group| group.scope()) + .max()?; + + let resources = parent + .resources() + .iter() + .filter(|res| res.entities().iter().any(|entity| entity <= &entity_type)) + .map(|res| permissions::get_resource_name(res, &entity_type)) + .collect::<Vec<_>>() + .join(", "); + + Some(( + parent, + format!("{} {}", permissions::get_scope_name(&scopes), resources), + )) + }) + .collect() + } } pub static OPERATIONS: [Resource; 8] = [ @@ -105,11 +154,10 @@ pub static OPERATIONS: [Resource; 8] = [ pub static CONNECTORS: [Resource; 2] = [Resource::Connector, Resource::Account]; -pub static WORKFLOWS: [Resource; 5] = [ +pub static WORKFLOWS: [Resource; 4] = [ Resource::Routing, Resource::ThreeDsDecisionManager, Resource::SurchargeDecisionManager, - Resource::Connector, Resource::Account, ]; diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 0521db7acc1..6e472d55623 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -73,3 +73,34 @@ generate_permissions! { }, ] } + +pub fn get_resource_name(resource: &Resource, entity_type: &EntityType) -> &'static str { + match (resource, entity_type) { + (Resource::Payment, _) => "Payments", + (Resource::Refund, _) => "Refunds", + (Resource::Dispute, _) => "Disputes", + (Resource::Mandate, _) => "Mandates", + (Resource::Customer, _) => "Customers", + (Resource::Payout, _) => "Payouts", + (Resource::ApiKey, _) => "Api Keys", + (Resource::Connector, _) => "Payment Processors, Payout Processors, Fraud & Risk Managers", + (Resource::Routing, _) => "Routing", + (Resource::ThreeDsDecisionManager, _) => "3DS Decision Manager", + (Resource::SurchargeDecisionManager, _) => "Surcharge Decision Manager", + (Resource::Analytics, _) => "Analytics", + (Resource::Report, _) => "Operation Reports", + (Resource::User, _) => "Users", + (Resource::WebhookEvent, _) => "Webhook Events", + (Resource::Recon, _) => "Reconciliation Reports", + (Resource::Account, EntityType::Profile) => "Business Profile Account", + (Resource::Account, EntityType::Merchant) => "Merchant Account", + (Resource::Account, EntityType::Organization) => "Organization Account", + } +} + +pub fn get_scope_name(scope: &PermissionScope) -> &'static str { + match scope { + PermissionScope::Read => "View", + PermissionScope::Write => "View and Manage", + } +} diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs index 33a1d5f53ca..39f6d47f824 100644 --- a/crates/router/src/services/authorization/roles/predefined_roles.rs +++ b/crates/router/src/services/authorization/roles/predefined_roles.rs @@ -24,7 +24,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, PermissionGroup::MerchantDetailsManage, + PermissionGroup::AccountManage, PermissionGroup::OrganizationManage, PermissionGroup::ReconOps, ], @@ -48,6 +50,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, ], role_id: common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(), role_name: "internal_view_only".to_string(), @@ -75,7 +78,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, PermissionGroup::MerchantDetailsManage, + PermissionGroup::AccountManage, PermissionGroup::OrganizationManage, PermissionGroup::ReconOps, ], @@ -105,7 +110,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, PermissionGroup::MerchantDetailsManage, + PermissionGroup::AccountManage, PermissionGroup::ReconOps, ], role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), @@ -128,6 +135,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(), role_name: "merchant_view_only".to_string(), @@ -148,6 +156,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(), role_name: "merchant_iam".to_string(), @@ -168,7 +177,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, PermissionGroup::MerchantDetailsManage, + PermissionGroup::AccountManage, ], role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(), role_name: "merchant_developer".to_string(), @@ -191,6 +202,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(), role_name: "merchant_operator".to_string(), @@ -210,6 +222,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(), role_name: "customer_support".to_string(), @@ -237,7 +250,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, PermissionGroup::MerchantDetailsManage, + PermissionGroup::AccountManage, ], role_id: consts::user_role::ROLE_ID_PROFILE_ADMIN.to_string(), role_name: "profile_admin".to_string(), @@ -259,6 +274,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY.to_string(), role_name: "profile_view_only".to_string(), @@ -279,6 +295,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN.to_string(), role_name: "profile_iam".to_string(), @@ -299,7 +316,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, PermissionGroup::MerchantDetailsManage, + PermissionGroup::AccountManage, ], role_id: consts::user_role::ROLE_ID_PROFILE_DEVELOPER.to_string(), role_name: "profile_developer".to_string(), @@ -322,6 +341,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_PROFILE_OPERATOR.to_string(), role_name: "profile_operator".to_string(), @@ -341,6 +361,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::MerchantDetailsView, + PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT.to_string(), role_name: "profile_customer_support".to_string(), diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 8d853ded338..652ce2b81db 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -374,6 +374,8 @@ pub enum Flow { GetAuthorizationInfo, /// Get Roles info GetRolesInfo, + /// Get Parent Group Info + GetParentGroupInfo, /// List roles v2 ListRolesV2, /// List invitable roles at entity level @@ -382,8 +384,12 @@ pub enum Flow { ListUpdatableRolesAtEntityLevel, /// Get role GetRole, + /// Get parent info for role + GetRoleV2, /// Get role from token GetRoleFromToken, + /// Get resources and groups for role from token + GetRoleFromTokenV2, /// Update user role UpdateUserRole, /// Create merchant account for user in a org
2024-10-25T12:17:59Z
## Description <!-- Describe your changes in detail --> Make new APIs to replace - `/user/role/{{role_id}}` -> `/user/role/{{role_id}}/v2` - `/user/role` -> `/user/role/v2` - `/user/module/list` -> `/user/parent/list` The new APIs will have proper description and parent info which has entity level context unlike the previous APIs. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6439. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Parent List ``` curl --location 'http://localhost:8080/user/parent/list' \ --header 'Authorization: JWT' \ ``` ```json [ { "name": "Operations", "description": "View and Manage Payments, Refunds, Mandates, Disputes, Customers, Payouts, Operation Reports, Organization Account", "scopes": [ "write", "read" ] }, { "name": "Recon", "description": "View and Manage Reconciliation Reports", "scopes": [ "write" ] }, { "name": "Analytics", "description": "View Analytics, Operation Reports, Organization Account", "scopes": [ "read" ] }, { "name": "Workflows", "description": "View and Manage Routing, 3DS Decision Manager, Surcharge Decision Manager, Organization Account", "scopes": [ "write", "read" ] }, { "name": "Users", "description": "View and Manage Users, Organization Account", "scopes": [ "read", "write" ] }, { "name": "Account", "description": "View and Manage Organization Account, Api Keys, Webhook Events", "scopes": [ "read", "write" ] }, { "name": "Connectors", "description": "View and Manage Payment Processors, Payout Processors, Fraud & Risk Managers, Organization Account", "scopes": [ "write", "read" ] } ] ``` The descriptions and scopes in the above response will change with respect the role. 2. Get Role V2 ``` curl --location 'http://localhost:8080/user/role/merchant_admin/v2' \ --header 'Authorization: JWT' \ ``` ```json { "role_id": "merchant_admin", "parent_groups": [ { "name": "Users", "description": "View and Manage Users, Merchant Account", "scopes": [ "read", "write" ] }, { "name": "Connectors", "description": "View and Manage Payment Processors, Payout Processors, Fraud & Risk Managers, Merchant Account", "scopes": [ "read", "write" ] }, { "name": "Recon", "description": "View and Manage Reconciliation Reports", "scopes": [ "write" ] }, { "name": "Account", "description": "View and Manage Merchant Account, Api Keys, Webhook Events", "scopes": [ "read", "write" ] }, { "name": "Workflows", "description": "View and Manage Routing, 3DS Decision Manager, Surcharge Decision Manager, Merchant Account", "scopes": [ "write", "read" ] }, { "name": "Analytics", "description": "View Analytics, Operation Reports, Merchant Account", "scopes": [ "read" ] }, { "name": "Operations", "description": "View and Manage Payments, Refunds, Mandates, Disputes, Customers, Payouts, Operation Reports, Merchant Account", "scopes": [ "read", "write" ] } ], "role_name": "merchant_admin", "role_scope": "organization" } ``` 3. Get Role from Token V2 ``` curl --location 'http://localhost:8080/user/role/v2' \ --header 'Authorization: JWT' \ ``` ``` { "groups": [ "connectors_manage", "account_manage", "users_manage", "merchant_details_manage", "merchant_details_view", "workflows_manage", "analytics_view", "operations_view", "organization_manage", "connectors_view", "recon_ops", "users_view", "workflows_view", "account_view", "operations_manage" ], "resources": [ "routing", "customer", "payout", "api_key", "refund", "connector", "user", "mandate", "analytics", "account", "surcharge_decision_manager", "payment", "webhook_event", "recon", "three_ds_decision_manager", "dispute", "report" ] } ```
98567569c1c61648eebf0ad7a1ab58bba967b427
1. Parent List ``` curl --location 'http://localhost:8080/user/parent/list' \ --header 'Authorization: JWT' \ ``` ```json [ { "name": "Operations", "description": "View and Manage Payments, Refunds, Mandates, Disputes, Customers, Payouts, Operation Reports, Organization Account", "scopes": [ "write", "read" ] }, { "name": "Recon", "description": "View and Manage Reconciliation Reports", "scopes": [ "write" ] }, { "name": "Analytics", "description": "View Analytics, Operation Reports, Organization Account", "scopes": [ "read" ] }, { "name": "Workflows", "description": "View and Manage Routing, 3DS Decision Manager, Surcharge Decision Manager, Organization Account", "scopes": [ "write", "read" ] }, { "name": "Users", "description": "View and Manage Users, Organization Account", "scopes": [ "read", "write" ] }, { "name": "Account", "description": "View and Manage Organization Account, Api Keys, Webhook Events", "scopes": [ "read", "write" ] }, { "name": "Connectors", "description": "View and Manage Payment Processors, Payout Processors, Fraud & Risk Managers, Organization Account", "scopes": [ "write", "read" ] } ] ``` The descriptions and scopes in the above response will change with respect the role. 2. Get Role V2 ``` curl --location 'http://localhost:8080/user/role/merchant_admin/v2' \ --header 'Authorization: JWT' \ ``` ```json { "role_id": "merchant_admin", "parent_groups": [ { "name": "Users", "description": "View and Manage Users, Merchant Account", "scopes": [ "read", "write" ] }, { "name": "Connectors", "description": "View and Manage Payment Processors, Payout Processors, Fraud & Risk Managers, Merchant Account", "scopes": [ "read", "write" ] }, { "name": "Recon", "description": "View and Manage Reconciliation Reports", "scopes": [ "write" ] }, { "name": "Account", "description": "View and Manage Merchant Account, Api Keys, Webhook Events", "scopes": [ "read", "write" ] }, { "name": "Workflows", "description": "View and Manage Routing, 3DS Decision Manager, Surcharge Decision Manager, Merchant Account", "scopes": [ "write", "read" ] }, { "name": "Analytics", "description": "View Analytics, Operation Reports, Merchant Account", "scopes": [ "read" ] }, { "name": "Operations", "description": "View and Manage Payments, Refunds, Mandates, Disputes, Customers, Payouts, Operation Reports, Merchant Account", "scopes": [ "read", "write" ] } ], "role_name": "merchant_admin", "role_scope": "organization" } ``` 3. Get Role from Token V2 ``` curl --location 'http://localhost:8080/user/role/v2' \ --header 'Authorization: JWT' \ ``` ``` { "groups": [ "connectors_manage", "account_manage", "users_manage", "merchant_details_manage", "merchant_details_view", "workflows_manage", "analytics_view", "operations_view", "organization_manage", "connectors_view", "recon_ops", "users_view", "workflows_view", "account_view", "operations_manage" ], "resources": [ "routing", "customer", "payout", "api_key", "refund", "connector", "user", "mandate", "analytics", "account", "surcharge_decision_manager", "payment", "webhook_event", "recon", "three_ds_decision_manager", "dispute", "report" ] } ```
[ "crates/api_models/src/events/user_role.rs", "crates/api_models/src/user_role/role.rs", "crates/common_enums/src/enums.rs", "crates/router/src/core/user_role.rs", "crates/router/src/core/user_role/role.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user_role.rs", "crates/router/src/services/authorization/info.rs", "crates/router/src/services/authorization/permission_groups.rs", "crates/router/src/services/authorization/permissions.rs", "crates/router/src/services/authorization/roles/predefined_roles.rs", "crates/router_env/src/logger/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6438
Bug: fix: lazy connection pools for dynamic routing service
diff --git a/Cargo.lock b/Cargo.lock index 9ccedba3c39..78ae2d63adb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3126,8 +3126,10 @@ dependencies = [ "dyn-clone", "error-stack", "hex", + "http-body-util", "hyper 0.14.30", "hyper-proxy", + "hyper-util", "hyperswitch_interfaces", "masking", "once_cell", @@ -3959,9 +3961,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.7" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cde7055719c54e36e95e8719f95883f22072a48ede39db7fc17a4e1d5281e9b9" +checksum = "41296eb09f183ac68eec06e03cdbea2e759633d4067b2f6552fc2e009bcad08b" dependencies = [ "bytes 1.7.1", "futures-channel", @@ -3972,7 +3974,6 @@ dependencies = [ "pin-project-lite", "socket2", "tokio 1.40.0", - "tower", "tower-service", "tracing", ] diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 735ccc5ebfa..12b9dd3b0f3 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -13,7 +13,7 @@ email = ["dep:aws-config"] aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"] hashicorp-vault = ["dep:vaultrs"] v1 = ["hyperswitch_interfaces/v1", "common_utils/v1"] -dynamic_routing = ["dep:prost", "dep:tonic", "dep:tonic-reflection", "dep:tonic-types", "dep:api_models", "tokio/macros", "tokio/rt-multi-thread", "dep:tonic-build", "dep:router_env"] +dynamic_routing = ["dep:prost", "dep:tonic", "dep:tonic-reflection", "dep:tonic-types", "dep:api_models", "tokio/macros", "tokio/rt-multi-thread", "dep:tonic-build", "dep:router_env", "dep:hyper-util", "dep:http-body-util"] [dependencies] async-trait = "0.1.79" @@ -38,6 +38,8 @@ tokio = "1.37.0" tonic = { version = "0.12.2", optional = true } tonic-reflection = { version = "0.12.2", optional = true } tonic-types = { version = "0.12.2", optional = true } +hyper-util = { version = "0.1.9", optional = true } +http-body-util = { version = "0.1.2", optional = true } # First party crates diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs index 2681bffb0ce..343dd80e951 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing.rs @@ -6,6 +6,9 @@ use api_models::routing::{ }; use common_utils::{errors::CustomResult, ext_traits::OptionExt, transformers::ForeignTryFrom}; use error_stack::ResultExt; +use http_body_util::combinators::UnsyncBoxBody; +use hyper::body::Bytes; +use hyper_util::client::legacy::connect::HttpConnector; use serde; use success_rate::{ success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig, @@ -13,7 +16,7 @@ use success_rate::{ CurrentBlockThreshold as DynamicCurrentThreshold, LabelWithStatus, UpdateSuccessRateWindowConfig, UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse, }; -use tonic::transport::Channel; +use tonic::Status; #[allow( missing_docs, unused_qualifications, @@ -40,11 +43,13 @@ pub enum DynamicRoutingError { SuccessRateBasedRoutingFailure(String), } +type Client = hyper_util::client::legacy::Client<HttpConnector, UnsyncBoxBody<Bytes, Status>>; + /// Type that consists of all the services provided by the client #[derive(Debug, Clone)] pub struct RoutingStrategy { /// success rate service for Dynamic Routing - pub success_rate_client: Option<SuccessRateCalculatorClient<Channel>>, + pub success_rate_client: Option<SuccessRateCalculatorClient<Client>>, } /// Contains the Dynamic Routing Client Config @@ -68,11 +73,14 @@ impl DynamicRoutingClientConfig { pub async fn get_dynamic_routing_connection( self, ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> { + let client = + hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) + .http2_only(true) + .build_http(); let success_rate_client = match self { Self::Enabled { host, port } => { - let uri = format!("http://{}:{}", host, port); - let channel = tonic::transport::Endpoint::new(uri)?.connect().await?; - Some(SuccessRateCalculatorClient::new(channel)) + let uri = format!("http://{}:{}", host, port).parse::<tonic::transport::Uri>()?; + Some(SuccessRateCalculatorClient::with_origin(client, uri)) } Self::Disabled => None, }; @@ -102,7 +110,7 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { } #[async_trait::async_trait] -impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Channel> { +impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { async fn calculate_success_rate( &self, id: String,
2024-10-25T10:47:07Z
## Description <!-- Describe your changes in detail --> Previously hyperswitch server was panicking, if it wasn't able to establish a connection with dynamic_routing service. We have fixed this by establishing lazy connection pools and not established channel(which was previously). Which will insure hyperswitch server to run even when the connection isn't established. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested on my local. <img width="1728" alt="Screenshot 2024-10-25 at 4 15 03 PM" src="https://github.com/user-attachments/assets/a7a1d6c8-8c6c-4b35-ae3a-b05b6af9f9bc"> This can't be tested on Integ as we don't have this service on integ. Can't be tested on sbx as well, as it will require the pods to be killed. and a re-establishment of connection.
aaac9aa97d1b00d50bec4e02efb0658956463398
Tested on my local. <img width="1728" alt="Screenshot 2024-10-25 at 4 15 03 PM" src="https://github.com/user-attachments/assets/a7a1d6c8-8c6c-4b35-ae3a-b05b6af9f9bc"> This can't be tested on Integ as we don't have this service on integ. Can't be tested on sbx as well, as it will require the pods to be killed. and a re-establishment of connection.
[ "Cargo.lock", "crates/external_services/Cargo.toml", "crates/external_services/src/grpc_client/dynamic_routing.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6436
Bug: chore(users): change entity_type column of roles to non-optional Make entity-type in roles non-optional
diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs index 3fb64e645d6..8199bd3979c 100644 --- a/crates/diesel_models/src/role.rs +++ b/crates/diesel_models/src/role.rs @@ -18,7 +18,7 @@ pub struct Role { pub created_by: String, pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, - pub entity_type: Option<enums::EntityType>, + pub entity_type: enums::EntityType, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -35,7 +35,7 @@ pub struct RoleNew { pub created_by: String, pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, - pub entity_type: Option<enums::EntityType>, + pub entity_type: enums::EntityType, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 8d2dfc47b62..e2ab676b2d3 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1235,7 +1235,7 @@ diesel::table! { #[max_length = 64] last_modified_by -> Varchar, #[max_length = 64] - entity_type -> Nullable<Varchar>, + entity_type -> Varchar, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index b5e895cde79..5651bf95dd9 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1181,7 +1181,7 @@ diesel::table! { #[max_length = 64] last_modified_by -> Varchar, #[max_length = 64] - entity_type -> Nullable<Varchar>, + entity_type -> Varchar, } } diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index b5b5cab421f..e43f23674e9 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -64,7 +64,7 @@ pub async fn create_role( org_id: user_from_token.org_id, groups: req.groups, scope: req.role_scope, - entity_type: Some(EntityType::Merchant), + entity_type: EntityType::Merchant, created_by: user_from_token.user_id.clone(), last_modified_by: user_from_token.user_id, created_at: now, diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs index ce009d38a9e..d13508356e5 100644 --- a/crates/router/src/db/role.rs +++ b/crates/router/src/db/role.rs @@ -354,7 +354,7 @@ impl RoleInterface for MockDb { None => true, }; - matches_merchant && role.org_id == *org_id && role.entity_type == entity_type + matches_merchant && role.org_id == *org_id && Some(role.entity_type) == entity_type }) .take(limit_usize) .cloned() diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs index 63d547bfa67..bf66eb92466 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -119,7 +119,7 @@ impl From<diesel_models::role::Role> for RoleInfo { role_name: role.role_name, groups: role.groups.into_iter().map(Into::into).collect(), scope: role.scope, - entity_type: role.entity_type.unwrap_or(EntityType::Merchant), + entity_type: role.entity_type, is_invitable: true, is_deletable: true, is_updatable: true, diff --git a/migrations/2024-10-24-123318_update-entity-type-column-in-roles/down.sql b/migrations/2024-10-24-123318_update-entity-type-column-in-roles/down.sql new file mode 100644 index 00000000000..60dfa892e60 --- /dev/null +++ b/migrations/2024-10-24-123318_update-entity-type-column-in-roles/down.sql @@ -0,0 +1,4 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE roles ALTER COLUMN entity_type DROP DEFAULT; + +ALTER TABLE roles ALTER COLUMN entity_type DROP NOT NULL; \ No newline at end of file diff --git a/migrations/2024-10-24-123318_update-entity-type-column-in-roles/up.sql b/migrations/2024-10-24-123318_update-entity-type-column-in-roles/up.sql new file mode 100644 index 00000000000..564a026184e --- /dev/null +++ b/migrations/2024-10-24-123318_update-entity-type-column-in-roles/up.sql @@ -0,0 +1,6 @@ +-- Your SQL goes here +UPDATE roles SET entity_type = 'merchant' WHERE entity_type IS NULL; + +ALTER TABLE roles ALTER COLUMN entity_type SET DEFAULT 'merchant'; + +ALTER TABLE roles ALTER COLUMN entity_type SET NOT NULL; \ No newline at end of file
2024-10-25T09:20:18Z
## Description <!-- Describe your changes in detail --> Earlier entity-type column in roles table was optional , after this change the column will be non-optional with default value as Merchant ### Additional Changes - [ ] This PR modifies the API contract - [X] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Request : ``` curl 'http://localhost:8080/user/role' \ -H 'authorization: Bearer JWT \ --data-raw '{"role_scope":"merchant","groups":["operations_manage","connectors_view","connectors_manage"],"role_name":"merch-scope-merch-role"}' ``` Response : ``` { "role_id": "role_qrQ05Q9pu7czBlDEWnGE", "groups": [ "operations_manage", "connectors_view", "connectors_manage" ], "role_name": "merch-scope-merch-role", "role_scope": "merchant" } ``` Db should have an entry in roles table with role-name as merch-scope-merch-role and entity-type as merchant. All the existing flows should work as before
8372389671c4aefeb625365d198390df5d8f35a5
- Request : ``` curl 'http://localhost:8080/user/role' \ -H 'authorization: Bearer JWT \ --data-raw '{"role_scope":"merchant","groups":["operations_manage","connectors_view","connectors_manage"],"role_name":"merch-scope-merch-role"}' ``` Response : ``` { "role_id": "role_qrQ05Q9pu7czBlDEWnGE", "groups": [ "operations_manage", "connectors_view", "connectors_manage" ], "role_name": "merch-scope-merch-role", "role_scope": "merchant" } ``` Db should have an entry in roles table with role-name as merch-scope-merch-role and entity-type as merchant. All the existing flows should work as before
[ "crates/diesel_models/src/role.rs", "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/schema_v2.rs", "crates/router/src/core/user_role/role.rs", "crates/router/src/db/role.rs", "crates/router/src/services/authorization/roles.rs", "migrations/2024-10-24-123318_update-entity-type-column-in-roles/down.sql", "migrations/2024-10-24-123318_update-entity-type-column-in-roles/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-4680
Bug: Add audit events for PaymentApprove update Created from #4525 This covers adding events for PaymentApprove operation This event should include the payment data similar to [PaymentCancel](https://github.com/juspay/hyperswitch/pull/4166) It should also include any metadata for the event e.g reason for payment rejection, error codes, rejection source etc ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index fe5e7a7e72f..2bc18122b22 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -12,6 +12,7 @@ use crate::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentData}, }, + events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ @@ -213,7 +214,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for async fn update_trackers<'b>( &'b self, state: &'b SessionState, - _req_state: ReqState, + req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, @@ -257,6 +258,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + req_state + .event_context + .event(AuditEvent::new(AuditEventType::PaymentApprove)) + .with(payment_data.to_event()) + .emit(); Ok((Box::new(self), payment_data)) } diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs index 54c1934e36f..9fbd754b43c 100644 --- a/crates/router/src/events/audit_events.rs +++ b/crates/router/src/events/audit_events.rs @@ -27,6 +27,7 @@ pub enum AuditEventType { capture_amount: Option<MinorUnit>, multiple_capture_count: Option<i16>, }, + PaymentApprove, PaymentCreate, } @@ -66,6 +67,7 @@ impl Event for AuditEvent { AuditEventType::RefundSuccess => "refund_success", AuditEventType::RefundFail => "refund_fail", AuditEventType::PaymentCancelled { .. } => "payment_cancelled", + AuditEventType::PaymentApprove { .. } => "payment_approve", AuditEventType::PaymentCreate { .. } => "payment_create", }; format!(
2024-10-24T18:41:48Z
## Description This PR adds an Audit event for the PaymentApprove operation. ### Additional Changes - [x] This PR modifies the files below - `crates/router/src/core/payments/operations/payment_approve.rs` - `crates/router/src/events/audit_events.rs` ## Motivation and Context This PR fixes #4680 ## How did you test it This requires FRM related flows to be tested, and may not be tested locally.
063fe904c66c9af3d7ce0a82ad712eac69e41786
[ "crates/router/src/core/payments/operations/payment_approve.rs", "crates/router/src/events/audit_events.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6430
Bug: fix(analytics): fix refund status filter on dashboard Whenever Refund Status filter is applied on the analytics section on dashboard, errors are being generated. The wrong RefundStatus enum has been imported for the RefundStatus filter in RefundFilters struct in this PR: https://github.com/juspay/hyperswitch/pull/2988. Need to import the correct enum for the same
diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs index 8acb51e764c..ef17387d1ea 100644 --- a/crates/api_models/src/analytics/refunds.rs +++ b/crates/api_models/src/analytics/refunds.rs @@ -5,7 +5,7 @@ use std::{ use common_utils::id_type; -use crate::{enums::Currency, refunds::RefundStatus}; +use crate::enums::{Currency, RefundStatus}; #[derive( Clone,
2024-10-24T13:21:38Z
## Description <!-- Describe your changes in detail --> - Whenever `Refund Status` filter is applied on the analytics section on dashboard, errors are being generated. - The wrong `RefundStatus` enum has been imported for the `RefundStatus` filter in `RefundFilters` struct in this PR: [https://github.com/juspay/hyperswitch/pull/2988](https://github.com/juspay/hyperswitch/pull/2988). - Updated the code to use the correct `RefundStatus` import. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> To fix the issue on dashboard whenever refund status filter is applied. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Apply the refund status filter on the dashboard - Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTkyOTAwOCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.B7sxut7HMs1C7QDRJWqOhQXHbugw4Ev3w8EAzskmzeo' \ --header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-16T18:30:00Z", "endTime": "2024-10-24T13:17:00Z" }, "timeSeries": { "granularity": "G_ONEDAY" }, "filters": { "refund_status": ["success"] }, "mode": "ORDER", "source": "BATCH", "metrics": [ "refund_success_rate", "refund_count", "refund_success_count", "refund_processed_amount" ] } ]' ``` Respoonse: ```bash { "queryData": [ { "refund_success_rate": 100.0, "refund_count": 1, "refund_success_count": 1, "refund_processed_amount": 600, "currency": null, "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "time_range": { "start_time": "2024-10-24T00:00:00.000Z", "end_time": "2024-10-24T23:00:00.000Z" }, "time_bucket": "2024-10-24 00:00:00" } ], "metaData": [ { "current_time_range": { "start_time": "2024-10-16T18:30:00.000Z", "end_time": "2024-10-24T13:17:00.000Z" } } ] } ``` <img width="1332" alt="image" src="https://github.com/user-attachments/assets/bf8d08a6-e2e6-437c-884f-6de6c2bcaae3">
c3b0f7c1d6ad95034535048aa50ff6abe9ed6aa0
- Apply the refund status filter on the dashboard - Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTkyOTAwOCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.B7sxut7HMs1C7QDRJWqOhQXHbugw4Ev3w8EAzskmzeo' \ --header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-16T18:30:00Z", "endTime": "2024-10-24T13:17:00Z" }, "timeSeries": { "granularity": "G_ONEDAY" }, "filters": { "refund_status": ["success"] }, "mode": "ORDER", "source": "BATCH", "metrics": [ "refund_success_rate", "refund_count", "refund_success_count", "refund_processed_amount" ] } ]' ``` Respoonse: ```bash { "queryData": [ { "refund_success_rate": 100.0, "refund_count": 1, "refund_success_count": 1, "refund_processed_amount": 600, "currency": null, "refund_status": null, "connector": null, "refund_type": null, "profile_id": null, "time_range": { "start_time": "2024-10-24T00:00:00.000Z", "end_time": "2024-10-24T23:00:00.000Z" }, "time_bucket": "2024-10-24 00:00:00" } ], "metaData": [ { "current_time_range": { "start_time": "2024-10-16T18:30:00.000Z", "end_time": "2024-10-24T13:17:00.000Z" } } ] } ``` <img width="1332" alt="image" src="https://github.com/user-attachments/assets/bf8d08a6-e2e6-437c-884f-6de6c2bcaae3">
[ "crates/api_models/src/analytics/refunds.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4672
Bug: Add audit events for PaymentCreate update Created from https://github.com/juspay/hyperswitch/issues/4525 This covers adding events for PaymentCreate operation This event should include the payment data similar to https://github.com/juspay/hyperswitch/pull/4166 It should also include any metadata for the event e.g reason for payment rejection, error codes, rejection source etc
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index d4057c523bc..c65e58ea2d4 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -42,6 +42,7 @@ use crate::{ utils as core_utils, }, db::StorageInterface, + events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ @@ -818,7 +819,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen async fn update_trackers<'b>( &'b self, state: &'b SessionState, - _req_state: ReqState, + req_state: ReqState, mut payment_data: PaymentData<F>, customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, @@ -923,6 +924,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + req_state + .event_context + .event(AuditEvent::new(AuditEventType::PaymentCreate)) + .with(payment_data.to_event()) + .emit(); // payment_data.mandate_id = response.and_then(|router_data| router_data.request.mandate_id); Ok(( diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs index 9b7a688f7eb..54c1934e36f 100644 --- a/crates/router/src/events/audit_events.rs +++ b/crates/router/src/events/audit_events.rs @@ -27,6 +27,7 @@ pub enum AuditEventType { capture_amount: Option<MinorUnit>, multiple_capture_count: Option<i16>, }, + PaymentCreate, } #[derive(Debug, Clone, Serialize)] @@ -65,6 +66,7 @@ impl Event for AuditEvent { AuditEventType::RefundSuccess => "refund_success", AuditEventType::RefundFail => "refund_fail", AuditEventType::PaymentCancelled { .. } => "payment_cancelled", + AuditEventType::PaymentCreate { .. } => "payment_create", }; format!( "{event_type}-{}",
2024-10-24T11:52:21Z
## Description This PR adds an Audit event for the PaymentCreate operation. ### Additional Changes - [x] This PR modifies the files below - `crates/router/src/core/payments/operations/payment_create.rs` - `crates/router/src/events/audit_events.rs` ## Motivation and Context This PR fixes #4672 ## How did you test it Hit the `Payments - Create` endpoint with `"confirm": false` - Curl: ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "profile_id": "pro_v5sFoHe80OeiUlIonocM" }' ``` - Response: ```json { "payment_id": "pay_pvLYaf7aejhEVszi9OnZ", "merchant_id": "merchant_1726046328", "status": "requires_confirmation", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_pvLYaf7aejhEVszi9OnZ_secret_a9hynS88hC0oz7LNRjFc", "created": "2024-11-06T18:21:43.625Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_btocKPXDGHw1UKcvTpMW", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1730917303, "expires": 1730920903, "secret": "epk_11b7865dffb2468e8d16f29afcf8677f" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_v5sFoHe80OeiUlIonocM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-06T18:36:43.625Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-11-06T18:21:43.669Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` Audit log will get generated and can be viewed in hyperswitch-audit-events topic in kafka with `PaymentCreate` event-type. <img width="1298" alt="Screenshot 2024-11-06 at 11 52 00 PM" src="https://github.com/user-attachments/assets/efc6ff47-3a6e-411a-a539-3b4d13f71967"> Now hit the `Payments - Confirm` endpoint, and audit log will get generated with `PaymentConfirm` event-type. <img width="1350" alt="image" src="https://github.com/user-attachments/assets/20afd6ca-7c84-4a77-885b-e235ef5cd98c">
1ba3d84df1e93d2286db1a262c4a67b3861b90c0
[ "crates/router/src/core/payments/operations/payment_create.rs", "crates/router/src/events/audit_events.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4682
Bug: Add audit events for PaymentUpdate update Created from #4525 This covers adding events for PaymentUpdate operation This event should include the payment data similar to [PaymentCancel](https://github.com/juspay/hyperswitch/pull/4166) It should also include any metadata for the event e.g reason for payment rejection, error codes, rejection source etc ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 9005e94c962..2f1a0c333fa 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -25,6 +25,7 @@ use crate::{ payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, }, + events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ @@ -694,7 +695,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen async fn update_trackers<'b>( &'b self, _state: &'b SessionState, - _req_state: ReqState, + req_state: ReqState, mut _payment_data: PaymentData<F>, _customer: Option<domain::Customer>, _storage_scheme: storage_enums::MerchantStorageScheme, @@ -714,7 +715,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen async fn update_trackers<'b>( &'b self, state: &'b SessionState, - _req_state: ReqState, + req_state: ReqState, mut payment_data: PaymentData<F>, customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, @@ -925,6 +926,12 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + let amount = payment_data.amount; + req_state + .event_context + .event(AuditEvent::new(AuditEventType::PaymentUpdate { amount })) + .with(payment_data.to_event()) + .emit(); Ok(( payments::is_confirm(self, payment_data.confirm), diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs index 9fbd754b43c..a6b0884d21d 100644 --- a/crates/router/src/events/audit_events.rs +++ b/crates/router/src/events/audit_events.rs @@ -1,3 +1,4 @@ +use api_models::payments::Amount; use common_utils::types::MinorUnit; use diesel_models::fraud_check::FraudCheck; use events::{Event, EventInfo}; @@ -27,6 +28,9 @@ pub enum AuditEventType { capture_amount: Option<MinorUnit>, multiple_capture_count: Option<i16>, }, + PaymentUpdate { + amount: Amount, + }, PaymentApprove, PaymentCreate, } @@ -67,6 +71,7 @@ impl Event for AuditEvent { AuditEventType::RefundSuccess => "refund_success", AuditEventType::RefundFail => "refund_fail", AuditEventType::PaymentCancelled { .. } => "payment_cancelled", + AuditEventType::PaymentUpdate { .. } => "payment_update", AuditEventType::PaymentApprove { .. } => "payment_approve", AuditEventType::PaymentCreate { .. } => "payment_create", };
2024-10-24T11:03:29Z
## Description This PR adds an Audit event for the PaymentUpdate operation. ### Additional Changes - [x] This PR modifies the files below - `crates/router/src/core/payments/operations/payment_update.rs` - `crates/router/src/events/audit_events.rs` ## Motivation and Context This PR fixes #4682 ## How did you test it - Hit the `Payments - Create` endpoint. Make a payment with `"confirm": false` ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "profile_id": "pro_v5sFoHe80OeiUlIonocM" }' ``` - Now hit the `Payments - Update` endpoint. ```bash { "amount": 20000, "currency": "SGD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 20000, "email": "joseph@example.com", "name": "joseph Doe", "phone": "8888888888", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "return_url": "https://google.com", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` Audit log will get generated and can be viewed in hyperswitch-audit-events topic in kafka with `PaymentUpdate` event-type. Amount parameter can be verified in the event. <img width="1424" alt="Screenshot 2024-11-07 at 12 42 34 PM" src="https://github.com/user-attachments/assets/e4dfdef5-495b-48ad-938a-8053d0271408"> <img width="1458" alt="Screenshot 2024-11-07 at 12 42 42 PM" src="https://github.com/user-attachments/assets/2b39e2bb-6200-4184-84ed-0b913d0f437f"> Now payment can be completed by hitting the `Payments - Confirm` endpoint.
fe4931a37e6030ea03ca83540f9a21877c7b6b34
[ "crates/router/src/core/payments/operations/payment_update.rs", "crates/router/src/events/audit_events.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6417
Bug: feat(analytics): add `sessionized_metrics` for refunds (backwards compatibility) and `currency_conversion` ## Current Behaviour - There is no `sessionized_metrics` module for refunds like there is for `payments` and `payment_intents` - Update the existing metrics with `currency_conversion` usage. ## Proposed Changes - create `sessionized_metrics` module for refunds - implement `currency_conversion` for refunds analytics
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index 7ea8e9007f7..b242b3dae81 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -69,11 +69,21 @@ pub async fn get_sankey( i.refunds_status.unwrap_or_default().as_ref(), i.attempt_count, ) { + (IntentStatus::Succeeded, SessionizerRefundStatus::FullRefunded, 1) => { + sankey_response.refunded += i.count; + sankey_response.normal_success += i.count + } + (IntentStatus::Succeeded, SessionizerRefundStatus::PartialRefunded, 1) => { + sankey_response.partial_refunded += i.count; + sankey_response.normal_success += i.count + } (IntentStatus::Succeeded, SessionizerRefundStatus::FullRefunded, _) => { - sankey_response.refunded += i.count + sankey_response.refunded += i.count; + sankey_response.smart_retried_success += i.count } (IntentStatus::Succeeded, SessionizerRefundStatus::PartialRefunded, _) => { - sankey_response.partial_refunded += i.count + sankey_response.partial_refunded += i.count; + sankey_response.smart_retried_success += i.count } ( IntentStatus::Succeeded diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs index 651eeb0bcfe..5ca9fdf7516 100644 --- a/crates/analytics/src/payments/accumulator.rs +++ b/crates/analytics/src/payments/accumulator.rs @@ -387,7 +387,7 @@ impl PaymentMetricsAccumulator { payment_processed_count, payment_processed_amount_without_smart_retries, payment_processed_count_without_smart_retries, - payment_processed_amount_usd, + payment_processed_amount_in_usd, payment_processed_amount_without_smart_retries_usd, ) = self.processed_amount.collect(); let ( @@ -417,7 +417,7 @@ impl PaymentMetricsAccumulator { payments_failure_rate_distribution_without_smart_retries, failure_reason_count, failure_reason_count_without_smart_retries, - payment_processed_amount_usd, + payment_processed_amount_in_usd, payment_processed_amount_without_smart_retries_usd, } } diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs index bcd009270dc..01a3b1abc15 100644 --- a/crates/analytics/src/payments/core.rs +++ b/crates/analytics/src/payments/core.rs @@ -228,7 +228,7 @@ pub async fn get_metrics( let mut total_payment_processed_count_without_smart_retries = 0; let mut total_failure_reasons_count = 0; let mut total_failure_reasons_count_without_smart_retries = 0; - let mut total_payment_processed_amount_usd = 0; + let mut total_payment_processed_amount_in_usd = 0; let mut total_payment_processed_amount_without_smart_retries_usd = 0; let query_data: Vec<MetricsBucketResponse> = metrics_accumulator .into_iter() @@ -251,9 +251,9 @@ pub async fn get_metrics( }) .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) .unwrap_or_default(); - collected_values.payment_processed_amount_usd = amount_in_usd; + collected_values.payment_processed_amount_in_usd = amount_in_usd; total_payment_processed_amount += amount; - total_payment_processed_amount_usd += amount_in_usd.unwrap_or(0); + total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0); } if let Some(count) = collected_values.payment_processed_count { total_payment_processed_count += count; @@ -299,7 +299,7 @@ pub async fn get_metrics( query_data, meta_data: [PaymentsAnalyticsMetadata { total_payment_processed_amount: Some(total_payment_processed_amount), - total_payment_processed_amount_usd: Some(total_payment_processed_amount_usd), + total_payment_processed_amount_in_usd: Some(total_payment_processed_amount_in_usd), total_payment_processed_amount_without_smart_retries: Some( total_payment_processed_amount_without_smart_retries, ), diff --git a/crates/analytics/src/refunds/accumulator.rs b/crates/analytics/src/refunds/accumulator.rs index 9c51defdcf9..add38c98162 100644 --- a/crates/analytics/src/refunds/accumulator.rs +++ b/crates/analytics/src/refunds/accumulator.rs @@ -7,7 +7,7 @@ pub struct RefundMetricsAccumulator { pub refund_success_rate: SuccessRateAccumulator, pub refund_count: CountAccumulator, pub refund_success: CountAccumulator, - pub processed_amount: SumAccumulator, + pub processed_amount: PaymentProcessedAmountAccumulator, } #[derive(Debug, Default)] @@ -22,7 +22,7 @@ pub struct CountAccumulator { } #[derive(Debug, Default)] #[repr(transparent)] -pub struct SumAccumulator { +pub struct PaymentProcessedAmountAccumulator { pub total: Option<i64>, } @@ -50,8 +50,8 @@ impl RefundMetricAccumulator for CountAccumulator { } } -impl RefundMetricAccumulator for SumAccumulator { - type MetricOutput = Option<u64>; +impl RefundMetricAccumulator for PaymentProcessedAmountAccumulator { + type MetricOutput = (Option<u64>, Option<u64>); #[inline] fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) { self.total = match ( @@ -68,7 +68,7 @@ impl RefundMetricAccumulator for SumAccumulator { } #[inline] fn collect(self) -> Self::MetricOutput { - self.total.and_then(|i| u64::try_from(i).ok()) + (self.total.and_then(|i| u64::try_from(i).ok()), Some(0)) } } @@ -98,11 +98,14 @@ impl RefundMetricAccumulator for SuccessRateAccumulator { impl RefundMetricsAccumulator { pub fn collect(self) -> RefundMetricsBucketValue { + let (refund_processed_amount, refund_processed_amount_in_usd) = + self.processed_amount.collect(); RefundMetricsBucketValue { refund_success_rate: self.refund_success_rate.collect(), refund_count: self.refund_count.collect(), refund_success_count: self.refund_success.collect(), - refund_processed_amount: self.processed_amount.collect(), + refund_processed_amount, + refund_processed_amount_in_usd, } } } diff --git a/crates/analytics/src/refunds/core.rs b/crates/analytics/src/refunds/core.rs index 9c4770c79ee..e3bfa4da9d1 100644 --- a/crates/analytics/src/refunds/core.rs +++ b/crates/analytics/src/refunds/core.rs @@ -5,9 +5,12 @@ use api_models::analytics::{ refunds::{ RefundDimensions, RefundMetrics, RefundMetricsBucketIdentifier, RefundMetricsBucketResponse, }, - AnalyticsMetadata, GetRefundFilterRequest, GetRefundMetricRequest, MetricsResponse, - RefundFilterValue, RefundFiltersResponse, + GetRefundFilterRequest, GetRefundMetricRequest, RefundFilterValue, RefundFiltersResponse, + RefundsAnalyticsMetadata, RefundsMetricsResponse, }; +use bigdecimal::ToPrimitive; +use common_enums::Currency; +use currency_conversion::{conversion::convert, types::ExchangeRates}; use error_stack::ResultExt; use router_env::{ logger, @@ -29,9 +32,10 @@ use crate::{ pub async fn get_metrics( pool: &AnalyticsProvider, + ex_rates: &ExchangeRates, auth: &AuthInfo, req: GetRefundMetricRequest, -) -> AnalyticsResult<MetricsResponse<RefundMetricsBucketResponse>> { +) -> AnalyticsResult<RefundsMetricsResponse<RefundMetricsBucketResponse>> { let mut metrics_accumulator: HashMap<RefundMetricsBucketIdentifier, RefundMetricsAccumulator> = HashMap::new(); let mut set = tokio::task::JoinSet::new(); @@ -86,16 +90,20 @@ pub async fn get_metrics( logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}"); let metrics_builder = metrics_accumulator.entry(id).or_default(); match metric { - RefundMetrics::RefundSuccessRate => metrics_builder - .refund_success_rate - .add_metrics_bucket(&value), - RefundMetrics::RefundCount => { + RefundMetrics::RefundSuccessRate | RefundMetrics::SessionizedRefundSuccessRate => { + metrics_builder + .refund_success_rate + .add_metrics_bucket(&value) + } + RefundMetrics::RefundCount | RefundMetrics::SessionizedRefundCount => { metrics_builder.refund_count.add_metrics_bucket(&value) } - RefundMetrics::RefundSuccessCount => { + RefundMetrics::RefundSuccessCount + | RefundMetrics::SessionizedRefundSuccessCount => { metrics_builder.refund_success.add_metrics_bucket(&value) } - RefundMetrics::RefundProcessedAmount => { + RefundMetrics::RefundProcessedAmount + | RefundMetrics::SessionizedRefundProcessedAmount => { metrics_builder.processed_amount.add_metrics_bucket(&value) } } @@ -107,18 +115,45 @@ pub async fn get_metrics( metrics_accumulator ); } + let mut total_refund_processed_amount = 0; + let mut total_refund_processed_amount_in_usd = 0; let query_data: Vec<RefundMetricsBucketResponse> = metrics_accumulator .into_iter() - .map(|(id, val)| RefundMetricsBucketResponse { - values: val.collect(), - dimensions: id, + .map(|(id, val)| { + let mut collected_values = val.collect(); + if let Some(amount) = collected_values.refund_processed_amount { + let amount_in_usd = id + .currency + .and_then(|currency| { + i64::try_from(amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default(); + collected_values.refund_processed_amount_in_usd = amount_in_usd; + total_refund_processed_amount += amount; + total_refund_processed_amount_in_usd += amount_in_usd.unwrap_or(0); + } + RefundMetricsBucketResponse { + values: collected_values, + dimensions: id, + } }) .collect(); - Ok(MetricsResponse { + Ok(RefundsMetricsResponse { query_data, - meta_data: [AnalyticsMetadata { - current_time_range: req.time_range, + meta_data: [RefundsAnalyticsMetadata { + total_refund_processed_amount: Some(total_refund_processed_amount), + total_refund_processed_amount_in_usd: Some(total_refund_processed_amount_in_usd), }], }) } diff --git a/crates/analytics/src/refunds/metrics.rs b/crates/analytics/src/refunds/metrics.rs index 6ecfd8aeb29..c211ea82d7a 100644 --- a/crates/analytics/src/refunds/metrics.rs +++ b/crates/analytics/src/refunds/metrics.rs @@ -10,6 +10,7 @@ mod refund_count; mod refund_processed_amount; mod refund_success_count; mod refund_success_rate; +mod sessionized_metrics; use std::collections::HashSet; use refund_count::RefundCount; @@ -101,6 +102,26 @@ where .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } + Self::SessionizedRefundSuccessRate => { + sessionized_metrics::RefundSuccessRate::default() + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedRefundCount => { + sessionized_metrics::RefundCount::default() + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedRefundSuccessCount => { + sessionized_metrics::RefundSuccessCount::default() + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedRefundProcessedAmount => { + sessionized_metrics::RefundProcessedAmount::default() + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } } } } diff --git a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs index f0f51a21fe0..6cba5f58fed 100644 --- a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs +++ b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs @@ -52,6 +52,7 @@ where alias: Some("total"), }) .switch()?; + query_builder.add_select_column("currency").switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", @@ -78,6 +79,7 @@ where query_builder.add_group_by_clause(dim).switch()?; } + query_builder.add_group_by_clause("currency").switch()?; if let Some(granularity) = granularity.as_ref() { granularity .set_group_by_clause(&mut query_builder) diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs new file mode 100644 index 00000000000..bb404cd3410 --- /dev/null +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs @@ -0,0 +1,11 @@ +mod refund_count; +mod refund_processed_amount; +mod refund_success_count; +mod refund_success_rate; + +pub(super) use refund_count::RefundCount; +pub(super) use refund_processed_amount::RefundProcessedAmount; +pub(super) use refund_success_count::RefundSuccessCount; +pub(super) use refund_success_rate::RefundSuccessRate; + +pub use super::{RefundMetric, RefundMetricAnalytics, RefundMetricRow}; diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs new file mode 100644 index 00000000000..c77e1f7a52c --- /dev/null +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs @@ -0,0 +1,120 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::RefundMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct RefundCount {} + +#[async_trait::async_trait] +impl<T> super::RefundMetric<T> for RefundCount +where + T: AnalyticsDataSource + super::RefundMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[RefundDimensions], + auth: &AuthInfo, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::RefundSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<RefundMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + RefundMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + i.refund_status.as_ref().map(|i| i.0.to_string()), + i.connector.clone(), + i.refund_type.as_ref().map(|i| i.0.to_string()), + i.profile_id.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs new file mode 100644 index 00000000000..c91938228af --- /dev/null +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs @@ -0,0 +1,129 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::RefundMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; +#[derive(Default)] +pub(crate) struct RefundProcessedAmount {} + +#[async_trait::async_trait] +impl<T> super::RefundMetric<T> for RefundProcessedAmount +where + T: AnalyticsDataSource + super::RefundMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[RefundDimensions], + auth: &AuthInfo, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> + where + T: AnalyticsDataSource + super::RefundMetricAnalytics, + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::RefundSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Sum { + field: "refund_amount", + alias: Some("total"), + }) + .switch()?; + query_builder.add_select_column("currency").switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder.add_group_by_clause(dim).switch()?; + } + + query_builder.add_group_by_clause("currency").switch()?; + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .switch()?; + } + + query_builder + .add_filter_clause( + RefundDimensions::RefundStatus, + storage_enums::RefundStatus::Success, + ) + .switch()?; + + query_builder + .execute_query::<RefundMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + RefundMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.refund_type.as_ref().map(|i| i.0.to_string()), + i.profile_id.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs new file mode 100644 index 00000000000..332261a3208 --- /dev/null +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs @@ -0,0 +1,125 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::RefundMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct RefundSuccessCount {} + +#[async_trait::async_trait] +impl<T> super::RefundMetric<T> for RefundSuccessCount +where + T: AnalyticsDataSource + super::RefundMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[RefundDimensions], + auth: &AuthInfo, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> + where + T: AnalyticsDataSource + super::RefundMetricAnalytics, + { + let mut query_builder = QueryBuilder::new(AnalyticsCollection::RefundSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range.set_filter_clause(&mut query_builder).switch()?; + + for dim in dimensions.iter() { + query_builder.add_group_by_clause(dim).switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .switch()?; + } + + query_builder + .add_filter_clause( + RefundDimensions::RefundStatus, + storage_enums::RefundStatus::Success, + ) + .switch()?; + query_builder + .execute_query::<RefundMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + RefundMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.refund_type.as_ref().map(|i| i.0.to_string()), + i.profile_id.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs new file mode 100644 index 00000000000..35ee0d61b50 --- /dev/null +++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs @@ -0,0 +1,120 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::RefundMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; +#[derive(Default)] +pub(crate) struct RefundSuccessRate {} + +#[async_trait::async_trait] +impl<T> super::RefundMetric<T> for RefundSuccessRate +where + T: AnalyticsDataSource + super::RefundMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[RefundDimensions], + auth: &AuthInfo, + filters: &RefundFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> + where + T: AnalyticsDataSource + super::RefundMetricAnalytics, + { + let mut query_builder = QueryBuilder::new(AnalyticsCollection::RefundSessionized); + let mut dimensions = dimensions.to_vec(); + + dimensions.push(RefundDimensions::RefundStatus); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range.set_filter_clause(&mut query_builder).switch()?; + + for dim in dimensions.iter() { + query_builder.add_group_by_clause(dim).switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .switch()?; + } + + query_builder + .execute_query::<RefundMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + RefundMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.refund_type.as_ref().map(|i| i.0.to_string()), + i.profile_id.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 8d63bc3096c..70c0e0e78dc 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -203,7 +203,7 @@ pub struct AnalyticsMetadata { #[derive(Debug, serde::Serialize)] pub struct PaymentsAnalyticsMetadata { pub total_payment_processed_amount: Option<u64>, - pub total_payment_processed_amount_usd: Option<u64>, + pub total_payment_processed_amount_in_usd: Option<u64>, pub total_payment_processed_amount_without_smart_retries: Option<u64>, pub total_payment_processed_amount_without_smart_retries_usd: Option<u64>, pub total_payment_processed_count: Option<u64>, @@ -228,6 +228,11 @@ pub struct PaymentIntentsAnalyticsMetadata { pub total_payment_processed_count_without_smart_retries: Option<u64>, } +#[derive(Debug, serde::Serialize)] +pub struct RefundsAnalyticsMetadata { + pub total_refund_processed_amount: Option<u64>, + pub total_refund_processed_amount_in_usd: Option<u64>, +} #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentFiltersRequest { @@ -362,6 +367,12 @@ pub struct PaymentIntentsMetricsResponse<T> { pub meta_data: [PaymentIntentsAnalyticsMetadata; 1], } +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RefundsMetricsResponse<T> { + pub query_data: Vec<T>, + pub meta_data: [RefundsAnalyticsMetadata; 1], +} #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetApiEventFiltersRequest { diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs index 1faba79eb37..b34f8c9293c 100644 --- a/crates/api_models/src/analytics/payments.rs +++ b/crates/api_models/src/analytics/payments.rs @@ -271,7 +271,7 @@ pub struct PaymentMetricsBucketValue { pub payment_count: Option<u64>, pub payment_success_count: Option<u64>, pub payment_processed_amount: Option<u64>, - pub payment_processed_amount_usd: Option<u64>, + pub payment_processed_amount_in_usd: Option<u64>, pub payment_processed_count: Option<u64>, pub payment_processed_amount_without_smart_retries: Option<u64>, pub payment_processed_amount_without_smart_retries_usd: Option<u64>, diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs index ef17387d1ea..d981bd4382f 100644 --- a/crates/api_models/src/analytics/refunds.rs +++ b/crates/api_models/src/analytics/refunds.rs @@ -88,6 +88,10 @@ pub enum RefundMetrics { RefundCount, RefundSuccessCount, RefundProcessedAmount, + SessionizedRefundSuccessRate, + SessionizedRefundCount, + SessionizedRefundSuccessCount, + SessionizedRefundProcessedAmount, } pub mod metric_behaviour { @@ -176,6 +180,7 @@ pub struct RefundMetricsBucketValue { pub refund_count: Option<u64>, pub refund_success_count: Option<u64>, pub refund_processed_amount: Option<u64>, + pub refund_processed_amount_in_usd: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct RefundMetricsBucketResponse { diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 7272abffbff..77d8cb117ef 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -168,6 +168,11 @@ impl<T> ApiEventMetric for PaymentIntentsMetricsResponse<T> { } } +impl<T> ApiEventMetric for RefundsMetricsResponse<T> { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Miscellaneous) + } +} #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl ApiEventMetric for PaymentMethodIntentConfirmInternal { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index aba1c2e2efa..fc45e3f80e6 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -652,7 +652,8 @@ pub mod routes { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; - analytics::refunds::get_metrics(&state.pool, &auth, req) + let ex_rates = get_forex_exchange_rates(state.clone()).await?; + analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, @@ -690,7 +691,8 @@ pub mod routes { let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; - analytics::refunds::get_metrics(&state.pool, &auth, req) + let ex_rates = get_forex_exchange_rates(state.clone()).await?; + analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, @@ -735,7 +737,8 @@ pub mod routes { merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; - analytics::refunds::get_metrics(&state.pool, &auth, req) + let ex_rates = get_forex_exchange_rates(state.clone()).await?; + analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) },
2024-10-23T19:59:24Z
## Description <!-- Describe your changes in detail --> - Add sessionized metrics module and implement backwards compatibility. - Implement currency conversion for refunds analytics ### Minor unrelated changes - refactor inconsistent naming of fields in some places => [commit](https://github.com/juspay/hyperswitch/pull/6419/commits/08e53d63b5561163712bdfaefebed1caecdb793b) - fix sankey incorrect formula => [commit](https://github.com/juspay/hyperswitch/pull/6419/commits/6ae2fb68290bf91a6d10178aa620893c3fd45846) ### Fixes #6417 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - Refund metrics didn't had a `sessionized_metrics` module and implementation as were there in payments and payment_intents metrics - Refund metrics weren't implementing currency conversion. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStat' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTA4ODY3NSwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.S0OBbdBmFjnRC-1hP-QTVA2fzQESHIvou_8dtmFDCgY' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-15T18:30:00Z", "endTime": "2024-11-07T09:30:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_refund_processed_amount" ], "delta": true } ]' ``` <img width="750" alt="Screenshot 2024-11-07 at 2 56 08 PM" src="https://github.com/user-attachments/assets/6f5ba9b3-1b41-498f-a685-b1e8bf30f78d"> ### For sankey changes ```bash curl --location 'http://localhost:8080/analytics/v1/profile/metrics/sankey' \ --header 'accept: */*' \ --header 'accept-language: en-US,en;q=0.9' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTA4ODY3NSwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.S0OBbdBmFjnRC-1hP-QTVA2fzQESHIvou_8dtmFDCgY' \ --header 'content-type: application/json' \ --header 'origin: https://integ.hyperswitch.io' \ --header 'priority: u=1, i' \ --header 'referer: https://integ.hyperswitch.io/dashboard/new-analytics-payment' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'sec-fetch-dest: empty' \ --header 'sec-fetch-mode: cors' \ --header 'sec-fetch-site: same-origin' \ --header 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --data '{"startTime":"2024-10-30T18:30:00Z","endTime":"2024-11-08T11:16:00Z"}' ``` <img width="537" alt="Screenshot 2024-11-08 at 3 03 12 PM" src="https://github.com/user-attachments/assets/1fb56fd2-1585-4423-84dd-3883cc3dfc63">
1ba3d84df1e93d2286db1a262c4a67b3861b90c0
```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStat' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTA4ODY3NSwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.S0OBbdBmFjnRC-1hP-QTVA2fzQESHIvou_8dtmFDCgY' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-15T18:30:00Z", "endTime": "2024-11-07T09:30:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_refund_processed_amount" ], "delta": true } ]' ``` <img width="750" alt="Screenshot 2024-11-07 at 2 56 08 PM" src="https://github.com/user-attachments/assets/6f5ba9b3-1b41-498f-a685-b1e8bf30f78d"> ### For sankey changes ```bash curl --location 'http://localhost:8080/analytics/v1/profile/metrics/sankey' \ --header 'accept: */*' \ --header 'accept-language: en-US,en;q=0.9' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTA4ODY3NSwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.S0OBbdBmFjnRC-1hP-QTVA2fzQESHIvou_8dtmFDCgY' \ --header 'content-type: application/json' \ --header 'origin: https://integ.hyperswitch.io' \ --header 'priority: u=1, i' \ --header 'referer: https://integ.hyperswitch.io/dashboard/new-analytics-payment' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'sec-fetch-dest: empty' \ --header 'sec-fetch-mode: cors' \ --header 'sec-fetch-site: same-origin' \ --header 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --data '{"startTime":"2024-10-30T18:30:00Z","endTime":"2024-11-08T11:16:00Z"}' ``` <img width="537" alt="Screenshot 2024-11-08 at 3 03 12 PM" src="https://github.com/user-attachments/assets/1fb56fd2-1585-4423-84dd-3883cc3dfc63">
[ "crates/analytics/src/payment_intents/core.rs", "crates/analytics/src/payments/accumulator.rs", "crates/analytics/src/payments/core.rs", "crates/analytics/src/refunds/accumulator.rs", "crates/analytics/src/refunds/core.rs", "crates/analytics/src/refunds/metrics.rs", "crates/analytics/src/refunds/metrics/refund_processed_amount.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs", "crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs", "crates/api_models/src/analytics.rs", "crates/api_models/src/analytics/payments.rs", "crates/api_models/src/analytics/refunds.rs", "crates/api_models/src/events.rs", "crates/router/src/analytics.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6416
Bug: feat(analytics): implement currency conversion to power multi-currency aggregation ## Current Behaviour The total amount calculated for all payment analytics buckets related to amounts is incorrect because currency conversion is not being applied before summing the values. As a result, amounts in different currencies are being added together, leading to an inaccurate total. ## Proposed Changes - introduce `<AMOUNT_RELATED_FIELD>_in_usd` fields to convert and store value in `USD` - introduce total_in_usd to store the total value in usd - Generally provide currency_conversion facility to metrics function for other future use cases
diff --git a/Cargo.lock b/Cargo.lock index 26ad619ee0b..8c69154fcea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -353,6 +353,7 @@ dependencies = [ "bigdecimal", "common_enums", "common_utils", + "currency_conversion", "diesel_models", "error-stack", "futures 0.3.30", @@ -363,6 +364,7 @@ dependencies = [ "opensearch", "reqwest 0.11.27", "router_env", + "rust_decimal", "serde", "serde_json", "sqlx", diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml index 687d5a2e208..db516c49abd 100644 --- a/crates/analytics/Cargo.toml +++ b/crates/analytics/Cargo.toml @@ -21,6 +21,7 @@ hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" masking = { version = "0.1.0", path = "../masking" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } +currency_conversion = { version = "0.1.0", path = "../currency_conversion" } #Third Party dependencies actix-web = "4.5.1" @@ -34,6 +35,7 @@ futures = "0.3.30" once_cell = "1.19.0" opensearch = { version = "2.2.0", features = ["aws-auth"] } reqwest = { version = "0.11.27", features = ["serde_json"] } +rust_decimal = "1.35" serde = { version = "1.0.197", features = ["derive", "rc"] } serde_json = "1.0.115" sqlx = { version = "0.8.2", features = ["postgres", "runtime-tokio", "runtime-tokio-native-tls", "time", "bigdecimal"] } diff --git a/crates/analytics/src/errors.rs b/crates/analytics/src/errors.rs index 0e39a4ddd92..d7b15a6db11 100644 --- a/crates/analytics/src/errors.rs +++ b/crates/analytics/src/errors.rs @@ -12,6 +12,8 @@ pub enum AnalyticsError { UnknownError, #[error("Access Forbidden Analytics Error")] AccessForbiddenError, + #[error("Failed to fetch currency exchange rate")] + ForexFetchFailed, } impl ErrorSwitch<ApiErrorResponse> for AnalyticsError { @@ -32,6 +34,12 @@ impl ErrorSwitch<ApiErrorResponse> for AnalyticsError { Self::AccessForbiddenError => { ApiErrorResponse::Unauthorized(ApiError::new("IR", 0, "Access Forbidden", None)) } + Self::ForexFetchFailed => ApiErrorResponse::InternalServerError(ApiError::new( + "HE", + 0, + "Failed to fetch currency exchange rate", + None, + )), } } } diff --git a/crates/analytics/src/payment_intents/accumulator.rs b/crates/analytics/src/payment_intents/accumulator.rs index cbb8335cea0..ef3cd3129c4 100644 --- a/crates/analytics/src/payment_intents/accumulator.rs +++ b/crates/analytics/src/payment_intents/accumulator.rs @@ -86,7 +86,7 @@ impl PaymentIntentMetricAccumulator for CountAccumulator { } impl PaymentIntentMetricAccumulator for SmartRetriedAmountAccumulator { - type MetricOutput = (Option<u64>, Option<u64>); + type MetricOutput = (Option<u64>, Option<u64>, Option<u64>, Option<u64>); #[inline] fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) { self.amount = match ( @@ -117,7 +117,7 @@ impl PaymentIntentMetricAccumulator for SmartRetriedAmountAccumulator { .amount_without_retries .and_then(|i| u64::try_from(i).ok()) .or(Some(0)); - (with_retries, without_retries) + (with_retries, without_retries, Some(0), Some(0)) } } @@ -185,7 +185,14 @@ impl PaymentIntentMetricAccumulator for PaymentsSuccessRateAccumulator { } impl PaymentIntentMetricAccumulator for ProcessedAmountAccumulator { - type MetricOutput = (Option<u64>, Option<u64>, Option<u64>, Option<u64>); + type MetricOutput = ( + Option<u64>, + Option<u64>, + Option<u64>, + Option<u64>, + Option<u64>, + Option<u64>, + ); #[inline] fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) { self.total_with_retries = match ( @@ -235,6 +242,8 @@ impl PaymentIntentMetricAccumulator for ProcessedAmountAccumulator { count_with_retries, total_without_retries, count_without_retries, + Some(0), + Some(0), ) } } @@ -301,13 +310,19 @@ impl PaymentIntentMetricsAccumulator { payments_success_rate, payments_success_rate_without_smart_retries, ) = self.payments_success_rate.collect(); - let (smart_retried_amount, smart_retried_amount_without_smart_retries) = - self.smart_retried_amount.collect(); + let ( + smart_retried_amount, + smart_retried_amount_without_smart_retries, + smart_retried_amount_in_usd, + smart_retried_amount_without_smart_retries_in_usd, + ) = self.smart_retried_amount.collect(); let ( payment_processed_amount, payment_processed_count, payment_processed_amount_without_smart_retries, payment_processed_count_without_smart_retries, + payment_processed_amount_in_usd, + payment_processed_amount_without_smart_retries_in_usd, ) = self.payment_processed_amount.collect(); let ( payments_success_rate_distribution_without_smart_retries, @@ -317,7 +332,9 @@ impl PaymentIntentMetricsAccumulator { successful_smart_retries: self.successful_smart_retries.collect(), total_smart_retries: self.total_smart_retries.collect(), smart_retried_amount, + smart_retried_amount_in_usd, smart_retried_amount_without_smart_retries, + smart_retried_amount_without_smart_retries_in_usd, payment_intent_count: self.payment_intent_count.collect(), successful_payments, successful_payments_without_smart_retries, @@ -330,6 +347,8 @@ impl PaymentIntentMetricsAccumulator { payment_processed_count_without_smart_retries, payments_success_rate_distribution_without_smart_retries, payments_failure_rate_distribution_without_smart_retries, + payment_processed_amount_in_usd, + payment_processed_amount_without_smart_retries_in_usd, } } } diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index e04c3b7bd9e..076c28f4f37 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -10,8 +10,10 @@ use api_models::analytics::{ PaymentIntentFiltersResponse, PaymentIntentsAnalyticsMetadata, PaymentIntentsMetricsResponse, SankeyResponse, }; -use common_enums::IntentStatus; +use bigdecimal::ToPrimitive; +use common_enums::{Currency, IntentStatus}; use common_utils::{errors::CustomResult, types::TimeRange}; +use currency_conversion::{conversion::convert, types::ExchangeRates}; use error_stack::ResultExt; use router_env::{ instrument, logger, @@ -120,6 +122,7 @@ pub async fn get_sankey( #[instrument(skip_all)] pub async fn get_metrics( pool: &AnalyticsProvider, + ex_rates: &ExchangeRates, auth: &AuthInfo, req: GetPaymentIntentMetricRequest, ) -> AnalyticsResult<PaymentIntentsMetricsResponse<MetricsBucketResponse>> { @@ -226,16 +229,20 @@ pub async fn get_metrics( let mut success = 0; let mut success_without_smart_retries = 0; let mut total_smart_retried_amount = 0; + let mut total_smart_retried_amount_in_usd = 0; let mut total_smart_retried_amount_without_smart_retries = 0; + let mut total_smart_retried_amount_without_smart_retries_in_usd = 0; let mut total = 0; let mut total_payment_processed_amount = 0; + let mut total_payment_processed_amount_in_usd = 0; let mut total_payment_processed_count = 0; let mut total_payment_processed_amount_without_smart_retries = 0; + let mut total_payment_processed_amount_without_smart_retries_in_usd = 0; let mut total_payment_processed_count_without_smart_retries = 0; let query_data: Vec<MetricsBucketResponse> = metrics_accumulator .into_iter() .map(|(id, val)| { - let collected_values = val.collect(); + let mut collected_values = val.collect(); if let Some(success_count) = collected_values.successful_payments { success += success_count; } @@ -247,20 +254,95 @@ pub async fn get_metrics( total += total_count; } if let Some(retried_amount) = collected_values.smart_retried_amount { + let amount_in_usd = id + .currency + .and_then(|currency| { + i64::try_from(retried_amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default(); + collected_values.smart_retried_amount_in_usd = amount_in_usd; total_smart_retried_amount += retried_amount; + total_smart_retried_amount_in_usd += amount_in_usd.unwrap_or(0); } if let Some(retried_amount) = collected_values.smart_retried_amount_without_smart_retries { + let amount_in_usd = id + .currency + .and_then(|currency| { + i64::try_from(retried_amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default(); + collected_values.smart_retried_amount_without_smart_retries_in_usd = amount_in_usd; total_smart_retried_amount_without_smart_retries += retried_amount; + total_smart_retried_amount_without_smart_retries_in_usd += + amount_in_usd.unwrap_or(0); } if let Some(amount) = collected_values.payment_processed_amount { + let amount_in_usd = id + .currency + .and_then(|currency| { + i64::try_from(amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default(); + collected_values.payment_processed_amount_in_usd = amount_in_usd; + total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0); total_payment_processed_amount += amount; } if let Some(count) = collected_values.payment_processed_count { total_payment_processed_count += count; } if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries { + let amount_in_usd = id + .currency + .and_then(|currency| { + i64::try_from(amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default(); + collected_values.payment_processed_amount_without_smart_retries_in_usd = + amount_in_usd; + total_payment_processed_amount_without_smart_retries_in_usd += + amount_in_usd.unwrap_or(0); total_payment_processed_amount_without_smart_retries += amount; } if let Some(count) = collected_values.payment_processed_count_without_smart_retries { @@ -293,6 +375,14 @@ pub async fn get_metrics( total_payment_processed_amount_without_smart_retries: Some( total_payment_processed_amount_without_smart_retries, ), + total_smart_retried_amount_in_usd: Some(total_smart_retried_amount_in_usd), + total_smart_retried_amount_without_smart_retries_in_usd: Some( + total_smart_retried_amount_without_smart_retries_in_usd, + ), + total_payment_processed_amount_in_usd: Some(total_payment_processed_amount_in_usd), + total_payment_processed_amount_without_smart_retries_in_usd: Some( + total_payment_processed_amount_without_smart_retries_in_usd, + ), total_payment_processed_count: Some(total_payment_processed_count), total_payment_processed_count_without_smart_retries: Some( total_payment_processed_count_without_smart_retries, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs index 506965375f5..2ba75ca8519 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs @@ -61,7 +61,7 @@ where query_builder .add_select_column("attempt_count == 1 as first_attempt") .switch()?; - + query_builder.add_select_column("currency").switch()?; query_builder .add_select_column(Aggregate::Sum { field: "amount", @@ -101,7 +101,10 @@ where .add_group_by_clause("attempt_count") .attach_printable("Error grouping by attempt_count") .switch()?; - + query_builder + .add_group_by_clause("currency") + .attach_printable("Error grouping by currency") + .switch()?; if let Some(granularity) = granularity.as_ref() { granularity .set_group_by_clause(&mut query_builder) diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs index 8105a4c82a4..b92b7356924 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs @@ -63,6 +63,7 @@ where .add_select_column("attempt_count == 1 as first_attempt") .switch()?; + query_builder.add_select_column("currency").switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", @@ -102,7 +103,10 @@ where .add_group_by_clause("first_attempt") .attach_printable("Error grouping by first_attempt") .switch()?; - + query_builder + .add_group_by_clause("currency") + .attach_printable("Error grouping by first_attempt") + .switch()?; if let Some(granularity) = granularity.as_ref() { granularity .set_group_by_clause(&mut query_builder) diff --git a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs index 8468911f7bb..ac08f59f358 100644 --- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs @@ -62,7 +62,7 @@ where query_builder .add_select_column("attempt_count == 1 as first_attempt") .switch()?; - + query_builder.add_select_column("currency").switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", @@ -102,7 +102,10 @@ where .add_group_by_clause("first_attempt") .attach_printable("Error grouping by first_attempt") .switch()?; - + query_builder + .add_group_by_clause("currency") + .attach_printable("Error grouping by currency") + .switch()?; if let Some(granularity) = granularity.as_ref() { granularity .set_group_by_clause(&mut query_builder) diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs index 4388b2071fe..651eeb0bcfe 100644 --- a/crates/analytics/src/payments/accumulator.rs +++ b/crates/analytics/src/payments/accumulator.rs @@ -272,7 +272,14 @@ impl PaymentMetricAccumulator for CountAccumulator { } impl PaymentMetricAccumulator for ProcessedAmountAccumulator { - type MetricOutput = (Option<u64>, Option<u64>, Option<u64>, Option<u64>); + type MetricOutput = ( + Option<u64>, + Option<u64>, + Option<u64>, + Option<u64>, + Option<u64>, + Option<u64>, + ); #[inline] fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { self.total_with_retries = match ( @@ -322,6 +329,8 @@ impl PaymentMetricAccumulator for ProcessedAmountAccumulator { count_with_retries, total_without_retries, count_without_retries, + Some(0), + Some(0), ) } } @@ -378,6 +387,8 @@ impl PaymentMetricsAccumulator { payment_processed_count, payment_processed_amount_without_smart_retries, payment_processed_count_without_smart_retries, + payment_processed_amount_usd, + payment_processed_amount_without_smart_retries_usd, ) = self.processed_amount.collect(); let ( payments_success_rate_distribution, @@ -406,6 +417,8 @@ impl PaymentMetricsAccumulator { payments_failure_rate_distribution_without_smart_retries, failure_reason_count, failure_reason_count_without_smart_retries, + payment_processed_amount_usd, + payment_processed_amount_without_smart_retries_usd, } } } diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs index 59ae549b283..bcd009270dc 100644 --- a/crates/analytics/src/payments/core.rs +++ b/crates/analytics/src/payments/core.rs @@ -9,7 +9,10 @@ use api_models::analytics::{ FilterValue, GetPaymentFiltersRequest, GetPaymentMetricRequest, PaymentFiltersResponse, PaymentsAnalyticsMetadata, PaymentsMetricsResponse, }; +use bigdecimal::ToPrimitive; +use common_enums::Currency; use common_utils::errors::CustomResult; +use currency_conversion::{conversion::convert, types::ExchangeRates}; use error_stack::ResultExt; use router_env::{ instrument, logger, @@ -46,6 +49,7 @@ pub enum TaskType { #[instrument(skip_all)] pub async fn get_metrics( pool: &AnalyticsProvider, + ex_rates: &ExchangeRates, auth: &AuthInfo, req: GetPaymentMetricRequest, ) -> AnalyticsResult<PaymentsMetricsResponse<MetricsBucketResponse>> { @@ -224,18 +228,57 @@ pub async fn get_metrics( let mut total_payment_processed_count_without_smart_retries = 0; let mut total_failure_reasons_count = 0; let mut total_failure_reasons_count_without_smart_retries = 0; + let mut total_payment_processed_amount_usd = 0; + let mut total_payment_processed_amount_without_smart_retries_usd = 0; let query_data: Vec<MetricsBucketResponse> = metrics_accumulator .into_iter() .map(|(id, val)| { - let collected_values = val.collect(); + let mut collected_values = val.collect(); if let Some(amount) = collected_values.payment_processed_amount { + let amount_in_usd = id + .currency + .and_then(|currency| { + i64::try_from(amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default(); + collected_values.payment_processed_amount_usd = amount_in_usd; total_payment_processed_amount += amount; + total_payment_processed_amount_usd += amount_in_usd.unwrap_or(0); } if let Some(count) = collected_values.payment_processed_count { total_payment_processed_count += count; } if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries { + let amount_in_usd = id + .currency + .and_then(|currency| { + i64::try_from(amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default(); + collected_values.payment_processed_amount_without_smart_retries_usd = amount_in_usd; total_payment_processed_amount_without_smart_retries += amount; + total_payment_processed_amount_without_smart_retries_usd += + amount_in_usd.unwrap_or(0); } if let Some(count) = collected_values.payment_processed_count_without_smart_retries { total_payment_processed_count_without_smart_retries += count; @@ -252,14 +295,17 @@ pub async fn get_metrics( } }) .collect(); - Ok(PaymentsMetricsResponse { query_data, meta_data: [PaymentsAnalyticsMetadata { total_payment_processed_amount: Some(total_payment_processed_amount), + total_payment_processed_amount_usd: Some(total_payment_processed_amount_usd), total_payment_processed_amount_without_smart_retries: Some( total_payment_processed_amount_without_smart_retries, ), + total_payment_processed_amount_without_smart_retries_usd: Some( + total_payment_processed_amount_without_smart_retries_usd, + ), total_payment_processed_count: Some(total_payment_processed_count), total_payment_processed_count_without_smart_retries: Some( total_payment_processed_count_without_smart_retries, diff --git a/crates/analytics/src/payments/metrics/payment_processed_amount.rs b/crates/analytics/src/payments/metrics/payment_processed_amount.rs index b8b3868803c..fa54c173041 100644 --- a/crates/analytics/src/payments/metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payments/metrics/payment_processed_amount.rs @@ -50,6 +50,7 @@ where alias: Some("total"), }) .switch()?; + query_builder.add_select_column("currency").switch()?; query_builder .add_select_column(Aggregate::Min { field: "created_at", @@ -79,6 +80,11 @@ where .switch()?; } + query_builder + .add_group_by_clause("currency") + .attach_printable("Error grouping by currency") + .switch()?; + if let Some(granularity) = granularity.as_ref() { granularity .set_group_by_clause(&mut query_builder) diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs index 9bc554eaae7..a315b2fc4c8 100644 --- a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs @@ -57,6 +57,8 @@ where query_builder.add_select_column("first_attempt").switch()?; + query_builder.add_select_column("currency").switch()?; + query_builder .add_select_column(Aggregate::Sum { field: "amount", @@ -95,6 +97,12 @@ where .add_group_by_clause("first_attempt") .attach_printable("Error grouping by first_attempt") .switch()?; + + query_builder + .add_group_by_clause("currency") + .attach_printable("Error grouping by currency") + .switch()?; + if let Some(granularity) = granularity.as_ref() { granularity .set_group_by_clause(&mut query_builder) diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index b95404080b0..8d63bc3096c 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -203,7 +203,9 @@ pub struct AnalyticsMetadata { #[derive(Debug, serde::Serialize)] pub struct PaymentsAnalyticsMetadata { pub total_payment_processed_amount: Option<u64>, + pub total_payment_processed_amount_usd: Option<u64>, pub total_payment_processed_amount_without_smart_retries: Option<u64>, + pub total_payment_processed_amount_without_smart_retries_usd: Option<u64>, pub total_payment_processed_count: Option<u64>, pub total_payment_processed_count_without_smart_retries: Option<u64>, pub total_failure_reasons_count: Option<u64>, @@ -218,6 +220,10 @@ pub struct PaymentIntentsAnalyticsMetadata { pub total_smart_retried_amount_without_smart_retries: Option<u64>, pub total_payment_processed_amount: Option<u64>, pub total_payment_processed_amount_without_smart_retries: Option<u64>, + pub total_smart_retried_amount_in_usd: Option<u64>, + pub total_smart_retried_amount_without_smart_retries_in_usd: Option<u64>, + pub total_payment_processed_amount_in_usd: Option<u64>, + pub total_payment_processed_amount_without_smart_retries_in_usd: Option<u64>, pub total_payment_processed_count: Option<u64>, pub total_payment_processed_count_without_smart_retries: Option<u64>, } diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs index 41f11c19ef8..05548245e8e 100644 --- a/crates/api_models/src/analytics/payment_intents.rs +++ b/crates/api_models/src/analytics/payment_intents.rs @@ -223,7 +223,9 @@ pub struct PaymentIntentMetricsBucketValue { pub successful_smart_retries: Option<u64>, pub total_smart_retries: Option<u64>, pub smart_retried_amount: Option<u64>, + pub smart_retried_amount_in_usd: Option<u64>, pub smart_retried_amount_without_smart_retries: Option<u64>, + pub smart_retried_amount_without_smart_retries_in_usd: Option<u64>, pub payment_intent_count: Option<u64>, pub successful_payments: Option<u32>, pub successful_payments_without_smart_retries: Option<u32>, @@ -231,8 +233,10 @@ pub struct PaymentIntentMetricsBucketValue { pub payments_success_rate: Option<f64>, pub payments_success_rate_without_smart_retries: Option<f64>, pub payment_processed_amount: Option<u64>, + pub payment_processed_amount_in_usd: Option<u64>, pub payment_processed_count: Option<u64>, pub payment_processed_amount_without_smart_retries: Option<u64>, + pub payment_processed_amount_without_smart_retries_in_usd: Option<u64>, pub payment_processed_count_without_smart_retries: Option<u64>, pub payments_success_rate_distribution_without_smart_retries: Option<f64>, pub payments_failure_rate_distribution_without_smart_retries: Option<f64>, diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs index 1120ab092d7..1faba79eb37 100644 --- a/crates/api_models/src/analytics/payments.rs +++ b/crates/api_models/src/analytics/payments.rs @@ -271,8 +271,10 @@ pub struct PaymentMetricsBucketValue { pub payment_count: Option<u64>, pub payment_success_count: Option<u64>, pub payment_processed_amount: Option<u64>, + pub payment_processed_amount_usd: Option<u64>, pub payment_processed_count: Option<u64>, pub payment_processed_amount_without_smart_retries: Option<u64>, + pub payment_processed_amount_without_smart_retries_usd: Option<u64>, pub payment_processed_count_without_smart_retries: Option<u64>, pub avg_ticket_size: Option<f64>, pub payment_error_message: Option<Vec<ErrorResult>>, diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index aa6db56bb34..fead4c720c3 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -32,7 +32,10 @@ pub mod routes { use crate::{ consts::opensearch::SEARCH_INDEXES, - core::{api_locking, errors::user::UserErrors, verification::utils}, + core::{ + api_locking, currency::get_forex_exchange_rates, errors::user::UserErrors, + verification::utils, + }, db::{user::UserInterface, user_role::ListUserRolesByUserIdPayload}, routes::AppState, services::{ @@ -397,7 +400,8 @@ pub mod routes { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; - analytics::payments::get_metrics(&state.pool, &auth, req) + let ex_rates = get_forex_exchange_rates(state.clone()).await?; + analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, @@ -436,7 +440,8 @@ pub mod routes { let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; - analytics::payments::get_metrics(&state.pool, &auth, req) + let ex_rates = get_forex_exchange_rates(state.clone()).await?; + analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, @@ -482,7 +487,8 @@ pub mod routes { merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; - analytics::payments::get_metrics(&state.pool, &auth, req) + let ex_rates = get_forex_exchange_rates(state.clone()).await?; + analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, @@ -523,7 +529,8 @@ pub mod routes { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; - analytics::payment_intents::get_metrics(&state.pool, &auth, req) + let ex_rates = get_forex_exchange_rates(state.clone()).await?; + analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, @@ -562,7 +569,8 @@ pub mod routes { let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; - analytics::payment_intents::get_metrics(&state.pool, &auth, req) + let ex_rates = get_forex_exchange_rates(state.clone()).await?; + analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, @@ -608,7 +616,8 @@ pub mod routes { merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; - analytics::payment_intents::get_metrics(&state.pool, &auth, req) + let ex_rates = get_forex_exchange_rates(state.clone()).await?; + analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) }, diff --git a/crates/router/src/core/currency.rs b/crates/router/src/core/currency.rs index 96d75098271..912484b014a 100644 --- a/crates/router/src/core/currency.rs +++ b/crates/router/src/core/currency.rs @@ -1,4 +1,6 @@ +use analytics::errors::AnalyticsError; use common_utils::errors::CustomResult; +use currency_conversion::types::ExchangeRates; use error_stack::ResultExt; use crate::{ @@ -46,3 +48,19 @@ pub async fn convert_forex( .change_context(ApiErrorResponse::InternalServerError)?, )) } + +pub async fn get_forex_exchange_rates( + state: SessionState, +) -> CustomResult<ExchangeRates, AnalyticsError> { + let forex_api = state.conf.forex_api.get_inner(); + let rates = get_forex_rates( + &state, + forex_api.call_delay, + forex_api.local_fetch_retry_delay, + forex_api.local_fetch_retry_count, + ) + .await + .change_context(AnalyticsError::ForexFetchFailed)?; + + Ok((*rates.data).clone()) +} diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index dcfe0347d6f..2173478ab67 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -26,7 +26,7 @@ const FALLBACK_FOREX_API_CURRENCY_PREFIX: &str = "USD"; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct FxExchangeRatesCacheEntry { - data: Arc<ExchangeRates>, + pub data: Arc<ExchangeRates>, timestamp: i64, } @@ -421,7 +421,13 @@ pub async fn fallback_fetch_forex_rates( conversions.insert(enum_curr, currency_factors); } None => { - logger::error!("Rates for {} not received from API", &enum_curr); + if enum_curr == enums::Currency::USD { + let currency_factors = + CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0)); + conversions.insert(enum_curr, currency_factors); + } else { + logger::error!("Rates for {} not received from API", &enum_curr); + } } }; }
2024-10-23T19:46:05Z
## Description - implemented currency_conversion for calculating values of amount related metrics from their currency (i.e `INR`) to `USD` and store it in a separate field variant I created `<fieldname>_in_usd` - Implemented a total_amount_in_usd variant for all the total fields related to amounts in query Metadata ### Fixes #6416 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The total amount calculated for all payment analytics buckets related to amounts is incorrect because currency conversion is not being applied before summing the values. As a result, amounts in different currencies are being added together, leading to an inaccurate total. ### Dependency This functionality depends on `currency_conversion` crate directly to fetch exchange rates. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### API request for metrics ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStat' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTgzNzUwNywib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.KlBRpu8DpGZ43u9hsB4xE2oSXNM21HC0RadRdfMe2VI' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-13T18:30:00Z", "endTime": "2024-10-21T12:54:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "payment_processed_amount" ], "delta": true } ]' ``` ### API response ```json { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 150000, "payment_processed_amount_usd": 1782, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": 0, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": "INR", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-10-10T18:30:00.000Z", "end_time": "2024-10-18T08:24:00.000Z" }, "time_bucket": "2024-10-10 18:30:00" }, { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 1794006540, "payment_processed_amount_usd": 1794006540, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": 0, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": "USD", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-10-10T18:30:00.000Z", "end_time": "2024-10-18T08:24:00.000Z" }, "time_bucket": "2024-10-10 18:30:00" }, { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 6540, "payment_processed_amount_usd": 7118, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": 0, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": "EUR", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-10-10T18:30:00.000Z", "end_time": "2024-10-18T08:24:00.000Z" }, "time_bucket": "2024-10-10 18:30:00" } ], "metaData": [ { "total_payment_processed_amount": 1794163080, "total_payment_processed_amount_usd": 1794015440, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 0, "total_failure_reasons_count_without_smart_retries": 0 } ] } ``` ## Testing for various other scenarios ### by tweaking `development.toml` we can create these scenarios ```toml [forex_api] call_delay = 30 local_fetch_retry_count = 5 local_fetch_retry_delay = 1000 api_timeout = 20000 api_key = "YOUR PRIMARY API KEY HER" # set this value to anything else to invalidate it fallback_api_key = "YOUR FALLBACK API KEY HER" # set this value to anything else to invalidate it redis_lock_timeout = 2600 ``` by setting `call_delay` to 30s we can check for the fetch cycle and redis updates. 1. When primary api isn't working (invalidating the primary api key) <img width="1722" alt="Screenshot 2024-10-29 at 12 08 11 AM" src="https://github.com/user-attachments/assets/9b5fe452-d339-4dca-b65d-f3fd3e510037"> #### API response : 200 2. when both keys are invalidated <img width="1709" alt="Screenshot 2024-10-29 at 12 10 32 AM" src="https://github.com/user-attachments/assets/6dcaa6be-236c-40af-b3a1-0d40f789b99c"> <img width="1282" alt="Screenshot 2024-10-29 at 12 32 15 AM" src="https://github.com/user-attachments/assets/0c13bdee-e076-47a7-943b-642765d09804"> #### API response : 500
aee11c560e427195a0d321dff19c0d33ec60ba64
### API request for metrics ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStat' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTgzNzUwNywib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.KlBRpu8DpGZ43u9hsB4xE2oSXNM21HC0RadRdfMe2VI' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-13T18:30:00Z", "endTime": "2024-10-21T12:54:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "payment_processed_amount" ], "delta": true } ]' ``` ### API response ```json { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 150000, "payment_processed_amount_usd": 1782, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": 0, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": "INR", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-10-10T18:30:00.000Z", "end_time": "2024-10-18T08:24:00.000Z" }, "time_bucket": "2024-10-10 18:30:00" }, { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 1794006540, "payment_processed_amount_usd": 1794006540, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": 0, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": "USD", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-10-10T18:30:00.000Z", "end_time": "2024-10-18T08:24:00.000Z" }, "time_bucket": "2024-10-10 18:30:00" }, { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 6540, "payment_processed_amount_usd": 7118, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": 0, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": "EUR", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-10-10T18:30:00.000Z", "end_time": "2024-10-18T08:24:00.000Z" }, "time_bucket": "2024-10-10 18:30:00" } ], "metaData": [ { "total_payment_processed_amount": 1794163080, "total_payment_processed_amount_usd": 1794015440, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 0, "total_failure_reasons_count_without_smart_retries": 0 } ] } ```
[ "Cargo.lock", "crates/analytics/Cargo.toml", "crates/analytics/src/errors.rs", "crates/analytics/src/payment_intents/accumulator.rs", "crates/analytics/src/payment_intents/core.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs", "crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs", "crates/analytics/src/payments/accumulator.rs", "crates/analytics/src/payments/core.rs", "crates/analytics/src/payments/metrics/payment_processed_amount.rs", "crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs", "crates/api_models/src/analytics.rs", "crates/api_models/src/analytics/payment_intents.rs", "crates/api_models/src/analytics/payments.rs", "crates/router/src/analytics.rs", "crates/router/src/core/currency.rs", "crates/router/src/utils/currency.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6020
Bug: [REFACTOR]: [RAPYD] Add amount conversion framework to Rapyd ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://docs.rapyd.net/en/create-refund.html) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :package: Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index da10513b3d3..196eb4ce73d 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -1,11 +1,11 @@ pub mod transformers; -use std::fmt::Debug; use base64::Engine; use common_utils::{ date_time, ext_traits::{Encode, StringExt}, request::RequestContent, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use diesel_models::enums; use error_stack::{Report, ResultExt}; @@ -17,6 +17,7 @@ use transformers as rapyd; use super::utils as connector_utils; use crate::{ configs::settings, + connector::utils::convert_amount, consts, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, @@ -34,9 +35,17 @@ use crate::{ utils::{self, crypto, ByteSliceExt, BytesExt}, }; -#[derive(Debug, Clone)] -pub struct Rapyd; - +#[derive(Clone)] +pub struct Rapyd { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} +impl Rapyd { + pub fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} impl Rapyd { pub fn generate_signature( &self, @@ -198,12 +207,12 @@ impl req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = rapyd::RapydRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + let connector_router_data = rapyd::RapydRouterData::from((amount, req)); let connector_req = rapyd::RapydPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -528,12 +537,12 @@ impl req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = rapyd::RapydRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, req.request.currency, - req.request.amount_to_capture, - req, - ))?; + )?; + let connector_router_data = rapyd::RapydRouterData::from((amount, req)); let connector_req = rapyd::CaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -668,12 +677,12 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = rapyd::RapydRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; + )?; + let connector_router_data = rapyd::RapydRouterData::from((amount, req)); let connector_req = rapyd::RapydRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 1246444ff31..b83ffcec412 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -1,3 +1,4 @@ +use common_utils::types::MinorUnit; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -15,25 +16,22 @@ use crate::{ #[derive(Debug, Serialize)] pub struct RapydRouterData<T> { - pub amount: i64, + pub amount: MinorUnit, pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for RapydRouterData<T> { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), - ) -> Result<Self, Self::Error> { - Ok(Self { +impl<T> From<(MinorUnit, T)> for RapydRouterData<T> { + fn from((amount, router_data): (MinorUnit, T)) -> Self { + Self { amount, - router_data: item, - }) + router_data, + } } } #[derive(Default, Debug, Serialize)] pub struct RapydPaymentsRequest { - pub amount: i64, + pub amount: MinorUnit, pub currency: enums::Currency, pub payment_method: PaymentMethod, pub payment_method_options: Option<PaymentMethodOptions>, @@ -302,7 +300,7 @@ pub struct DisputeResponseData { #[derive(Default, Debug, Serialize)] pub struct RapydRefundRequest { pub payment: String, - pub amount: Option<i64>, + pub amount: Option<MinorUnit>, pub currency: Option<enums::Currency>, } @@ -409,7 +407,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> #[derive(Debug, Serialize, Clone)] pub struct CaptureRequest { - amount: Option<i64>, + amount: Option<MinorUnit>, receipt_email: Option<Secret<String>>, statement_descriptor: Option<String>, } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index b85ae5bfab2..9c21340a7e9 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -471,7 +471,9 @@ impl ConnectorData { enums::Connector::Razorpay => { Ok(ConnectorEnum::Old(Box::new(connector::Razorpay::new()))) } - enums::Connector::Rapyd => Ok(ConnectorEnum::Old(Box::new(&connector::Rapyd))), + enums::Connector::Rapyd => { + Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new()))) + } enums::Connector::Shift4 => { Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new()))) } diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs index fe6bc34cf18..ff083a37e59 100644 --- a/crates/router/tests/connectors/rapyd.rs +++ b/crates/router/tests/connectors/rapyd.rs @@ -16,7 +16,7 @@ impl utils::Connector for Rapyd { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Rapyd; utils::construct_connector_data_old( - Box::new(&Rapyd), + Box::new(Rapyd::new()), types::Connector::Rapyd, types::api::GetToken::Connector, None,
2024-10-23T13:43:06Z
## Description <!-- Describe your changes in detail --> This PR adds amount conversion framework to rapyd. rapyd accepts amount in MinorUnit ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Amount conversion for rapyd Fixes #6020 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
cd6265887adf7c17136e9fb608e97e6dd535e360
[ "crates/router/src/connector/rapyd.rs", "crates/router/src/connector/rapyd/transformers.rs", "crates/router/src/types/api.rs", "crates/router/tests/connectors/rapyd.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6410
Bug: [FEATURE] [PAZE] Add amount, currency and email to paze session response ### Feature Description Add amount, currency and email to paze session response ### Possible Implementation { "wallet_name": "paze", "client_id": "HIDDEN", "client_name": "HIDDEN", "client_profile_id": "HIDDEN", "transaction_currency_code": "USD", "transaction_amount": "12.34", "email_address": "guest@example.com" } ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index bd9de3a2962..c85bfad3326 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -16199,7 +16199,9 @@ "required": [ "client_id", "client_name", - "client_profile_id" + "client_profile_id", + "transaction_currency_code", + "transaction_amount" ], "properties": { "client_id": { @@ -16213,6 +16215,21 @@ "client_profile_id": { "type": "string", "description": "Paze Client Profile ID" + }, + "transaction_currency_code": { + "$ref": "#/components/schemas/Currency" + }, + "transaction_amount": { + "type": "string", + "description": "The transaction amount", + "example": "38.02" + }, + "email_address": { + "type": "string", + "description": "Email Address", + "example": "johntest@test.com", + "nullable": true, + "maxLength": 255 } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 61c7911170a..913cb1810ad 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5578,6 +5578,15 @@ pub struct PazeSessionTokenResponse { pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, + /// The transaction currency code + #[schema(value_type = Currency, example = "USD")] + pub transaction_currency_code: api_enums::Currency, + /// The transaction amount + #[schema(value_type = String, example = "38.02")] + pub transaction_amount: StringMajorUnit, + /// Email Address + #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] + pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index d29672058f8..bbeb041e74e 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -816,7 +816,7 @@ pub struct PaymentsSessionData { pub country: Option<common_enums::CountryAlpha2>, pub surcharge_details: Option<SurchargeDetails>, pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>, - + pub email: Option<pii::Email>, // Minor Unit amount for amount frame work pub minor_amount: MinorUnit, } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 736ffdd7b8b..ba8054696a1 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -511,7 +511,13 @@ fn create_paze_session_token( field_name: "connector_wallets_details".to_string(), expected_format: "paze_metadata_format".to_string(), })?; - + let required_amount_type = StringMajorUnitForConnector; + let transaction_currency_code = router_data.request.currency; + let transaction_amount = required_amount_type + .convert(router_data.request.minor_amount, transaction_currency_code) + .change_context(errors::ApiErrorResponse::PreconditionFailed { + message: "Failed to convert amount to string major unit for paze".to_string(), + })?; Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::Paze(Box::new( @@ -519,6 +525,9 @@ fn create_paze_session_token( client_id: paze_wallet_details.data.client_id, client_name: paze_wallet_details.data.client_name, client_profile_id: paze_wallet_details.data.client_profile_id, + transaction_currency_code, + transaction_amount, + email_address: router_data.request.email.clone(), }, )), }), diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 66e5c996d34..1e3472fc3c1 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2644,6 +2644,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionD ), order_details, surcharge_details: payment_data.surcharge_details, + email: payment_data.email, }) } } @@ -2703,6 +2704,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionD }, ), order_details, + email: payment_data.email, surcharge_details: payment_data.surcharge_details, }) }
2024-10-23T11:22:25Z
## Description <!-- Describe your changes in detail --> Add amount, currency and email to paze session response ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/6410 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Session Request Paze: ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "payment_id": "pay_Omdaxo733MC34fLvCfYw", "wallets": [], "client_secret": "pay_Omdaxo733MC34fLvCfYw_secret_ak2iLU1A5E6PK6XqqY6h" }' ``` Response: ``` { "payment_id": "pay_Omdaxo733MC34fLvCfYw", "client_secret": "pay_Omdaxo733MC34fLvCfYw_secret_ak2iLU1A5E6PK6XqqY6h", "session_token": [ { "wallet_name": "paze", "client_id": "HIDDEN", "client_name": "HIDDEN", "client_profile_id": "HIDDEN", "transaction_currency_code": "USD", "transaction_amount": "12.34", "email_address": "guest@example.com" } ] } ```
e36ea184ae6d1363fb1af55c790162df9f8b451c
Session Request Paze: ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "payment_id": "pay_Omdaxo733MC34fLvCfYw", "wallets": [], "client_secret": "pay_Omdaxo733MC34fLvCfYw_secret_ak2iLU1A5E6PK6XqqY6h" }' ``` Response: ``` { "payment_id": "pay_Omdaxo733MC34fLvCfYw", "client_secret": "pay_Omdaxo733MC34fLvCfYw_secret_ak2iLU1A5E6PK6XqqY6h", "session_token": [ { "wallet_name": "paze", "client_id": "HIDDEN", "client_name": "HIDDEN", "client_profile_id": "HIDDEN", "transaction_currency_code": "USD", "transaction_amount": "12.34", "email_address": "guest@example.com" } ] } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/payments.rs", "crates/hyperswitch_domain_models/src/router_request_types.rs", "crates/router/src/core/payments/flows/session_flow.rs", "crates/router/src/core/payments/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6425
Bug: fix(payment_methods): fix merchant payment method list to retain a mca based on connector_name and mca_id Earlier a connector was occurring twice while doing a session token call for wallets. This PR fixes merchant payment method list to retain a mca based on connector_name and mca_id. So that with every distinct mca_id the connector is listed just once for wallets.
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 84106a87d9b..d5255b5e8c5 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -1217,12 +1217,14 @@ pub struct ResponsePaymentMethodIntermediate { pub card_networks: Option<Vec<api_enums::CardNetwork>>, pub payment_method: api_enums::PaymentMethod, pub connector: String, + pub merchant_connector_id: String, } impl ResponsePaymentMethodIntermediate { pub fn new( pm_type: RequestPaymentMethodTypes, connector: String, + merchant_connector_id: String, pm: api_enums::PaymentMethod, ) -> Self { Self { @@ -1231,6 +1233,7 @@ impl ResponsePaymentMethodIntermediate { card_networks: pm_type.card_networks, payment_method: pm, connector, + merchant_connector_id, } } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 8419a600f39..b664088a415 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2980,6 +2980,7 @@ pub async fn list_payment_methods( api_enums::PaymentMethodType::ApplePay, api_enums::PaymentMethodType::Klarna, api_enums::PaymentMethodType::Paypal, + api_enums::PaymentMethodType::SamsungPay, ]); let mut chosen = Vec::<api::SessionConnectorData>::new(); @@ -3031,6 +3032,15 @@ pub async fn list_payment_methods( .connector .connector_name .to_string() + && first_routable_connector + .connector + .merchant_connector_id + .as_ref() + .map(|merchant_connector_id| { + *merchant_connector_id.get_string_repr() + == intermediate.merchant_connector_id + }) + .unwrap_or_default() } else { false } @@ -4068,6 +4078,7 @@ pub async fn filter_payment_methods( let response_pm_type = ResponsePaymentMethodIntermediate::new( payment_method_object, connector.clone(), + mca_id.get_string_repr().to_string(), payment_method, ); resp.push(response_pm_type); diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index fd45c475b6d..749ec52be24 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -5298,7 +5298,10 @@ where let routing_choice = choice .first() .ok_or(errors::ApiErrorResponse::InternalServerError)?; - if connector_data.connector.connector_name == routing_choice.connector.connector_name { + 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); } }
2024-10-23T09:37:30Z
## Description Earlier a connector was occurring twice while doing a session token call for wallets. This PR fixes merchant payment method list to retain a mca based on connector_name and mca_id. So that with every distinct mca_id the connector is listed just once for wallets. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? - Create a MA and an MCA(with wallets enabled) - Create an payment_intent ``` Intent Response { "payment_id": "pay_NHWegNguTfDH9hxuVj1m", "merchant_id": "merchant_1729514766", "status": "requires_payment_method", "amount": 8500, "net_amount": 8500, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_NHWegNguTfDH9hxuVj1m_secret_YgCdjC1ZMbdqGBmOOoTP", "created": "2024-10-21T13:11:49.384Z", "currency": "USD", "customer_id": "CustomerX777", "customer": { "id": "CustomerX777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "CustomerX777", "created_at": 1729516309, "expires": 1729519909, "secret": "epk_f7a7e71ac7b246b490d5cc31cb55e5d4" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_M3DqjrGVffJASyys4npr", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-21T13:26:49.384Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-21T13:11:49.418Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` - Do a PML call, for the wallets the mca should be listed once for the wallets that support session token flow ``` Merchant PML response { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "paypal", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "stripe" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "stripe" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": {}, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "samsung_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "stripe", "stripe" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "apple_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "stripe" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": {}, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "new_mandate", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } ``` - Create a MA and 2 same MCA - Create a payment_intent - Create a session token, only one google_pay will appear ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-client-platform: ios' \ --header 'api-key: pk_dev_385274838f7c4d66b6571c32756827d6' \ --data '{ "payment_id": "pay_NUmAgcew9X7W8yyBBsIK", "wallets":[], "client_secret": "pay_NUmAgcew9X7W8yyBBsIK_secret_DdDRx8PnhQznkCnVfY99" }' ``` ``` { "payment_id": "pay_NUmAgcew9X7W8yyBBsIK", "client_secret": "pay_NUmAgcew9X7W8yyBBsIK_secret_DdDRx8PnhQznkCnVfY99", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "S7" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "85.00" }, "delayed_session_token": false, "connector": "stripe", "sdk_next_action": { "next_action": "confirm" }, "secrets": null } ] } ```
4ef48c39b3ed7c1fcda9c850da766a0bdb701335
- Create a MA and an MCA(with wallets enabled) - Create an payment_intent ``` Intent Response { "payment_id": "pay_NHWegNguTfDH9hxuVj1m", "merchant_id": "merchant_1729514766", "status": "requires_payment_method", "amount": 8500, "net_amount": 8500, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_NHWegNguTfDH9hxuVj1m_secret_YgCdjC1ZMbdqGBmOOoTP", "created": "2024-10-21T13:11:49.384Z", "currency": "USD", "customer_id": "CustomerX777", "customer": { "id": "CustomerX777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "CustomerX777", "created_at": 1729516309, "expires": 1729519909, "secret": "epk_f7a7e71ac7b246b490d5cc31cb55e5d4" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_M3DqjrGVffJASyys4npr", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-21T13:26:49.384Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-21T13:11:49.418Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` - Do a PML call, for the wallets the mca should be listed once for the wallets that support session token flow ``` Merchant PML response { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "paypal", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "stripe" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "stripe" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": {}, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "samsung_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "stripe", "stripe" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "apple_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "stripe" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": {}, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "new_mandate", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } ``` - Create a MA and 2 same MCA - Create a payment_intent - Create a session token, only one google_pay will appear ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-client-platform: ios' \ --header 'api-key: pk_dev_385274838f7c4d66b6571c32756827d6' \ --data '{ "payment_id": "pay_NUmAgcew9X7W8yyBBsIK", "wallets":[], "client_secret": "pay_NUmAgcew9X7W8yyBBsIK_secret_DdDRx8PnhQznkCnVfY99" }' ``` ``` { "payment_id": "pay_NUmAgcew9X7W8yyBBsIK", "client_secret": "pay_NUmAgcew9X7W8yyBBsIK_secret_DdDRx8PnhQznkCnVfY99", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "S7" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "85.00" }, "delayed_session_token": false, "connector": "stripe", "sdk_next_action": { "next_action": "confirm" }, "secrets": null } ] } ```
[ "crates/api_models/src/payment_methods.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payments.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6406
Bug: feat(analytics): remove additional filters from PaymentIntentFilters hotfix -Additional filters are added to PaymentIntentFilters as new analytics APIs are expected to be calculated from `Sessionizer Payment Intents` table. - Existing metrics on current dashboard are breaking due to these new filters as the fields are not present in the `Payment Intents` table. The following additional filters from PaymentIntentFilters should be removed - connector - authentication_type - payment_method - payment_method_type - card_network - merchant_id - card_last_4 - card_issuer - error_reason
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index e04c3b7bd9e..af46baed23e 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -371,15 +371,6 @@ pub async fn get_filters( PaymentIntentDimensions::PaymentIntentStatus => fil.status.map(|i| i.as_ref().to_string()), PaymentIntentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), PaymentIntentDimensions::ProfileId => fil.profile_id, - PaymentIntentDimensions::Connector => fil.connector, - PaymentIntentDimensions::AuthType => fil.authentication_type.map(|i| i.as_ref().to_string()), - PaymentIntentDimensions::PaymentMethod => fil.payment_method, - PaymentIntentDimensions::PaymentMethodType => fil.payment_method_type, - PaymentIntentDimensions::CardNetwork => fil.card_network, - PaymentIntentDimensions::MerchantId => fil.merchant_id, - PaymentIntentDimensions::CardLast4 => fil.card_last_4, - PaymentIntentDimensions::CardIssuer => fil.card_issuer, - PaymentIntentDimensions::ErrorReason => fil.error_reason, }) .collect::<Vec<String>>(); res.query_data.push(PaymentIntentFilterValue { diff --git a/crates/analytics/src/payment_intents/filters.rs b/crates/analytics/src/payment_intents/filters.rs index 25d43e76f03..e81b050214c 100644 --- a/crates/analytics/src/payment_intents/filters.rs +++ b/crates/analytics/src/payment_intents/filters.rs @@ -1,6 +1,6 @@ use api_models::analytics::{payment_intents::PaymentIntentDimensions, Granularity, TimeRange}; use common_utils::errors::ReportSwitchExt; -use diesel_models::enums::{AuthenticationType, Currency, IntentStatus}; +use diesel_models::enums::{Currency, IntentStatus}; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -54,13 +54,4 @@ pub struct PaymentIntentFilterRow { pub status: Option<DBEnumWrapper<IntentStatus>>, pub currency: Option<DBEnumWrapper<Currency>>, pub profile_id: Option<String>, - pub connector: Option<String>, - pub authentication_type: Option<DBEnumWrapper<AuthenticationType>>, - pub payment_method: Option<String>, - pub payment_method_type: Option<String>, - pub card_network: Option<String>, - pub merchant_id: Option<String>, - pub card_last_4: Option<String>, - pub card_issuer: Option<String>, - pub error_reason: Option<String>, } diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs index 8ee9d24b5a0..e9d7f244306 100644 --- a/crates/analytics/src/payment_intents/metrics.rs +++ b/crates/analytics/src/payment_intents/metrics.rs @@ -34,15 +34,6 @@ pub struct PaymentIntentMetricRow { pub status: Option<DBEnumWrapper<storage_enums::IntentStatus>>, pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub profile_id: Option<String>, - pub connector: Option<String>, - pub authentication_type: Option<DBEnumWrapper<storage_enums::AuthenticationType>>, - pub payment_method: Option<String>, - pub payment_method_type: Option<String>, - pub card_network: Option<String>, - pub merchant_id: Option<String>, - pub card_last_4: Option<String>, - pub card_issuer: Option<String>, - pub error_reason: Option<String>, pub first_attempt: Option<i64>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, diff --git a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs index b301a9b9b23..4632cbe9f37 100644 --- a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs +++ b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs @@ -101,15 +101,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs index 07b1bfcf69f..14e168b3523 100644 --- a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs +++ b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs @@ -114,15 +114,6 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs index 7475a75bb53..644bf35a723 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs @@ -101,15 +101,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs index 506965375f5..e7772245063 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs @@ -128,15 +128,6 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs index 0b55c101a7c..eed6bf85a2c 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs @@ -113,15 +113,6 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs index 8c340d0b2d6..bd1f8bbbcd9 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs @@ -114,15 +114,6 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs index 8105a4c82a4..6d36aca5172 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs @@ -122,15 +122,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs index 0b28cb5366d..bf97e4c41ef 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs @@ -111,15 +111,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs index 20ef8be6277..cea5b2fa465 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs @@ -106,15 +106,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs index 8468911f7bb..b23fcafdee0 100644 --- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs @@ -122,15 +122,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs index a19bdec518c..4fe5f3a26f5 100644 --- a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs @@ -111,15 +111,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs index f5539abd9f5..e98efa9f6ab 100644 --- a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs @@ -106,15 +106,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/types.rs b/crates/analytics/src/payment_intents/types.rs index 1a9a2f2ed65..03f2a196c20 100644 --- a/crates/analytics/src/payment_intents/types.rs +++ b/crates/analytics/src/payment_intents/types.rs @@ -30,63 +30,6 @@ where .add_filter_in_range_clause(PaymentIntentDimensions::ProfileId, &self.profile_id) .attach_printable("Error adding profile id filter")?; } - if !self.connector.is_empty() { - builder - .add_filter_in_range_clause(PaymentIntentDimensions::Connector, &self.connector) - .attach_printable("Error adding connector filter")?; - } - if !self.auth_type.is_empty() { - builder - .add_filter_in_range_clause(PaymentIntentDimensions::AuthType, &self.auth_type) - .attach_printable("Error adding auth type filter")?; - } - if !self.payment_method.is_empty() { - builder - .add_filter_in_range_clause( - PaymentIntentDimensions::PaymentMethod, - &self.payment_method, - ) - .attach_printable("Error adding payment method filter")?; - } - if !self.payment_method_type.is_empty() { - builder - .add_filter_in_range_clause( - PaymentIntentDimensions::PaymentMethodType, - &self.payment_method_type, - ) - .attach_printable("Error adding payment method type filter")?; - } - if !self.card_network.is_empty() { - builder - .add_filter_in_range_clause( - PaymentIntentDimensions::CardNetwork, - &self.card_network, - ) - .attach_printable("Error adding card network filter")?; - } - if !self.merchant_id.is_empty() { - builder - .add_filter_in_range_clause(PaymentIntentDimensions::MerchantId, &self.merchant_id) - .attach_printable("Error adding merchant id filter")?; - } - if !self.card_last_4.is_empty() { - builder - .add_filter_in_range_clause(PaymentIntentDimensions::CardLast4, &self.card_last_4) - .attach_printable("Error adding card last 4 filter")?; - } - if !self.card_issuer.is_empty() { - builder - .add_filter_in_range_clause(PaymentIntentDimensions::CardIssuer, &self.card_issuer) - .attach_printable("Error adding card issuer filter")?; - } - if !self.error_reason.is_empty() { - builder - .add_filter_in_range_clause( - PaymentIntentDimensions::ErrorReason, - &self.error_reason, - ) - .attach_printable("Error adding error reason filter")?; - } Ok(()) } } diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index ae72bbeffea..89eb2ee0bde 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -604,45 +604,6 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; - let connector: Option<String> = row.try_get("connector").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = - row.try_get("authentication_type").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let payment_method: Option<String> = - row.try_get("payment_method").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let payment_method_type: Option<String> = - row.try_get("payment_method_type").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -666,15 +627,6 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe status, currency, profile_id, - connector, - authentication_type, - payment_method, - payment_method_type, - card_network, - merchant_id, - card_last_4, - card_issuer, - error_reason, first_attempt, total, count, @@ -700,58 +652,10 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFi ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; - let connector: Option<String> = row.try_get("connector").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = - row.try_get("authentication_type").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let payment_method: Option<String> = - row.try_get("payment_method").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let payment_method_type: Option<String> = - row.try_get("payment_method_type").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; Ok(Self { status, currency, profile_id, - connector, - authentication_type, - payment_method, - payment_method_type, - card_network, - merchant_id, - card_last_4, - card_issuer, - error_reason, }) } } diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index fc21bf09819..435e95451fe 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -35,12 +35,6 @@ pub fn get_payment_intent_dimensions() -> Vec<NameDescription> { PaymentIntentDimensions::PaymentIntentStatus, PaymentIntentDimensions::Currency, PaymentIntentDimensions::ProfileId, - PaymentIntentDimensions::Connector, - PaymentIntentDimensions::AuthType, - PaymentIntentDimensions::PaymentMethod, - PaymentIntentDimensions::PaymentMethodType, - PaymentIntentDimensions::CardNetwork, - PaymentIntentDimensions::MerchantId, ] .into_iter() .map(Into::into) diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs index 41f11c19ef8..d018437ae8c 100644 --- a/crates/api_models/src/analytics/payment_intents.rs +++ b/crates/api_models/src/analytics/payment_intents.rs @@ -6,9 +6,7 @@ use std::{ use common_utils::id_type; use super::{NameDescription, TimeRange}; -use crate::enums::{ - AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType, -}; +use crate::enums::{Currency, IntentStatus}; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct PaymentIntentFilters { @@ -18,24 +16,6 @@ pub struct PaymentIntentFilters { pub currency: Vec<Currency>, #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, - #[serde(default)] - pub connector: Vec<Connector>, - #[serde(default)] - pub auth_type: Vec<AuthenticationType>, - #[serde(default)] - pub payment_method: Vec<PaymentMethod>, - #[serde(default)] - pub payment_method_type: Vec<PaymentMethodType>, - #[serde(default)] - pub card_network: Vec<String>, - #[serde(default)] - pub merchant_id: Vec<id_type::MerchantId>, - #[serde(default)] - pub card_last_4: Vec<String>, - #[serde(default)] - pub card_issuer: Vec<String>, - #[serde(default)] - pub error_reason: Vec<String>, } #[derive( @@ -60,15 +40,6 @@ pub enum PaymentIntentDimensions { PaymentIntentStatus, Currency, ProfileId, - Connector, - AuthType, - PaymentMethod, - PaymentMethodType, - CardNetwork, - MerchantId, - CardLast4, - CardIssuer, - ErrorReason, } #[derive( @@ -138,15 +109,6 @@ pub struct PaymentIntentMetricsBucketIdentifier { pub status: Option<IntentStatus>, pub currency: Option<Currency>, pub profile_id: Option<String>, - pub connector: Option<String>, - pub auth_type: Option<AuthenticationType>, - pub payment_method: Option<String>, - pub payment_method_type: Option<String>, - pub card_network: Option<String>, - pub merchant_id: Option<String>, - pub card_last_4: Option<String>, - pub card_issuer: Option<String>, - pub error_reason: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] @@ -160,30 +122,12 @@ impl PaymentIntentMetricsBucketIdentifier { status: Option<IntentStatus>, currency: Option<Currency>, profile_id: Option<String>, - connector: Option<String>, - auth_type: Option<AuthenticationType>, - payment_method: Option<String>, - payment_method_type: Option<String>, - card_network: Option<String>, - merchant_id: Option<String>, - card_last_4: Option<String>, - card_issuer: Option<String>, - error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { status, currency, profile_id, - connector, - auth_type, - payment_method, - payment_method_type, - card_network, - merchant_id, - card_last_4, - card_issuer, - error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -195,15 +139,6 @@ impl Hash for PaymentIntentMetricsBucketIdentifier { self.status.map(|i| i.to_string()).hash(state); self.currency.hash(state); self.profile_id.hash(state); - self.connector.hash(state); - self.auth_type.map(|i| i.to_string()).hash(state); - self.payment_method.hash(state); - self.payment_method_type.hash(state); - self.card_network.hash(state); - self.merchant_id.hash(state); - self.card_last_4.hash(state); - self.card_issuer.hash(state); - self.error_reason.hash(state); self.time_bucket.hash(state); } }
2024-10-23T07:54:30Z
## Description <!-- Describe your changes in detail --> Hotfix PR for: [https://github.com/juspay/hyperswitch/pull/6403](https://github.com/juspay/hyperswitch/pull/6403) - Additional filters are added to `PaymentIntentFilters` as new analytics APIs are expected to be calculated from `Sessionizer Payment Intents` table. - Existing metrics on current dashboard are breaking due to these new filters as the fields are not present in the Payment Intents table. Removed the following additional filters from `PaymentIntentFilters` - connector - authentication_type - payment_method - payment_method_type - card_network - merchant_id - card_last_4 - card_issuer - error_reason ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes: [https://github.com/juspay/hyperswitch/issues/6404](https://github.com/juspay/hyperswitch/issues/6406) Dashboard is raising error (status_code - 500) when payment intent based analytics APIs ae being hit, due to filter fields not present in the payment intents table. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Added filters of connector, payment_method, etc on the dashboard and the payments v2 APIs should not return 500 error. - Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36' \ --header 'api-key: snd_ug3Xjm7pNJ6u3SeC5jQCApLIPr6NdDppvEKht091zd62EJJ0pWF6KziALr0yQEuF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTc0ODc1Mywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.-NHlfMrAjUDwjMpCo9PAn86koRkkPMBygNfCTh2jiTw' \ --header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-14T18:30:00Z", "endTime": "2024-10-22T15:24:00Z" }, "groupByNames": [ "currency" ], "filters": { "connector": [ "stripe_test" ] }, "timeSeries": { "granularity": "G_ONEDAY" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "successful_smart_retries", "total_smart_retries", "smart_retried_amount" ] } ]' ``` - Response: ```bash { "queryData": [ { "successful_smart_retries": 1, "total_smart_retries": 1, "smart_retried_amount": 6540, "smart_retried_amount_without_smart_retries": 0, "payment_intent_count": null, "successful_payments": null, "successful_payments_without_smart_retries": null, "total_payments": null, "payments_success_rate": null, "payments_success_rate_without_smart_retries": null, "payment_processed_amount": 0, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_count_without_smart_retries": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_without_smart_retries": null, "status": null, "currency": "USD", "profile_id": null, "time_range": { "start_time": "2024-10-18T00:00:00.000Z", "end_time": "2024-10-18T23:00:00.000Z" }, "time_bucket": "2024-10-18 00:00:00" } ], "metaData": [ { "total_success_rate": null, "total_success_rate_without_smart_retries": null, "total_smart_retried_amount": 6540, "total_smart_retried_amount_without_smart_retries": 0, "total_payment_processed_amount": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0 } ] } ```
76dda56642ceef8cc56104a715b76c4c1663da28
Added filters of connector, payment_method, etc on the dashboard and the payments v2 APIs should not return 500 error. - Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36' \ --header 'api-key: snd_ug3Xjm7pNJ6u3SeC5jQCApLIPr6NdDppvEKht091zd62EJJ0pWF6KziALr0yQEuF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTc0ODc1Mywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.-NHlfMrAjUDwjMpCo9PAn86koRkkPMBygNfCTh2jiTw' \ --header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-14T18:30:00Z", "endTime": "2024-10-22T15:24:00Z" }, "groupByNames": [ "currency" ], "filters": { "connector": [ "stripe_test" ] }, "timeSeries": { "granularity": "G_ONEDAY" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "successful_smart_retries", "total_smart_retries", "smart_retried_amount" ] } ]' ``` - Response: ```bash { "queryData": [ { "successful_smart_retries": 1, "total_smart_retries": 1, "smart_retried_amount": 6540, "smart_retried_amount_without_smart_retries": 0, "payment_intent_count": null, "successful_payments": null, "successful_payments_without_smart_retries": null, "total_payments": null, "payments_success_rate": null, "payments_success_rate_without_smart_retries": null, "payment_processed_amount": 0, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_count_without_smart_retries": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_without_smart_retries": null, "status": null, "currency": "USD", "profile_id": null, "time_range": { "start_time": "2024-10-18T00:00:00.000Z", "end_time": "2024-10-18T23:00:00.000Z" }, "time_bucket": "2024-10-18 00:00:00" } ], "metaData": [ { "total_success_rate": null, "total_success_rate_without_smart_retries": null, "total_smart_retried_amount": 6540, "total_smart_retried_amount_without_smart_retries": 0, "total_payment_processed_amount": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0 } ] } ```
[ "crates/analytics/src/payment_intents/core.rs", "crates/analytics/src/payment_intents/filters.rs", "crates/analytics/src/payment_intents/metrics.rs", "crates/analytics/src/payment_intents/metrics/payment_intent_count.rs", "crates/analytics/src/payment_intents/metrics/payments_success_rate.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs", "crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs", "crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs", "crates/analytics/src/payment_intents/metrics/total_smart_retries.rs", "crates/analytics/src/payment_intents/types.rs", "crates/analytics/src/sqlx.rs", "crates/analytics/src/utils.rs", "crates/api_models/src/analytics/payment_intents.rs" ]
juspay/hyperswitch
juspay__hyperswitch-5990
Bug: [FIX] Remove ToSchema from RefundAggregateResponse and exclude it from OpenAPI documentation ### Feature Description The RefundAggregateResponse type used by the [/refunds/aggregate](https://github.com/juspay/hyperswitch/blob/37925626e6446900f1d16e0e5f184ee472d4be3e/crates/router/src/routes/app.rs#L1004) API is currently annotated with ToSchema, which generates OpenAPI schema documentation for it. However, since this API is internal and should not be exposed to external users, the schema should not be generated or included in the OpenAPI documentation. Current Behavior: - The `RefundAggregateResponse` struct is annotated with ToSchema, which automatically generates OpenAPI documentation. - This results in the exposure of internal API details that should remain hidden from external consumers. Expected Behavior: - Remove the `ToSchema` derive macro from the RefundAggregateResponse struct. - Ensure that this struct and its associated API are excluded from OpenAPI documentation generation. ### Possible Implementation The Api [refunds/aggregate](https://github.com/juspay/hyperswitch/blob/37925626e6446900f1d16e0e5f184ee472d4be3e/crates/router/src/core/refunds.rs#L1098) returns `RefundAggregateResponse` The following code should be modified to remove ToSchema and update the OpenAPI documentation accordingly: ``` #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RefundAggregateResponse { /// The list of refund status with their count pub status_with_count: HashMap<enums::RefundStatus, i64>, } ``` Tasks: - Remove the ToSchema derive macro from the RefundAggregateResponse struct. - Remove any references to RefundAggregateResponse from openapi.rs to ensure it is not documented. - Test to verify that this type is no longer included in the OpenAPI schema. Additional Context: Since the `/refunds/aggregate` API is for internal use only, removing the OpenAPI schema ensures that this internal API remains undocumented for merchants. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 72afa1dc3da..63c01329dfe 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -18158,22 +18158,6 @@ } } }, - "RefundAggregateResponse": { - "type": "object", - "required": [ - "status_with_count" - ], - "properties": { - "status_with_count": { - "type": "object", - "description": "The list of refund status with their count", - "additionalProperties": { - "type": "integer", - "format": "int64" - } - } - } - }, "RefundErrorDetails": { "type": "object", "required": [ diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index f42eb8095b4..ac5e5cb4618 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -346,7 +346,7 @@ pub struct RefundListFilters { pub refund_status: Vec<enums::RefundStatus>, } -#[derive(Clone, Debug, serde::Serialize, ToSchema)] +#[derive(Clone, Debug, serde::Serialize)] pub struct RefundAggregateResponse { /// The list of refund status with their count pub status_with_count: HashMap<enums::RefundStatus, i64>, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 28a7f44c7a8..754ec433b77 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -492,7 +492,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodCollectLinkResponse, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, - api_models::refunds::RefundAggregateResponse, api_models::payments::AmountFilter, api_models::mandates::MandateRevokedResponse, api_models::mandates::MandateResponse, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 7c961b2b2b2..84f320778fe 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -432,7 +432,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodCollectLinkResponse, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, - api_models::refunds::RefundAggregateResponse, api_models::payments::AmountFilter, api_models::mandates::MandateRevokedResponse, api_models::mandates::MandateResponse,
2024-10-22T20:13:07Z
## Description <!-- Describe your changes in detail --> Removed all the openapi references to `RefundAggregateResponse`. 1. Removed `ToSchema` trait for `RefundAggregateResponse`. 2. Removed references from `openapi` and `openapi_v2` to `RefundAggregateResponse`. 3. Generated new `openapi_spec` file based on the above changes. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #5990 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested manually. The references of `RefundAggregateResponse` is removed in openapi generated json file after the modification. <img width="871" alt="image" src="https://github.com/user-attachments/assets/70f23a10-37e9-420e-8031-f41e6b5f11da"> <img width="1015" alt="image" src="https://github.com/user-attachments/assets/614b9c86-2735-445c-8aa0-d54248f944a5">
aee11c560e427195a0d321dff19c0d33ec60ba64
Tested manually. The references of `RefundAggregateResponse` is removed in openapi generated json file after the modification. <img width="871" alt="image" src="https://github.com/user-attachments/assets/70f23a10-37e9-420e-8031-f41e6b5f11da"> <img width="1015" alt="image" src="https://github.com/user-attachments/assets/614b9c86-2735-445c-8aa0-d54248f944a5">
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/refunds.rs", "crates/openapi/src/openapi.rs", "crates/openapi/src/openapi_v2.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6404
Bug: feat(analytics): remove additional filters from PaymentIntentFilters -Additional filters are added to PaymentIntentFilters as new analytics APIs are expected to be calculated from `Sessionizer Payment Intents` table. - Existing metrics on current dashboard are breaking due to these new filters as the fields are not present in the `Payment Intents` table. The following additional filters from PaymentIntentFilters should be removed - connector - authentication_type - payment_method - payment_method_type - card_network - merchant_id - card_last_4 - card_issuer - error_reason
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index e04c3b7bd9e..af46baed23e 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -371,15 +371,6 @@ pub async fn get_filters( PaymentIntentDimensions::PaymentIntentStatus => fil.status.map(|i| i.as_ref().to_string()), PaymentIntentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), PaymentIntentDimensions::ProfileId => fil.profile_id, - PaymentIntentDimensions::Connector => fil.connector, - PaymentIntentDimensions::AuthType => fil.authentication_type.map(|i| i.as_ref().to_string()), - PaymentIntentDimensions::PaymentMethod => fil.payment_method, - PaymentIntentDimensions::PaymentMethodType => fil.payment_method_type, - PaymentIntentDimensions::CardNetwork => fil.card_network, - PaymentIntentDimensions::MerchantId => fil.merchant_id, - PaymentIntentDimensions::CardLast4 => fil.card_last_4, - PaymentIntentDimensions::CardIssuer => fil.card_issuer, - PaymentIntentDimensions::ErrorReason => fil.error_reason, }) .collect::<Vec<String>>(); res.query_data.push(PaymentIntentFilterValue { diff --git a/crates/analytics/src/payment_intents/filters.rs b/crates/analytics/src/payment_intents/filters.rs index 25d43e76f03..e81b050214c 100644 --- a/crates/analytics/src/payment_intents/filters.rs +++ b/crates/analytics/src/payment_intents/filters.rs @@ -1,6 +1,6 @@ use api_models::analytics::{payment_intents::PaymentIntentDimensions, Granularity, TimeRange}; use common_utils::errors::ReportSwitchExt; -use diesel_models::enums::{AuthenticationType, Currency, IntentStatus}; +use diesel_models::enums::{Currency, IntentStatus}; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -54,13 +54,4 @@ pub struct PaymentIntentFilterRow { pub status: Option<DBEnumWrapper<IntentStatus>>, pub currency: Option<DBEnumWrapper<Currency>>, pub profile_id: Option<String>, - pub connector: Option<String>, - pub authentication_type: Option<DBEnumWrapper<AuthenticationType>>, - pub payment_method: Option<String>, - pub payment_method_type: Option<String>, - pub card_network: Option<String>, - pub merchant_id: Option<String>, - pub card_last_4: Option<String>, - pub card_issuer: Option<String>, - pub error_reason: Option<String>, } diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs index 8ee9d24b5a0..e9d7f244306 100644 --- a/crates/analytics/src/payment_intents/metrics.rs +++ b/crates/analytics/src/payment_intents/metrics.rs @@ -34,15 +34,6 @@ pub struct PaymentIntentMetricRow { pub status: Option<DBEnumWrapper<storage_enums::IntentStatus>>, pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub profile_id: Option<String>, - pub connector: Option<String>, - pub authentication_type: Option<DBEnumWrapper<storage_enums::AuthenticationType>>, - pub payment_method: Option<String>, - pub payment_method_type: Option<String>, - pub card_network: Option<String>, - pub merchant_id: Option<String>, - pub card_last_4: Option<String>, - pub card_issuer: Option<String>, - pub error_reason: Option<String>, pub first_attempt: Option<i64>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, diff --git a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs index b301a9b9b23..4632cbe9f37 100644 --- a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs +++ b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs @@ -101,15 +101,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs index 07b1bfcf69f..14e168b3523 100644 --- a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs +++ b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs @@ -114,15 +114,6 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs index 7475a75bb53..644bf35a723 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs @@ -101,15 +101,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs index 506965375f5..e7772245063 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs @@ -128,15 +128,6 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs index 0b55c101a7c..eed6bf85a2c 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs @@ -113,15 +113,6 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs index 8c340d0b2d6..bd1f8bbbcd9 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs @@ -114,15 +114,6 @@ where None, i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs index 8105a4c82a4..6d36aca5172 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs @@ -122,15 +122,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs index 0b28cb5366d..bf97e4c41ef 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs @@ -111,15 +111,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs index 20ef8be6277..cea5b2fa465 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs @@ -106,15 +106,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs index 8468911f7bb..b23fcafdee0 100644 --- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs @@ -122,15 +122,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs index a19bdec518c..4fe5f3a26f5 100644 --- a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs @@ -111,15 +111,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs index f5539abd9f5..e98efa9f6ab 100644 --- a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs @@ -106,15 +106,6 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), - i.connector.clone(), - i.authentication_type.as_ref().map(|i| i.0), - i.payment_method.clone(), - i.payment_method_type.clone(), - i.card_network.clone(), - i.merchant_id.clone(), - i.card_last_4.clone(), - i.card_issuer.clone(), - i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/types.rs b/crates/analytics/src/payment_intents/types.rs index 1a9a2f2ed65..03f2a196c20 100644 --- a/crates/analytics/src/payment_intents/types.rs +++ b/crates/analytics/src/payment_intents/types.rs @@ -30,63 +30,6 @@ where .add_filter_in_range_clause(PaymentIntentDimensions::ProfileId, &self.profile_id) .attach_printable("Error adding profile id filter")?; } - if !self.connector.is_empty() { - builder - .add_filter_in_range_clause(PaymentIntentDimensions::Connector, &self.connector) - .attach_printable("Error adding connector filter")?; - } - if !self.auth_type.is_empty() { - builder - .add_filter_in_range_clause(PaymentIntentDimensions::AuthType, &self.auth_type) - .attach_printable("Error adding auth type filter")?; - } - if !self.payment_method.is_empty() { - builder - .add_filter_in_range_clause( - PaymentIntentDimensions::PaymentMethod, - &self.payment_method, - ) - .attach_printable("Error adding payment method filter")?; - } - if !self.payment_method_type.is_empty() { - builder - .add_filter_in_range_clause( - PaymentIntentDimensions::PaymentMethodType, - &self.payment_method_type, - ) - .attach_printable("Error adding payment method type filter")?; - } - if !self.card_network.is_empty() { - builder - .add_filter_in_range_clause( - PaymentIntentDimensions::CardNetwork, - &self.card_network, - ) - .attach_printable("Error adding card network filter")?; - } - if !self.merchant_id.is_empty() { - builder - .add_filter_in_range_clause(PaymentIntentDimensions::MerchantId, &self.merchant_id) - .attach_printable("Error adding merchant id filter")?; - } - if !self.card_last_4.is_empty() { - builder - .add_filter_in_range_clause(PaymentIntentDimensions::CardLast4, &self.card_last_4) - .attach_printable("Error adding card last 4 filter")?; - } - if !self.card_issuer.is_empty() { - builder - .add_filter_in_range_clause(PaymentIntentDimensions::CardIssuer, &self.card_issuer) - .attach_printable("Error adding card issuer filter")?; - } - if !self.error_reason.is_empty() { - builder - .add_filter_in_range_clause( - PaymentIntentDimensions::ErrorReason, - &self.error_reason, - ) - .attach_printable("Error adding error reason filter")?; - } Ok(()) } } diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index ae72bbeffea..89eb2ee0bde 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -604,45 +604,6 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; - let connector: Option<String> = row.try_get("connector").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = - row.try_get("authentication_type").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let payment_method: Option<String> = - row.try_get("payment_method").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let payment_method_type: Option<String> = - row.try_get("payment_method_type").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -666,15 +627,6 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe status, currency, profile_id, - connector, - authentication_type, - payment_method, - payment_method_type, - card_network, - merchant_id, - card_last_4, - card_issuer, - error_reason, first_attempt, total, count, @@ -700,58 +652,10 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFi ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; - let connector: Option<String> = row.try_get("connector").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = - row.try_get("authentication_type").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let payment_method: Option<String> = - row.try_get("payment_method").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let payment_method_type: Option<String> = - row.try_get("payment_method_type").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; - let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { - ColumnNotFound(_) => Ok(Default::default()), - e => Err(e), - })?; Ok(Self { status, currency, profile_id, - connector, - authentication_type, - payment_method, - payment_method_type, - card_network, - merchant_id, - card_last_4, - card_issuer, - error_reason, }) } } diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index fc21bf09819..435e95451fe 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -35,12 +35,6 @@ pub fn get_payment_intent_dimensions() -> Vec<NameDescription> { PaymentIntentDimensions::PaymentIntentStatus, PaymentIntentDimensions::Currency, PaymentIntentDimensions::ProfileId, - PaymentIntentDimensions::Connector, - PaymentIntentDimensions::AuthType, - PaymentIntentDimensions::PaymentMethod, - PaymentIntentDimensions::PaymentMethodType, - PaymentIntentDimensions::CardNetwork, - PaymentIntentDimensions::MerchantId, ] .into_iter() .map(Into::into) diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs index 41f11c19ef8..d018437ae8c 100644 --- a/crates/api_models/src/analytics/payment_intents.rs +++ b/crates/api_models/src/analytics/payment_intents.rs @@ -6,9 +6,7 @@ use std::{ use common_utils::id_type; use super::{NameDescription, TimeRange}; -use crate::enums::{ - AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType, -}; +use crate::enums::{Currency, IntentStatus}; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct PaymentIntentFilters { @@ -18,24 +16,6 @@ pub struct PaymentIntentFilters { pub currency: Vec<Currency>, #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, - #[serde(default)] - pub connector: Vec<Connector>, - #[serde(default)] - pub auth_type: Vec<AuthenticationType>, - #[serde(default)] - pub payment_method: Vec<PaymentMethod>, - #[serde(default)] - pub payment_method_type: Vec<PaymentMethodType>, - #[serde(default)] - pub card_network: Vec<String>, - #[serde(default)] - pub merchant_id: Vec<id_type::MerchantId>, - #[serde(default)] - pub card_last_4: Vec<String>, - #[serde(default)] - pub card_issuer: Vec<String>, - #[serde(default)] - pub error_reason: Vec<String>, } #[derive( @@ -60,15 +40,6 @@ pub enum PaymentIntentDimensions { PaymentIntentStatus, Currency, ProfileId, - Connector, - AuthType, - PaymentMethod, - PaymentMethodType, - CardNetwork, - MerchantId, - CardLast4, - CardIssuer, - ErrorReason, } #[derive( @@ -138,15 +109,6 @@ pub struct PaymentIntentMetricsBucketIdentifier { pub status: Option<IntentStatus>, pub currency: Option<Currency>, pub profile_id: Option<String>, - pub connector: Option<String>, - pub auth_type: Option<AuthenticationType>, - pub payment_method: Option<String>, - pub payment_method_type: Option<String>, - pub card_network: Option<String>, - pub merchant_id: Option<String>, - pub card_last_4: Option<String>, - pub card_issuer: Option<String>, - pub error_reason: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] @@ -160,30 +122,12 @@ impl PaymentIntentMetricsBucketIdentifier { status: Option<IntentStatus>, currency: Option<Currency>, profile_id: Option<String>, - connector: Option<String>, - auth_type: Option<AuthenticationType>, - payment_method: Option<String>, - payment_method_type: Option<String>, - card_network: Option<String>, - merchant_id: Option<String>, - card_last_4: Option<String>, - card_issuer: Option<String>, - error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { status, currency, profile_id, - connector, - auth_type, - payment_method, - payment_method_type, - card_network, - merchant_id, - card_last_4, - card_issuer, - error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -195,15 +139,6 @@ impl Hash for PaymentIntentMetricsBucketIdentifier { self.status.map(|i| i.to_string()).hash(state); self.currency.hash(state); self.profile_id.hash(state); - self.connector.hash(state); - self.auth_type.map(|i| i.to_string()).hash(state); - self.payment_method.hash(state); - self.payment_method_type.hash(state); - self.card_network.hash(state); - self.merchant_id.hash(state); - self.card_last_4.hash(state); - self.card_issuer.hash(state); - self.error_reason.hash(state); self.time_bucket.hash(state); } }
2024-10-22T18:22:21Z
## Description <!-- Describe your changes in detail --> Fix for this PR: [https://github.com/juspay/hyperswitch/pull/5870](https://github.com/juspay/hyperswitch/pull/5870) - Additional filters are added to `PaymentIntentFilters` as new analytics APIs are expected to be calculated from `Sessionizer Payment Intents` table. - Existing metrics on current dashboard are breaking due to these new filters as the fields are not present in the Payment Intents table. Removed the following additional filters from `PaymentIntentFilters` - connector - authentication_type - payment_method - payment_method_type - card_network - merchant_id - card_last_4 - card_issuer - error_reason ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Dashboard is raising error (status_code - 500) when payment intent based analytics APIs ae being hit, due to filter fields not present in the payment intents table. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Added filters of connector, payment_method, etc on the dashboard and the payments v2 APIs should not return 500 error. - Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36' \ --header 'api-key: snd_ug3Xjm7pNJ6u3SeC5jQCApLIPr6NdDppvEKht091zd62EJJ0pWF6KziALr0yQEuF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTc0ODc1Mywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.-NHlfMrAjUDwjMpCo9PAn86koRkkPMBygNfCTh2jiTw' \ --header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-14T18:30:00Z", "endTime": "2024-10-22T15:24:00Z" }, "groupByNames": [ "currency" ], "filters": { "connector": [ "stripe_test" ] }, "timeSeries": { "granularity": "G_ONEDAY" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "successful_smart_retries", "total_smart_retries", "smart_retried_amount" ] } ]' ``` - Response: ```bash { "queryData": [ { "successful_smart_retries": 1, "total_smart_retries": 1, "smart_retried_amount": 6540, "smart_retried_amount_without_smart_retries": 0, "payment_intent_count": null, "successful_payments": null, "successful_payments_without_smart_retries": null, "total_payments": null, "payments_success_rate": null, "payments_success_rate_without_smart_retries": null, "payment_processed_amount": 0, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_count_without_smart_retries": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_without_smart_retries": null, "status": null, "currency": "USD", "profile_id": null, "time_range": { "start_time": "2024-10-18T00:00:00.000Z", "end_time": "2024-10-18T23:00:00.000Z" }, "time_bucket": "2024-10-18 00:00:00" } ], "metaData": [ { "total_success_rate": null, "total_success_rate_without_smart_retries": null, "total_smart_retried_amount": 6540, "total_smart_retried_amount_without_smart_retries": 0, "total_payment_processed_amount": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0 } ] } ```
3d1a3cdc8f942a3dca2e6a200bf9200366bd62f1
Added filters of connector, payment_method, etc on the dashboard and the payments v2 APIs should not return 500 error. - Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36' \ --header 'api-key: snd_ug3Xjm7pNJ6u3SeC5jQCApLIPr6NdDppvEKht091zd62EJJ0pWF6KziALr0yQEuF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTc0ODc1Mywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.-NHlfMrAjUDwjMpCo9PAn86koRkkPMBygNfCTh2jiTw' \ --header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-14T18:30:00Z", "endTime": "2024-10-22T15:24:00Z" }, "groupByNames": [ "currency" ], "filters": { "connector": [ "stripe_test" ] }, "timeSeries": { "granularity": "G_ONEDAY" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "successful_smart_retries", "total_smart_retries", "smart_retried_amount" ] } ]' ``` - Response: ```bash { "queryData": [ { "successful_smart_retries": 1, "total_smart_retries": 1, "smart_retried_amount": 6540, "smart_retried_amount_without_smart_retries": 0, "payment_intent_count": null, "successful_payments": null, "successful_payments_without_smart_retries": null, "total_payments": null, "payments_success_rate": null, "payments_success_rate_without_smart_retries": null, "payment_processed_amount": 0, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_count_without_smart_retries": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_without_smart_retries": null, "status": null, "currency": "USD", "profile_id": null, "time_range": { "start_time": "2024-10-18T00:00:00.000Z", "end_time": "2024-10-18T23:00:00.000Z" }, "time_bucket": "2024-10-18 00:00:00" } ], "metaData": [ { "total_success_rate": null, "total_success_rate_without_smart_retries": null, "total_smart_retried_amount": 6540, "total_smart_retried_amount_without_smart_retries": 0, "total_payment_processed_amount": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0 } ] } ```
[ "crates/analytics/src/payment_intents/core.rs", "crates/analytics/src/payment_intents/filters.rs", "crates/analytics/src/payment_intents/metrics.rs", "crates/analytics/src/payment_intents/metrics/payment_intent_count.rs", "crates/analytics/src/payment_intents/metrics/payments_success_rate.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs", "crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs", "crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs", "crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs", "crates/analytics/src/payment_intents/metrics/total_smart_retries.rs", "crates/analytics/src/payment_intents/types.rs", "crates/analytics/src/sqlx.rs", "crates/analytics/src/utils.rs", "crates/api_models/src/analytics/payment_intents.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6399
Bug: chore: address Rust 1.82.0 clippy lints Address the clippy lints occurring due to new rust version 1.82.0 See https://github.com/juspay/hyperswitch/issues/3391 for more information.
diff --git a/add_connector.md b/add_connector.md index eda368db9c8..4d6e885b7ed 100644 --- a/add_connector.md +++ b/add_connector.md @@ -311,7 +311,7 @@ impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>> let payments_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data, - mandate_reference: None, + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index 1454be66c8b..b508596cbc0 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -132,8 +132,8 @@ impl<F,T> TryFrom<ResponseRouterData<F, {{project-name | downcase | pascal_case} status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/api_models/src/connector_onboarding.rs b/crates/api_models/src/connector_onboarding.rs index 2dca57d5953..e86f4a6f2fa 100644 --- a/crates/api_models/src/connector_onboarding.rs +++ b/crates/api_models/src/connector_onboarding.rs @@ -42,7 +42,7 @@ pub enum PayPalOnboardingStatus { MorePermissionsNeeded, EmailNotVerified, Success(PayPalOnboardingDone), - ConnectorIntegrated(admin::MerchantConnectorResponse), + ConnectorIntegrated(Box<admin::MerchantConnectorResponse>), } #[derive(serde::Serialize, Debug, Clone)] diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index a7be9703d38..237d165d572 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -19,7 +19,7 @@ use crate::{enums as api_enums, payment_methods::RequiredFieldInfo, payments}; #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] pub enum PayoutRequest { PayoutActionRequest(PayoutActionRequest), - PayoutCreateRequest(PayoutCreateRequest), + PayoutCreateRequest(Box<PayoutCreateRequest>), PayoutRetrieveRequest(PayoutRetrieveRequest), } diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index ce9b303066e..56a566d170a 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -229,16 +229,16 @@ pub struct OutgoingWebhook { #[serde(tag = "type", content = "object", rename_all = "snake_case")] pub enum OutgoingWebhookContent { #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")] - PaymentDetails(payments::PaymentsResponse), + PaymentDetails(Box<payments::PaymentsResponse>), #[schema(value_type = RefundResponse, title = "RefundResponse")] - RefundDetails(refunds::RefundResponse), + RefundDetails(Box<refunds::RefundResponse>), #[schema(value_type = DisputeResponse, title = "DisputeResponse")] DisputeDetails(Box<disputes::DisputeResponse>), #[schema(value_type = MandateResponse, title = "MandateResponse")] MandateDetails(Box<mandates::MandateResponse>), #[cfg(feature = "payouts")] #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")] - PayoutDetails(payouts::PayoutCreateResponse), + PayoutDetails(Box<payouts::PayoutCreateResponse>), } #[derive(Debug, Clone, Serialize)] diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs index d91e57a2b5d..0bfa1434f69 100644 --- a/crates/diesel_models/src/kv.rs +++ b/crates/diesel_models/src/kv.rs @@ -20,8 +20,8 @@ use crate::{ #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "db_op", content = "data")] pub enum DBOperation { - Insert { insertable: Insertable }, - Update { updatable: Updateable }, + Insert { insertable: Box<Insertable> }, + Update { updatable: Box<Updateable> }, } impl DBOperation { @@ -33,7 +33,7 @@ impl DBOperation { } pub fn table<'a>(&self) -> &'a str { match self { - Self::Insert { insertable } => match insertable { + Self::Insert { insertable } => match **insertable { Insertable::PaymentIntent(_) => "payment_intent", Insertable::PaymentAttempt(_) => "payment_attempt", Insertable::Refund(_) => "refund", @@ -45,7 +45,7 @@ impl DBOperation { Insertable::PaymentMethod(_) => "payment_method", Insertable::Mandate(_) => "mandate", }, - Self::Update { updatable } => match updatable { + Self::Update { updatable } => match **updatable { Updateable::PaymentIntentUpdate(_) => "payment_intent", Updateable::PaymentAttemptUpdate(_) => "payment_attempt", Updateable::RefundUpdate(_) => "refund", @@ -83,7 +83,7 @@ pub struct TypedSql { impl DBOperation { pub async fn execute(self, conn: &PgPooledConn) -> crate::StorageResult<DBResult> { Ok(match self { - Self::Insert { insertable } => match insertable { + Self::Insert { insertable } => match *insertable { Insertable::PaymentIntent(a) => { DBResult::PaymentIntent(Box::new(a.insert(conn).await?)) } @@ -107,7 +107,7 @@ impl DBOperation { } Insertable::Mandate(m) => DBResult::Mandate(Box::new(m.insert(conn).await?)), }, - Self::Update { updatable } => match updatable { + Self::Update { updatable } => match *updatable { Updateable::PaymentIntentUpdate(a) => { DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?)) } @@ -201,8 +201,8 @@ impl TypedSql { #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "table", content = "data")] pub enum Insertable { - PaymentIntent(PaymentIntentNew), - PaymentAttempt(PaymentAttemptNew), + PaymentIntent(Box<PaymentIntentNew>), + PaymentAttempt(Box<PaymentAttemptNew>), Refund(RefundNew), Address(Box<AddressNew>), Customer(CustomerNew), @@ -216,14 +216,14 @@ pub enum Insertable { #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "table", content = "data")] pub enum Updateable { - PaymentIntentUpdate(PaymentIntentUpdateMems), - PaymentAttemptUpdate(PaymentAttemptUpdateMems), + PaymentIntentUpdate(Box<PaymentIntentUpdateMems>), + PaymentAttemptUpdate(Box<PaymentAttemptUpdateMems>), RefundUpdate(RefundUpdateMems), CustomerUpdate(CustomerUpdateMems), AddressUpdate(Box<AddressUpdateMems>), PayoutsUpdate(PayoutsUpdateMems), PayoutAttemptUpdate(PayoutAttemptUpdateMems), - PaymentMethodUpdate(PaymentMethodUpdateMems), + PaymentMethodUpdate(Box<PaymentMethodUpdateMems>), MandateUpdate(MandateUpdateMems), } diff --git a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs index 4212f7168db..567f519d794 100644 --- a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs @@ -471,8 +471,8 @@ impl<F> TryFrom<ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, Pa }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(pg_response.id.to_string()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(pg_response.order_number.to_string()), @@ -491,8 +491,8 @@ impl<F> TryFrom<ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, Pa status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: Some( serde_json::to_value(BamboraMeta { three_d_session_data: response.three_d_session_data.expose(), @@ -541,8 +541,8 @@ impl<F> }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), @@ -586,8 +586,8 @@ impl<F> }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), @@ -621,8 +621,8 @@ impl<F> }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), @@ -656,8 +656,8 @@ impl<F> }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), diff --git a/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs b/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs index cc63e1ad7cc..798f28d1f0a 100644 --- a/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs @@ -284,8 +284,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsRe }; let payments_response = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.handle.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.handle), diff --git a/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs index 1c42bfd08c8..333398dfa90 100644 --- a/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs @@ -159,8 +159,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BitpayPaymentsResponse, T, PaymentsResp status: enums::AttemptStatus::from(attempt_status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: connector_id, - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item diff --git a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs index 49493127621..2a282414f4b 100644 --- a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs @@ -269,8 +269,8 @@ impl<F> resource_id: ResponseId::ConnectorTransactionId( item.data.attempt_id.clone(), ), - redirection_data: Some(redirection_data), - mandate_reference: None, + redirection_data: Box::new(Some(redirection_data)), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -302,8 +302,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, Paym resource_id: ResponseId::ConnectorTransactionId( item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs index 3633c366c4c..41a5306527c 100644 --- a/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs @@ -146,8 +146,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsRe let response_data = timeline.context.map_or( Ok(PaymentsResponseData::TransactionResponse { resource_id: connector_id.clone(), - redirection_data: Some(redirection_data), - mandate_reference: None, + redirection_data: Box::new(Some(redirection_data)), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.data.id.clone()), diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs index 4440346db6b..1228edcaaea 100644 --- a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs @@ -183,8 +183,8 @@ impl<F, T> .map(|x| RedirectForm::from((x, common_utils::request::Method::Get))); Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.data.id.clone()), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs index e4b011f6204..ccecdaa3d41 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs @@ -298,16 +298,16 @@ impl }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, - redirection_data: Some(RedirectForm::Form { + redirection_data: Box::new(Some(RedirectForm::Form { endpoint: item.data.request.get_complete_authorize_url()?, method: common_utils::request::Method::Get, form_fields: HashMap::from([ ("reference".to_string(), reference.clone()), ("signed_on".to_string(), signed_on.clone()), ]), - }), + })), mandate_reference: if item.data.request.is_mandate_payment() { - Some(MandateReference { + Box::new(Some(MandateReference { connector_mandate_id: item.response.mandate_id, payment_method_id: None, mandate_metadata: Some(serde_json::json!(DeutschebankMandateMetadata { @@ -325,9 +325,9 @@ impl reference: Secret::from(reference.clone()), signed_on, })), - }) + })) } else { - None + Box::new(None) }, connector_metadata: None, network_txn_id: None, @@ -375,8 +375,8 @@ impl }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -578,8 +578,8 @@ impl }, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -637,8 +637,8 @@ impl Ok(Self { response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs b/crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs index 722c78442da..856736842f9 100644 --- a/crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs @@ -124,8 +124,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, DigitalvirgoPaymentsResponse, T, Paymen status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs index d21fa481579..f2a6e1b6a6f 100644 --- a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs @@ -326,8 +326,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResp let response = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.order_id.clone(), @@ -360,8 +360,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsSyncResponse, T, Payments status: enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.order_id.clone(), @@ -391,8 +391,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, Payme status: enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.order_id.clone(), @@ -420,8 +420,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCancelResponse, T, Paymen status: enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_id.clone()), diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs index cdcd82f5b4f..6f4f303ae8e 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs @@ -374,8 +374,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, FiservPaymentsResponse, T, PaymentsResp resource_id: ResponseId::ConnectorTransactionId( gateway_resp.transaction_processing_details.transaction_id, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( @@ -413,8 +413,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, FiservSyncResponse, T, PaymentsResponse .transaction_id .clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs index 7f88903e867..a5362283e7a 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs @@ -361,8 +361,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, FiservemeaPaymentsResponse, T, Payments ), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.ipg_transaction_id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.order_id, diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index a401af51008..3d11c24688d 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -604,8 +604,8 @@ impl<F> status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.txn_id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: get_qr_metadata(response)?, network_txn_id: None, connector_response_reference_id: None, @@ -640,8 +640,8 @@ impl<F> status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(data.txn_id), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -684,8 +684,8 @@ impl<F> } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(data.txn_id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -924,8 +924,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy }; let payments_response_data = PaymentsResponseData::TransactionResponse { resource_id: item.data.request.connector_transaction_id.clone(), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -963,8 +963,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy }; let payments_response_data = PaymentsResponseData::TransactionResponse { resource_id: item.data.request.connector_transaction_id.clone(), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -1130,8 +1130,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>> }; let payments_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.tran_id.to_string()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -1241,8 +1241,8 @@ impl TryFrom<PaymentsCancelResponseRouterData<FiuuPaymentCancelResponse>> }; let payments_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.tran_id.to_string()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs b/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs index d04ea7bfee4..6e67409238d 100644 --- a/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs @@ -299,8 +299,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, FortePaymentsResponse, T, PaymentsRespo status: get_status(response_code, action), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(ForteMeta { auth_id: item.response.authorization_code, })), @@ -342,8 +342,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsR status: enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(ForteMeta { auth_id: item.response.authorization_code, })), @@ -411,8 +411,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<ForteCaptureResponse>> status: enums::AttemptStatus::from(item.response.response.response_code), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(ForteMeta { auth_id: item.response.authorization_code, })), @@ -479,8 +479,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ForteCancelResponse, T, PaymentsRespons status: enums::AttemptStatus::from(item.response.response.response_code), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(ForteMeta { auth_id: item.response.authorization_code, })), diff --git a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs index 2e3919cfc48..66525d49c63 100644 --- a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs @@ -213,8 +213,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, GlobepayPaymentsResponse, T, PaymentsRe .order_id .ok_or(errors::ConnectorError::ResponseHandlingFailed)?, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: None, @@ -287,8 +287,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, GlobepaySyncResponse, T, PaymentsRespon status: enums::AttemptStatus::from(globepay_status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(globepay_id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs index a01e2cf918d..427fef3836c 100644 --- a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs @@ -379,8 +379,8 @@ impl<F> resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.to_string(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.invoice_number.clone(), @@ -430,8 +430,8 @@ impl<F> Ok(Self { response: Ok(PaymentsResponseData::TransactionResponse { resource_id, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: item.response.invoice_number.clone(), @@ -479,8 +479,8 @@ impl<F> resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.to_string(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.invoice_number.clone(), @@ -559,8 +559,8 @@ impl<F> resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.to_string(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.invoice_number.clone(), @@ -616,8 +616,8 @@ impl<F> resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.to_string(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.invoice_number.clone(), diff --git a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs index dc5f64bee18..cef3d684e7b 100644 --- a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs @@ -507,8 +507,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, MolliePaymentsResponse, T, PaymentsResp status: enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data: url, - mandate_reference: None, + redirection_data: Box::new(url), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs index eeb24233bef..4761581401f 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs @@ -365,8 +365,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, Paym status: get_status(transaction.status.clone(), item.response.transaction_type), response: Ok(PaymentsResponseData::TransactionResponse { resource_id, - redirection_data, - mandate_reference, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(mandate_reference), connector_metadata: Some(connector_metadata), network_txn_id: None, connector_response_reference_id: Some(item.response.order_id), @@ -445,8 +445,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsRes status: get_status(item.response.status, item.response.transaction_type), response: Ok(PaymentsResponseData::TransactionResponse { resource_id, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(connector_metadata), network_txn_id: None, connector_response_reference_id: Some(item.response.order.order_id), diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index 1677343fe38..d593864dbfc 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -353,8 +353,8 @@ impl<F> resource_id: ResponseId::ConnectorTransactionId( item.response.operation.order_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(item.response.operation.order_id), @@ -626,8 +626,8 @@ impl<F> resource_id: ResponseId::ConnectorTransactionId( item.response.operation.order_id.clone(), ), - redirection_data: Some(redirection_form.clone()), - mandate_reference: None, + redirection_data: Box::new(Some(redirection_form.clone())), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(item.response.operation.order_id), @@ -744,8 +744,8 @@ impl<F> resource_id: ResponseId::ConnectorTransactionId( item.response.operation.order_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(item.response.operation.order_id), @@ -867,8 +867,8 @@ impl<F> status: AttemptStatus::from(item.response.operation_result), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: item.data.request.connector_meta.clone(), network_txn_id: None, connector_response_reference_id: Some(item.response.order_id.clone()), @@ -923,8 +923,8 @@ impl<F> resource_id: ResponseId::ConnectorTransactionId( item.data.request.connector_transaction_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some( @@ -986,8 +986,8 @@ impl<F> resource_id: ResponseId::ConnectorTransactionId( item.data.request.connector_transaction_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some( diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index ab209a4db05..1f16a14fde3 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -594,14 +594,14 @@ impl<F, T> TryFrom<ResponseRouterData<F, NovalnetPaymentsResponse, T, PaymentsRe .clone() .map(ResponseId::ConnectorTransactionId) .unwrap_or(ResponseId::NoResponseId), - redirection_data, - mandate_reference: mandate_reference_id.as_ref().map(|id| { + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(mandate_reference_id.as_ref().map(|id| { MandateReference { connector_mandate_id: Some(id.clone()), payment_method_id: None, mandate_metadata: None, } - }), + })), connector_metadata: None, network_txn_id: None, connector_response_reference_id: transaction_id.clone(), @@ -995,14 +995,14 @@ impl<F> .clone() .map(ResponseId::ConnectorTransactionId) .unwrap_or(ResponseId::NoResponseId), - redirection_data: None, - mandate_reference: mandate_reference_id.as_ref().map(|id| { + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference_id.as_ref().map(|id| { MandateReference { connector_mandate_id: Some(id.clone()), payment_method_id: None, mandate_metadata: None, } - }), + })), connector_metadata: None, network_txn_id: None, connector_response_reference_id: transaction_id.clone(), @@ -1085,8 +1085,8 @@ impl<F> .clone() .map(ResponseId::ConnectorTransactionId) .unwrap_or(ResponseId::NoResponseId), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: transaction_id.clone(), @@ -1254,8 +1254,8 @@ impl<F> .clone() .map(ResponseId::ConnectorTransactionId) .unwrap_or(ResponseId::NoResponseId), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: transaction_id.clone(), diff --git a/crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs index 47c5c40363e..af29d54117a 100644 --- a/crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs @@ -432,8 +432,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsRes resource_id: ResponseId::ConnectorTransactionId( item.response.transaction_id.clone(), ), - redirection_data: None, - mandate_reference, + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference), connector_metadata: metadata, network_txn_id: None, connector_response_reference_id: Some( diff --git a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs index 7b3792c0e24..0b2b7030528 100644 --- a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs @@ -210,8 +210,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsResponse, T, PaymentsRespon status: enums::AttemptStatus::from(item.response.status.status_code), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item @@ -260,8 +260,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsCaptureResponse, T, Payment status: enums::AttemptStatus::from(item.response.status.status_code.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -335,8 +335,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsCancelResponse, T, Payments status: enums::AttemptStatus::from(item.response.status.status_code.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item @@ -464,8 +464,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsSyncResponse, T, PaymentsRe status: enums::AttemptStatus::from(order.status.clone()), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(order.order_id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: order diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs index 770688a3468..93ba3425978 100644 --- a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs @@ -336,8 +336,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PowertranzBaseResponse, T, PaymentsResp let response = error_response.map_or( Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(connector_transaction_id), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_identifier), diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs index b2151c524be..0e6d3128b30 100644 --- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs @@ -385,8 +385,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResp status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.payment.reference_id, diff --git a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs index 0f112566796..a8e9a7ad829 100644 --- a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs @@ -372,8 +372,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, StaxPaymentsResponse, T, PaymentsRespon status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some( diff --git a/crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs b/crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs index c0ee0fdae94..ca18179ff17 100644 --- a/crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs @@ -129,8 +129,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ThunesPaymentsResponse, T, PaymentsResp status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs index e97cf228729..fc485e65727 100644 --- a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs @@ -226,8 +226,8 @@ fn get_error_response( fn get_payments_response(connector_response: TsysResponse) -> PaymentsResponseData { PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(connector_response.transaction_id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(connector_response.transaction_id), @@ -246,8 +246,8 @@ fn get_payments_sync_response( .transaction_id .clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs index e04eae63b4c..b13d029185f 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs @@ -277,8 +277,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponse, T, PaymentsRespon status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), @@ -351,8 +351,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsRe resource_id: ResponseId::ConnectorTransactionId( payment_response.id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: payment_response @@ -392,8 +392,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsRe resource_id: ResponseId::ConnectorTransactionId( webhook_response.payment.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: webhook_response diff --git a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs index 09ffac81425..05986631c67 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs @@ -570,8 +570,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, Payment, T, PaymentsResponseData>> status: get_status((item.response.status, item.response.capture_method)), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), @@ -621,8 +621,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaymentResponse, T, PaymentsResponseDat )), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id.clone()), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.payment.id), diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs index a564fb4ee60..d4a18a15182 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs @@ -939,8 +939,8 @@ fn get_zen_response( }; let payment_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.id.clone()), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -983,8 +983,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, CheckoutResponse, T, PaymentsResponseDa status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs index af901a80558..9f079f1312e 100644 --- a/crates/hyperswitch_domain_models/src/customer.rs +++ b/crates/hyperswitch_domain_models/src/customer.rs @@ -275,7 +275,7 @@ pub enum CustomerUpdate { description: Option<Description>, phone_country_code: Option<String>, metadata: Option<pii::SecretSerdeValue>, - connector_customer: Option<pii::SecretSerdeValue>, + connector_customer: Box<Option<pii::SecretSerdeValue>>, default_billing_address: Option<Encryption>, default_shipping_address: Option<Encryption>, default_payment_method_id: Option<Option<String>>, @@ -312,7 +312,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal { description, phone_country_code, metadata, - connector_customer, + connector_customer: *connector_customer, modified_at: date_time::now(), default_billing_address, default_shipping_address, @@ -366,7 +366,7 @@ pub enum CustomerUpdate { description: Option<Description>, phone_country_code: Option<String>, metadata: Option<pii::SecretSerdeValue>, - connector_customer: Option<pii::SecretSerdeValue>, + connector_customer: Box<Option<pii::SecretSerdeValue>>, address_id: Option<String>, }, ConnectorCustomer { @@ -397,7 +397,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal { description, phone_country_code, metadata, - connector_customer, + connector_customer: *connector_customer, modified_at: date_time::now(), address_id, default_payment_method_id: None, diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs index 66b98389818..9418f6f8f1e 100644 --- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs @@ -88,20 +88,20 @@ pub enum MerchantConnectorAccountUpdate { Update { connector_type: Option<enums::ConnectorType>, connector_name: Option<String>, - connector_account_details: Option<Encryptable<pii::SecretSerdeValue>>, + connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, test_mode: Option<bool>, disabled: Option<bool>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, metadata: Option<pii::SecretSerdeValue>, frm_configs: Option<Vec<pii::SecretSerdeValue>>, - connector_webhook_details: Option<pii::SecretSerdeValue>, + connector_webhook_details: Box<Option<pii::SecretSerdeValue>>, applepay_verified_domains: Option<Vec<String>>, - pm_auth_config: Option<pii::SecretSerdeValue>, + pm_auth_config: Box<Option<pii::SecretSerdeValue>>, connector_label: Option<String>, status: Option<enums::ConnectorStatus>, - connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>, - additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>, + connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, + additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>, }, ConnectorWalletDetailsUpdate { connector_wallets_details: Encryptable<pii::SecretSerdeValue>, @@ -113,18 +113,18 @@ pub enum MerchantConnectorAccountUpdate { pub enum MerchantConnectorAccountUpdate { Update { connector_type: Option<enums::ConnectorType>, - connector_account_details: Option<Encryptable<pii::SecretSerdeValue>>, + connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, disabled: Option<bool>, payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, metadata: Option<pii::SecretSerdeValue>, frm_configs: Option<Vec<pii::SecretSerdeValue>>, connector_webhook_details: Option<pii::SecretSerdeValue>, applepay_verified_domains: Option<Vec<String>>, - pm_auth_config: Option<pii::SecretSerdeValue>, + pm_auth_config: Box<Option<pii::SecretSerdeValue>>, connector_label: Option<String>, status: Option<enums::ConnectorStatus>, - connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>, - additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>, + connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, + additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>, }, ConnectorWalletDetailsUpdate { connector_wallets_details: Encryptable<pii::SecretSerdeValue>, @@ -413,9 +413,9 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte frm_configs: None, frm_config: frm_configs, modified_at: Some(date_time::now()), - connector_webhook_details, + connector_webhook_details: *connector_webhook_details, applepay_verified_domains, - pm_auth_config, + pm_auth_config: *pm_auth_config, connector_label, status, connector_wallets_details: connector_wallets_details.map(Encryption::from), @@ -475,7 +475,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte modified_at: Some(date_time::now()), connector_webhook_details, applepay_verified_domains, - pm_auth_config, + pm_auth_config: *pm_auth_config, connector_label, status, connector_wallets_details: connector_wallets_details.map(Encryption::from), diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index 6682ac1ad44..2ed77c8072d 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -17,8 +17,8 @@ pub struct RefundsResponseData { pub enum PaymentsResponseData { TransactionResponse { resource_id: ResponseId, - redirection_data: Option<RedirectForm>, - mandate_reference: Option<MandateReference>, + redirection_data: Box<Option<RedirectForm>>, + mandate_reference: Box<Option<MandateReference>>, connector_metadata: Option<serde_json::Value>, network_txn_id: Option<String>, connector_response_reference_id: Option<String>, diff --git a/crates/router/src/compatibility/stripe/webhooks.rs b/crates/router/src/compatibility/stripe/webhooks.rs index 8445011f569..ddc291e6b13 100644 --- a/crates/router/src/compatibility/stripe/webhooks.rs +++ b/crates/router/src/compatibility/stripe/webhooks.rs @@ -81,7 +81,7 @@ impl OutgoingWebhookType for StripeOutgoingWebhook { #[derive(Serialize, Debug)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] pub enum StripeWebhookObject { - PaymentIntent(StripePaymentIntentResponse), + PaymentIntent(Box<StripePaymentIntentResponse>), Refund(StripeRefundResponse), Dispute(StripeDisputeResponse), Mandate(StripeMandateResponse), @@ -327,9 +327,9 @@ impl From<api::OutgoingWebhookContent> for StripeWebhookObject { fn from(value: api::OutgoingWebhookContent) -> Self { match value { api::OutgoingWebhookContent::PaymentDetails(payment) => { - Self::PaymentIntent(payment.into()) + Self::PaymentIntent(Box::new((*payment).into())) } - api::OutgoingWebhookContent::RefundDetails(refund) => Self::Refund(refund.into()), + api::OutgoingWebhookContent::RefundDetails(refund) => Self::Refund((*refund).into()), api::OutgoingWebhookContent::DisputeDetails(dispute) => { Self::Dispute((*dispute).into()) } @@ -337,7 +337,7 @@ impl From<api::OutgoingWebhookContent> for StripeWebhookObject { Self::Mandate((*mandate).into()) } #[cfg(feature = "payouts")] - api::OutgoingWebhookContent::PayoutDetails(payout) => Self::Payout(payout.into()), + api::OutgoingWebhookContent::PayoutDetails(payout) => Self::Payout((*payout).into()), } } } diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 5e803b593ee..7355617b53a 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -763,8 +763,8 @@ impl<F, T> }, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data, - mandate_reference, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index ca13e57e401..21c9c34409a 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -3273,8 +3273,8 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> resource_id: types::ResponseId::ConnectorTransactionId( item.response.payment_psp_reference, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.reference), @@ -3308,8 +3308,8 @@ impl<F> Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.psp_reference), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -3374,8 +3374,8 @@ pub fn get_adyen_response( let payments_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(response.psp_reference), - redirection_data: None, - mandate_reference, + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id, connector_response_reference_id: Some(response.merchant_reference), @@ -3438,8 +3438,8 @@ pub fn get_webhook_response( .payment_reference .unwrap_or(response.transaction_id), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(response.merchant_reference_id), @@ -3508,8 +3508,8 @@ pub fn get_redirection_response( Some(psp) => types::ResponseId::ConnectorTransactionId(psp.to_string()), None => types::ResponseId::NoResponseId, }, - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: response @@ -3566,8 +3566,8 @@ pub fn get_present_to_shopper_response( Some(psp) => types::ResponseId::ConnectorTransactionId(psp.to_string()), None => types::ResponseId::NoResponseId, }, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: response @@ -3623,8 +3623,8 @@ pub fn get_qr_code_response( Some(psp) => types::ResponseId::ConnectorTransactionId(psp.to_string()), None => types::ResponseId::NoResponseId, }, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: response @@ -3666,8 +3666,8 @@ pub fn get_redirection_error_response( // We don't get connector transaction id for redirections in Adyen. let payments_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: response @@ -4036,8 +4036,8 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>> status: storage_enums::AttemptStatus::Pending, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(connector_transaction_id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.reference), diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index d3824e9d0da..ad7ae2716f1 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -570,8 +570,8 @@ impl<F, T> reference_id: Some(item.response.id.clone()), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), @@ -613,8 +613,8 @@ impl reference_id: Some(item.response.id.clone()), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 903470ae952..6961a87326b 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -388,20 +388,19 @@ impl<F, T> status: enums::AttemptStatus::Charged, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: item.response.customer_profile_id.map( + redirection_data: Box::new(None), + mandate_reference: Box::new(item.response.customer_profile_id.map( |customer_profile_id| types::MandateReference { - connector_mandate_id: item - .response - .customer_payment_profile_id_list - .first() - .map(|payment_profile_id| { - format!("{customer_profile_id}-{payment_profile_id}") - }), + connector_mandate_id: + item.response.customer_payment_profile_id_list.first().map( + |payment_profile_id| { + format!("{customer_profile_id}-{payment_profile_id}") + }, + ), payment_method_id: None, mandate_metadata: None, }, - ), + )), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -1125,8 +1124,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( transaction_response.transaction_id.clone(), ), - redirection_data, - mandate_reference, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(mandate_reference), connector_metadata: metadata, network_txn_id: transaction_response .network_trans_id @@ -1198,8 +1197,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( transaction_response.transaction_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: metadata, network_txn_id: transaction_response .network_trans_id @@ -1528,8 +1527,8 @@ impl<F, Req> resource_id: types::ResponseId::ConnectorTransactionId( transaction.transaction_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(transaction.transaction_id.clone()), diff --git a/crates/router/src/connector/bamboraapac/transformers.rs b/crates/router/src/connector/bamboraapac/transformers.rs index 819c918338e..8fcbcd98f09 100644 --- a/crates/router/src/connector/bamboraapac/transformers.rs +++ b/crates/router/src/connector/bamboraapac/transformers.rs @@ -39,14 +39,14 @@ pub fn get_payment_body( let transaction_data = get_transaction_body(req)?; let body = format!( r#" - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dts="http://www.ippayments.com.au/interface/api/dts"> <soapenv:Body> <dts:SubmitSinglePayment> <dts:trnXML> <![CDATA[ {} - ]]> + ]]> </dts:trnXML> </dts:SubmitSinglePayment> </soapenv:Body> @@ -293,8 +293,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( connector_transaction_id.to_owned(), ), - redirection_data: None, - mandate_reference, + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(connector_transaction_id), @@ -354,12 +354,12 @@ pub fn get_setup_mandate_body(req: &types::SetupMandateRouterData) -> Result<Vec <sipp:tokeniseCreditCardXML> <![CDATA[ <TokeniseCreditCard> - <CardNumber>{}</CardNumber> + <CardNumber>{}</CardNumber> <ExpM>{}</ExpM> <ExpY>{}</ExpY> <CardHolderName>{}</CardHolderName> <TokeniseAlgorithmID>2</TokeniseAlgorithmID> - <UserName>{}</UserName> + <UserName>{}</UserName> <Password>{}</Password> </TokeniseCreditCard> ]]> @@ -460,12 +460,12 @@ impl<F> status: enums::AttemptStatus::Charged, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: Some(types::MandateReference { + redirection_data: Box::new(None), + mandate_reference: Box::new(Some(types::MandateReference { connector_mandate_id: Some(connector_mandate_id), payment_method_id: None, mandate_metadata: None, - }), + })), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -501,7 +501,7 @@ pub fn get_capture_body( let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?; let body = format!( r#" - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dts="http://www.ippayments.com.au/interface/api/dts"> <soapenv:Body> <dts:SubmitSingleCapture> @@ -514,8 +514,8 @@ pub fn get_capture_body( <UserName>{}</UserName> <Password>{}</Password> </Security> - </Capture> - ]]> + </Capture> + ]]> </dts:trnXML> </dts:SubmitSingleCapture> </soapenv:Body> @@ -610,8 +610,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( connector_transaction_id.to_owned(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(connector_transaction_id), @@ -663,7 +663,7 @@ pub fn get_refund_body( let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?; let body = format!( r#" - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dts="http://www.ippayments.com.au/interface/api/dts"> <soapenv:Header/> <soapenv:Body> @@ -677,9 +677,9 @@ pub fn get_refund_body( <Security> <UserName>{}</UserName> <Password>{}</Password> - </Security> + </Security> </Refund> - ]]> + ]]> </dts:trnXML> </dts:SubmitSingleRefund> </soapenv:Body> @@ -792,7 +792,7 @@ pub fn get_payment_sync_body(req: &types::PaymentsSyncRouterData) -> Result<Vec< .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; let body = format!( r#" - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dts="http://www.ippayments.com.au/interface/api/dts"> <soapenv:Header/> <soapenv:Body> @@ -810,8 +810,8 @@ pub fn get_payment_sync_body(req: &types::PaymentsSyncRouterData) -> Result<Vec< <UserName>{}</UserName> <Password>{}</Password> </Security> - </QueryTransaction> - ]]> + </QueryTransaction> + ]]> </dts:queryXML> </dts:QueryTransaction> </soapenv:Body> @@ -909,8 +909,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( connector_transaction_id.to_owned(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(connector_transaction_id), @@ -961,7 +961,7 @@ pub fn get_refund_sync_body(req: &types::RefundSyncRouterData) -> Result<Vec<u8> let body = format!( r#" - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dts="http://www.ippayments.com.au/interface/api/dts"> <soapenv:Header/> <soapenv:Body> @@ -979,8 +979,8 @@ pub fn get_refund_sync_body(req: &types::RefundSyncRouterData) -> Result<Vec<u8> <UserName>{}</UserName> <Password>{}</Password> </Security> - </QueryTransaction> - ]]> + </QueryTransaction> + ]]> </dts:queryXML> </dts:QueryTransaction> </soapenv:Body> diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index ad75328322d..b5669decd86 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -412,8 +412,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( info_response.id.clone(), ), - redirection_data: None, - mandate_reference, + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( @@ -1516,8 +1516,8 @@ fn get_payment_response( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), - redirection_data: None, - mandate_reference, + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( @@ -1829,8 +1829,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( item.response.id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item @@ -1852,8 +1852,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( item.response.id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index e6f01700c6d..468f68dc340 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -741,10 +741,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P status: enums::AttemptStatus::AuthenticationPending, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: Some(services::RedirectForm::BlueSnap { + redirection_data: Box::new(Some(services::RedirectForm::BlueSnap { payment_fields_token, - }), - mandate_reference: None, + })), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 39be2517e4b..6db0ddac49b 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -875,8 +875,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.transaction_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.transaction_id), diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs index bc9eb4e3722..777b795a438 100644 --- a/crates/router/src/connector/boku/transformers.rs +++ b/crates/router/src/connector/boku/transformers.rs @@ -301,8 +301,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, BokuResponse, T, types::Payments status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(transaction_id), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index b7515a964bb..948d6f2cfd3 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -439,14 +439,14 @@ impl<F> } else { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id), - redirection_data: None, - mandate_reference: transaction_data.payment_method.as_ref().map(|pm| { - MandateReference { + redirection_data: Box::new(None), + mandate_reference: Box::new(transaction_data.payment_method.as_ref().map( + |pm| MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, mandate_metadata: None, - } - }), + }, + )), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -464,12 +464,12 @@ impl<F> status: enums::AttemptStatus::AuthenticationPending, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: Some(get_braintree_redirect_form( + redirection_data: Box::new(Some(get_braintree_redirect_form( *client_token_data, item.data.get_payment_method_token()?, item.data.request.payment_method_data.clone(), - )?), - mandate_reference: None, + )?)), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -614,14 +614,14 @@ impl<F> } else { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id), - redirection_data: None, - mandate_reference: transaction_data.payment_method.as_ref().map(|pm| { - MandateReference { + redirection_data: Box::new(None), + mandate_reference: Box::new(transaction_data.payment_method.as_ref().map( + |pm| MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, mandate_metadata: None, - } - }), + }, + )), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -639,12 +639,12 @@ impl<F> status: enums::AttemptStatus::AuthenticationPending, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: Some(get_braintree_redirect_form( + redirection_data: Box::new(Some(get_braintree_redirect_form( *client_token_data, item.data.get_payment_method_token()?, item.data.request.payment_method_data.clone(), - )?), - mandate_reference: None, + )?)), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -696,14 +696,14 @@ impl<F> } else { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id), - redirection_data: None, - mandate_reference: transaction_data.payment_method.as_ref().map(|pm| { - MandateReference { + redirection_data: Box::new(None), + mandate_reference: Box::new(transaction_data.payment_method.as_ref().map( + |pm| MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, mandate_metadata: None, - } - }), + }, + )), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -760,14 +760,14 @@ impl<F> } else { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id), - redirection_data: None, - mandate_reference: transaction_data.payment_method.as_ref().map(|pm| { - MandateReference { + redirection_data: Box::new(None), + mandate_reference: Box::new(transaction_data.payment_method.as_ref().map( + |pm| MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, mandate_metadata: None, - } - }), + }, + )), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -1274,8 +1274,8 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>> } else { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -1384,8 +1384,8 @@ impl<F, T> } else { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -1489,8 +1489,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( edge_data.node.id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 3e951b3ac86..686a9d57ac3 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -688,8 +688,8 @@ impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>> }; let payments_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: Some( @@ -741,8 +741,8 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponse>> }; let payments_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( @@ -819,8 +819,8 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymentVoidResponse>> Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(response.action_id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -920,8 +920,8 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>> Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(resource_id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: item.response.reference, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index da768258614..4331b4d7983 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -2559,8 +2559,8 @@ fn get_payment_response( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), - redirection_data: None, - mandate_reference, + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: info_response.processor_information.as_ref().and_then( |processor_information| processor_information.network_transaction_id.clone(), @@ -2647,18 +2647,20 @@ impl<F> status: enums::AttemptStatus::AuthenticationPending, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: Some(services::RedirectForm::CybersourceAuthSetup { - access_token: info_response - .consumer_authentication_information - .access_token, - ddc_url: info_response - .consumer_authentication_information - .device_data_collection_url, - reference_id: info_response - .consumer_authentication_information - .reference_id, - }), - mandate_reference: None, + redirection_data: Box::new(Some( + services::RedirectForm::CybersourceAuthSetup { + access_token: info_response + .consumer_authentication_information + .access_token, + ddc_url: info_response + .consumer_authentication_information + .device_data_collection_url, + reference_id: info_response + .consumer_authentication_information + .reference_id, + }, + )), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( @@ -3066,8 +3068,8 @@ impl<F> status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!({ "three_ds_data": three_ds_data })), @@ -3311,8 +3313,8 @@ impl resource_id: types::ResponseId::ConnectorTransactionId( item.response.id.clone(), ), - redirection_data: None, - mandate_reference, + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: item.response.processor_information.as_ref().and_then( |processor_information| { @@ -3449,8 +3451,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( item.response.id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item @@ -3471,8 +3473,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( item.response.id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), diff --git a/crates/router/src/connector/datatrans/transformers.rs b/crates/router/src/connector/datatrans/transformers.rs index b28504a1d83..e9dcfd87071 100644 --- a/crates/router/src/connector/datatrans/transformers.rs +++ b/crates/router/src/connector/datatrans/transformers.rs @@ -293,8 +293,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( response.transaction_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -411,8 +411,8 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<DatatransSyncResponse>> status: enums::AttemptStatus::from(response), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/dummyconnector/transformers.rs b/crates/router/src/connector/dummyconnector/transformers.rs index 2cf5960bf75..79caa3d0a76 100644 --- a/crates/router/src/connector/dummyconnector/transformers.rs +++ b/crates/router/src/connector/dummyconnector/transformers.rs @@ -253,8 +253,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentsResponse, T, types::Paym status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index 19568ae4671..d17c8a8fdfd 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -274,8 +274,8 @@ fn get_payment_response( }), _ => Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(response.id), - redirection_data, - mandate_reference, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id: response.reference, diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index c0360a94a51..dac90b28366 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -523,8 +523,8 @@ impl<F> connector_response_reference_id: None, incremental_authorization_allowed: None, resource_id: ResponseId::NoResponseId, - redirection_data: None, - mandate_reference, + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference), network_txn_id: None, charge_id: None, }), @@ -674,8 +674,8 @@ impl<F> status: enums::AttemptStatus::from(item.response.payments.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id), - redirection_data: None, - mandate_reference: Some(mandate_reference), + redirection_data: Box::new(None), + mandate_reference: Box::new(Some(mandate_reference)), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -710,8 +710,8 @@ impl<F> status: enums::AttemptStatus::from(item.response.payments.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index de92168036c..ec94b322fe7 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -382,8 +382,8 @@ fn get_iatpay_response( types::PaymentsResponseData::TransactionResponse { resource_id: id, - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: connector_response_reference_id.clone(), @@ -393,8 +393,8 @@ fn get_iatpay_response( } None => types::PaymentsResponseData::TransactionResponse { resource_id: id.clone(), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: connector_response_reference_id.clone(), diff --git a/crates/router/src/connector/itaubank/transformers.rs b/crates/router/src/connector/itaubank/transformers.rs index 41c41408381..15dfb1ce240 100644 --- a/crates/router/src/connector/itaubank/transformers.rs +++ b/crates/router/src/connector/itaubank/transformers.rs @@ -280,8 +280,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.txid.to_owned(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(item.response.txid), @@ -368,8 +368,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.txid.to_owned(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(item.response.txid), diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index e6f0bab9c2c..ea83e20d99d 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -272,8 +272,8 @@ impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>> resource_id: types::ResponseId::ConnectorTransactionId( item.response.order_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.order_id.clone()), @@ -394,8 +394,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.order_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item @@ -474,8 +474,8 @@ impl<F> Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(resource_id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs index 03c63d66795..6ff52bb7eb1 100644 --- a/crates/router/src/connector/mifinity/transformers.rs +++ b/crates/router/src/connector/mifinity/transformers.rs @@ -259,10 +259,10 @@ impl<F, T> status: enums::AttemptStatus::AuthenticationPending, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(trace_id.clone()), - redirection_data: Some(services::RedirectForm::Mifinity { + redirection_data: Box::new(Some(services::RedirectForm::Mifinity { initialization_token, - }), - mandate_reference: None, + })), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(trace_id), @@ -276,8 +276,8 @@ impl<F, T> status: enums::AttemptStatus::AuthenticationPending, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -345,8 +345,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( transaction_reference, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -360,8 +360,8 @@ impl<F, T> status: enums::AttemptStatus::from(status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -376,8 +376,8 @@ impl<F, T> status: item.data.status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 9db1cb3701a..2831b63fcbe 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -930,7 +930,7 @@ pub struct MultisafepayPaymentsResponse { #[serde(untagged)] pub enum MultisafepayAuthResponse { ErrorResponse(MultisafepayErrorResponse), - PaymentResponse(MultisafepayPaymentsResponse), + PaymentResponse(Box<MultisafepayPaymentsResponse>), } impl<F, T> @@ -979,16 +979,18 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( payment_response.data.order_id.clone(), ), - redirection_data, - mandate_reference: payment_response - .data - .payment_details - .and_then(|payment_details| payment_details.recurring_id) - .map(|id| types::MandateReference { - connector_mandate_id: Some(id.expose()), - payment_method_id: None, - mandate_metadata: None, - }), + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new( + payment_response + .data + .payment_details + .and_then(|payment_details| payment_details.recurring_id) + .map(|id| types::MandateReference { + connector_mandate_id: Some(id.expose()), + payment_method_id: None, + mandate_metadata: None, + }), + ), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some( diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index af2a9fe56bb..0ec9cc94888 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -185,7 +185,7 @@ impl Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: Some(services::RedirectForm::Nmi { + redirection_data: Box::new(Some(services::RedirectForm::Nmi { amount: utils::to_currency_base_unit_asf64( amount_data, currency_data.to_owned(), @@ -206,8 +206,8 @@ impl }, )?, order_id: item.data.connector_request_reference_id.clone(), - }), - mandate_reference: None, + })), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.transactionid), @@ -360,8 +360,8 @@ impl resource_id: types::ResponseId::ConnectorTransactionId( item.response.transactionid, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), @@ -743,8 +743,8 @@ impl resource_id: types::ResponseId::ConnectorTransactionId( item.response.transactionid.to_owned(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), @@ -838,8 +838,8 @@ impl<T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), @@ -895,8 +895,8 @@ impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> resource_id: types::ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), @@ -946,8 +946,8 @@ impl<T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), @@ -997,8 +997,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SyncResponse, T, types::Payments status: enums::AttemptStatus::from(NmiStatus::from(trn.condition)), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(trn.transaction_id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 5c3de332b70..634a9feccf3 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -596,8 +596,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( order.id.to_string(), ), - redirection_data, - mandate_reference, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: None, connector_response_reference_id, diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index d1d7122f49e..68c25f58acb 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1598,15 +1598,17 @@ where .map_or(response.order_id.clone(), Some) // For paypal there will be no transaction_id, only order_id will be present .map(types::ResponseId::ConnectorTransactionId) .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - redirection_data, - mandate_reference: response - .payment_option - .and_then(|po| po.user_payment_option_id) - .map(|id| types::MandateReference { - connector_mandate_id: Some(id), - payment_method_id: None, - mandate_metadata: None, - }), + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new( + response + .payment_option + .and_then(|po| po.user_payment_option_id) + .map(|id| types::MandateReference { + connector_mandate_id: Some(id), + payment_method_id: None, + mandate_metadata: None, + }), + ), // we don't need to save session token for capture, void flow so ignoring if it is not present connector_metadata: if let Some(token) = response.session_token { Some( diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index 44069f3650b..44445a3d7d9 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -144,8 +144,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.transaction_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.transaction_id), diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs index 8f1579ac1ff..1e8239d377b 100644 --- a/crates/router/src/connector/opennode/transformers.rs +++ b/crates/router/src/connector/opennode/transformers.rs @@ -138,8 +138,8 @@ impl<F, T> let response_data = if attempt_status != OpennodePaymentStatus::Underpaid { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: connector_id, - redirection_data: Some(redirection_data), - mandate_reference: None, + redirection_data: Box::new(Some(redirection_data)), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.data.order_id, diff --git a/crates/router/src/connector/paybox/transformers.rs b/crates/router/src/connector/paybox/transformers.rs index d02f75693c4..b52a6e463f6 100644 --- a/crates/router/src/connector/paybox/transformers.rs +++ b/crates/router/src/connector/paybox/transformers.rs @@ -597,8 +597,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( response.paybox_order_id, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(PayboxMeta { connector_request_id: response.transaction_number.clone() })), @@ -657,8 +657,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( response.paybox_order_id, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(PayboxMeta { connector_request_id: response.transaction_number.clone() })), @@ -686,10 +686,10 @@ impl<F> status: enums::AttemptStatus::AuthenticationPending, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: Some(RedirectForm::Html { + redirection_data: Box::new(Some(RedirectForm::Html { html_data: data.peek().to_string(), - }), - mandate_reference: None, + })), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -731,8 +731,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PayboxSyncResponse, T, types::Pa resource_id: types::ResponseId::ConnectorTransactionId( response.paybox_order_id, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(PayboxMeta { connector_request_id: response.transaction_number.clone() })), @@ -916,8 +916,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( response.paybox_order_id, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(PayboxMeta { connector_request_id: response.transaction_number.clone() })), diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 4eac0a6f94d..ceeafb50251 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -246,12 +246,14 @@ impl TryFrom<&PaymePaySaleResponse> for types::PaymentsResponseData { }; Ok(Self::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(value.payme_sale_id.clone()), - redirection_data, - mandate_reference: value.buyer_key.clone().map(|buyer_key| MandateReference { - connector_mandate_id: Some(buyer_key.expose()), - payment_method_id: None, - mandate_metadata: None, - }), + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(value.buyer_key.clone().map(|buyer_key| { + MandateReference { + connector_mandate_id: Some(buyer_key.expose()), + payment_method_id: None, + mandate_metadata: None, + } + })), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -316,9 +318,9 @@ impl From<&SaleQuery> for types::PaymentsResponseData { fn from(value: &SaleQuery) -> Self { Self::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(value.sale_payme_id.clone()), - redirection_data: None, + redirection_data: Box::new(None), // mandate reference will be updated with webhooks only. That has been handled with PaymePaySaleResponse struct - mandate_reference: None, + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -536,8 +538,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( item.response.payme_sale_id.to_owned(), ), - redirection_data: Some(services::RedirectForm::Payme), - mandate_reference: None, + redirection_data: Box::new(Some(services::RedirectForm::Payme)), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -1110,8 +1112,8 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymeVoidResponse>> // Since we are not receiving payme_sale_id, we are not populating the transaction response Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index 274aab8e504..7b866971b01 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -1117,14 +1117,14 @@ impl status: storage_enums::AttemptStatus::AuthenticationSuccessful, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, - charge_id: None, - }), + charge_id: None, + }), ..data.clone() }) } @@ -1168,8 +1168,8 @@ impl status: storage_enums::AttemptStatus::AuthenticationSuccessful, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 30aaf5a84a8..e30a3f07c9b 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -1388,8 +1388,8 @@ impl<F, T> status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: order_id, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: purchase_units @@ -1511,11 +1511,11 @@ impl<F, T> status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data: Some(services::RedirectForm::from(( + redirection_data: Box::new(Some(services::RedirectForm::from(( link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?, services::Method::Get, - ))), - mandate_reference: None, + )))), + mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: Some( @@ -1566,11 +1566,11 @@ impl status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data: Some(services::RedirectForm::from(( + redirection_data: Box::new(Some(services::RedirectForm::from(( link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?, services::Method::Get, - ))), - mandate_reference: None, + )))), + mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: Some( @@ -1624,8 +1624,8 @@ impl status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: None, @@ -1662,8 +1662,8 @@ impl<F> status: storage_enums::AttemptStatus::AuthenticationPending, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -1712,11 +1712,11 @@ impl<F> status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: Some(paypal_threeds_link(( + redirection_data: Box::new(Some(paypal_threeds_link(( link, item.data.request.complete_authorize_url.clone(), - ))?), - mandate_reference: None, + ))?)), + mandate_reference: Box::new(None), connector_metadata: Some(connector_meta), network_txn_id: None, connector_response_reference_id: None, @@ -1780,8 +1780,8 @@ impl<F, T> .order_id .clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item @@ -2115,8 +2115,8 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaypalCaptureResponse>> resource_id: types::ResponseId::ConnectorTransactionId( item.data.request.connector_transaction_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(serde_json::json!(PaypalMeta { authorize_id: connector_payment_id.authorize_id, capture_id: Some(item.response.id.clone()), @@ -2173,8 +2173,8 @@ impl<F, T> status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs index 32d651787b6..2d1ce4771ca 100644 --- a/crates/router/src/connector/placetopay/transformers.rs +++ b/crates/router/src/connector/placetopay/transformers.rs @@ -263,8 +263,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.internal_reference.to_string(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: item .response .authorization diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/router/src/connector/plaid/transformers.rs index f0cf91b9cf6..29d4db1297f 100644 --- a/crates/router/src/connector/plaid/transformers.rs +++ b/crates/router/src/connector/plaid/transformers.rs @@ -308,8 +308,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.payment_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.payment_id), @@ -394,8 +394,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidSyncResponse, T, types::Pay resource_id: types::ResponseId::ConnectorTransactionId( item.response.payment_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.payment_id), diff --git a/crates/router/src/connector/prophetpay/transformers.rs b/crates/router/src/connector/prophetpay/transformers.rs index 6862c7c4c80..24bd4642c01 100644 --- a/crates/router/src/connector/prophetpay/transformers.rs +++ b/crates/router/src/connector/prophetpay/transformers.rs @@ -201,8 +201,8 @@ impl<F> status: enums::AttemptStatus::AuthenticationPending, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -401,8 +401,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( item.response.transaction_id, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: None, @@ -452,8 +452,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.transaction_id, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -503,8 +503,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.transaction_id, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 044a64b413c..bcd0693500a 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -474,8 +474,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( data.id.to_owned(), ), //transaction_id is also the field but this id is used to initiate a refund - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/razorpay/transformers.rs b/crates/router/src/connector/razorpay/transformers.rs index fde72cac100..6755a2d1816 100644 --- a/crates/router/src/connector/razorpay/transformers.rs +++ b/crates/router/src/connector/razorpay/transformers.rs @@ -789,8 +789,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( second_factor.epg_txn_id, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(second_factor.txn_id), @@ -1010,8 +1010,8 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( item.response.second_factor.epg_txn_id, ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.second_factor.txn_id), diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 3b768151115..570d3b90aff 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -759,8 +759,8 @@ impl TryFrom<types::PaymentsPreprocessingResponseRouterData<Shift4ThreeDsRespons }, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: Some( serde_json::to_value(Shift4CardToken { id: item.response.token.id, @@ -802,13 +802,14 @@ impl<T, F> )), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: connector_id, - redirection_data: item - .response - .flow - .and_then(|flow| flow.redirect) - .and_then(|redirect| redirect.redirect_url) - .map(|url| services::RedirectForm::from((url, services::Method::Get))), - mandate_reference: None, + redirection_data: Box::new( + item.response + .flow + .and_then(|flow| flow.redirect) + .and_then(|redirect| redirect.redirect_url) + .map(|url| services::RedirectForm::from((url, services::Method::Get))), + ), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 63720696ef4..fe69f43777e 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2490,8 +2490,8 @@ impl<F, T> }); Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data, - mandate_reference, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(mandate_reference), connector_metadata, network_txn_id, connector_response_reference_id: Some(item.response.id), @@ -2697,8 +2697,8 @@ impl<F, T> }); Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data, - mandate_reference, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(mandate_reference), connector_metadata, network_txn_id: network_transaction_id, connector_response_reference_id: Some(item.response.id.clone()), @@ -2776,8 +2776,8 @@ impl<F, T> Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data, - mandate_reference, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: network_transaction_id, connector_response_reference_id: Some(item.response.id), @@ -3270,7 +3270,7 @@ pub struct MitExemption { #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(untagged)] pub enum LatestAttempt { - PaymentIntentAttempt(LatestPaymentAttempt), + PaymentIntentAttempt(Box<LatestPaymentAttempt>), SetupAttempt(String), } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] @@ -3480,8 +3480,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme } else { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: Some(connector_metadata), network_txn_id: None, connector_response_reference_id: Some(item.response.id.clone()), diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index fbff19fd0ad..3b109a7f02e 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -727,8 +727,8 @@ fn handle_cards_response( }; let payment_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(response.instance_id.clone()), - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -754,11 +754,11 @@ fn handle_bank_redirects_response( resource_id: types::ResponseId::ConnectorTransactionId( response.payment_request_id.to_string(), ), - redirection_data: Some(services::RedirectForm::from(( + redirection_data: Box::new(Some(services::RedirectForm::from(( response.gateway_url, services::Method::Get, - ))), - mandate_reference: None, + )))), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -791,8 +791,8 @@ fn handle_bank_redirects_error_response( }); let payment_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -852,8 +852,8 @@ fn handle_bank_redirects_sync_response( .payment_request_id .clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -900,8 +900,8 @@ pub fn handle_webhook_response( }; let payment_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs index 999b81a2ff9..4dd455d0da3 100644 --- a/crates/router/src/connector/wellsfargo/transformers.rs +++ b/crates/router/src/connector/wellsfargo/transformers.rs @@ -1791,8 +1791,8 @@ fn get_payment_response( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), - redirection_data: None, - mandate_reference, + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: info_response.processor_information.as_ref().and_then( |processor_information| processor_information.network_transaction_id.clone(), @@ -2003,8 +2003,8 @@ impl resource_id: types::ResponseId::ConnectorTransactionId( item.response.id.clone(), ), - redirection_data: None, - mandate_reference, + redirection_data: Box::new(None), + mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: item.response.processor_information.as_ref().and_then( |processor_information| { @@ -2141,8 +2141,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( item.response.id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item @@ -2163,8 +2163,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( item.response.id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.id), diff --git a/crates/router/src/connector/wellsfargopayout/transformers.rs b/crates/router/src/connector/wellsfargopayout/transformers.rs index e335c3cf59a..135cb5f53cb 100644 --- a/crates/router/src/connector/wellsfargopayout/transformers.rs +++ b/crates/router/src/connector/wellsfargopayout/transformers.rs @@ -134,8 +134,8 @@ impl<F, T> status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index 777594a4534..79147a35b5e 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -260,8 +260,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR response, Some(data.request.connector_transaction_id.clone()), ))?, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: optional_correlation_id, @@ -403,8 +403,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: data.request.connector_transaction_id.clone(), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: optional_correlation_id, @@ -506,8 +506,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme response, Some(data.request.connector_transaction_id.clone()), ))?, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: optional_correlation_id, diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index fee004a6e4c..efdd0fa6878 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -485,8 +485,8 @@ impl<F, T> router_data.response, optional_correlation_id.clone(), ))?, - redirection_data, - mandate_reference: None, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: optional_correlation_id.clone(), diff --git a/crates/router/src/connector/zsl/transformers.rs b/crates/router/src/connector/zsl/transformers.rs index c8758f5322c..d6f9117d786 100644 --- a/crates/router/src/connector/zsl/transformers.rs +++ b/crates/router/src/connector/zsl/transformers.rs @@ -328,12 +328,12 @@ impl<F, T> status: enums::AttemptStatus::AuthenticationPending, // Redirect is always expected after success response response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirection_data: Some(services::RedirectForm::Form { + redirection_data: Box::new(Some(services::RedirectForm::Form { endpoint: redirect_url, method: services::Method::Get, form_fields: HashMap::new(), - }), - mandate_reference: None, + })), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.mer_ref.clone()), @@ -451,8 +451,8 @@ impl<F> resource_id: types::ResponseId::ConnectorTransactionId( item.response.txn_id.clone(), ), - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.mer_ref.clone()), diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 545f94cfeb4..f49f4096340 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -2122,7 +2122,7 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect Ok(storage::MerchantConnectorAccountUpdate::Update { connector_type: Some(self.connector_type), connector_label: self.connector_label.clone(), - connector_account_details: encrypted_data.connector_account_details, + connector_account_details: Box::new(encrypted_data.connector_account_details), disabled, payment_methods_enabled, metadata: self.metadata, @@ -2136,10 +2136,10 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect None => None, }, applepay_verified_domains: None, - pm_auth_config: self.pm_auth_config, + pm_auth_config: Box::new(self.pm_auth_config), status: Some(connector_status), - additional_merchant_data: encrypted_data.additional_merchant_data, - connector_wallets_details: encrypted_data.connector_wallets_details, + additional_merchant_data: Box::new(encrypted_data.additional_merchant_data), + connector_wallets_details: Box::new(encrypted_data.connector_wallets_details), }) } } @@ -2291,25 +2291,27 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect connector_name: None, merchant_connector_id: None, connector_label: self.connector_label.clone(), - connector_account_details: encrypted_data.connector_account_details, + connector_account_details: Box::new(encrypted_data.connector_account_details), test_mode: self.test_mode, disabled, payment_methods_enabled, metadata: self.metadata, frm_configs, connector_webhook_details: match &self.connector_webhook_details { - Some(connector_webhook_details) => connector_webhook_details - .encode_to_value() - .change_context(errors::ApiErrorResponse::InternalServerError) - .map(Some)? - .map(Secret::new), - None => None, + Some(connector_webhook_details) => Box::new( + connector_webhook_details + .encode_to_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .map(Some)? + .map(Secret::new), + ), + None => Box::new(None), }, applepay_verified_domains: None, - pm_auth_config: self.pm_auth_config, + pm_auth_config: Box::new(self.pm_auth_config), status: Some(connector_status), - additional_merchant_data: encrypted_data.additional_merchant_data, - connector_wallets_details: encrypted_data.connector_wallets_details, + additional_merchant_data: Box::new(encrypted_data.additional_merchant_data), + connector_wallets_details: Box::new(encrypted_data.connector_wallets_details), }) } } diff --git a/crates/router/src/core/connector_onboarding.rs b/crates/router/src/core/connector_onboarding.rs index c3de228d9a7..5813a5bcd0c 100644 --- a/crates/router/src/core/connector_onboarding.rs +++ b/crates/router/src/core/connector_onboarding.rs @@ -95,7 +95,7 @@ pub async fn sync_onboarding_status( .await?; return Ok(ApplicationResponse::Json(api::OnboardingStatus::PayPal( - api::PayPalOnboardingStatus::ConnectorIntegrated(update_mca_data), + api::PayPalOnboardingStatus::ConnectorIntegrated(Box::new(update_mca_data)), ))); } Ok(ApplicationResponse::Json(status)) diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 19fbbf1952b..18cc8682eee 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -662,7 +662,7 @@ impl CustomerDeleteBridge for customers::GlobalId { description: Some(Description::from_str_unchecked(REDACTED)), phone_country_code: Some(REDACTED.to_string()), metadata: None, - connector_customer: None, + connector_customer: Box::new(None), default_billing_address: None, default_shipping_address: None, default_payment_method_id: None, @@ -904,7 +904,7 @@ impl CustomerDeleteBridge for customers::CustomerId { description: Some(Description::from_str_unchecked(REDACTED)), phone_country_code: Some(REDACTED.to_string()), metadata: None, - connector_customer: None, + connector_customer: Box::new(None), address_id: None, }; @@ -1204,7 +1204,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), description: self.description.clone(), - connector_customer: None, + connector_customer: Box::new(None), address_id: address.clone().map(|addr| addr.address_id), }, key_store, @@ -1296,7 +1296,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), description: self.description.clone(), - connector_customer: None, + connector_customer: Box::new(None), default_billing_address: encrypted_customer_billing_address.map(Into::into), default_shipping_address: encrypted_customer_shipping_address.map(Into::into), default_payment_method_id: Some(self.default_payment_method_id.clone()), diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index b5707979247..5ed3e910563 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -357,10 +357,10 @@ where network_txn_id, .. } => (mandate_reference.clone(), network_txn_id.clone()), - _ => (None, None), + _ => (Box::new(None), None), }; - let mandate_ids = mandate_reference + let mandate_ids = (*mandate_reference) .as_ref() .map(|md| { md.encode_to_value() @@ -379,7 +379,7 @@ where mandate_ids, network_txn_id, get_insensitive_payment_method_data_if_exists(resp), - mandate_reference, + *mandate_reference, merchant_connector_id, )? else { @@ -439,7 +439,7 @@ impl ForeignFrom<Result<types::PaymentsResponseData, types::ErrorResponse>> match resp { Ok(types::PaymentsResponseData::TransactionResponse { mandate_reference, .. - }) => mandate_reference, + }) => *mandate_reference, _ => None, } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 2218197743a..b4acb98a7d4 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3071,9 +3071,9 @@ where let should_continue = matches!( router_data.response, Ok(router_types::PaymentsResponseData::TransactionResponse { - redirection_data: None, + ref redirection_data, .. - }) + }) if redirection_data.is_none() ) && router_data.status != common_enums::AttemptStatus::AuthenticationFailed; (router_data, should_continue) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 51cb5793adb..0de7683097b 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1620,7 +1620,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>( phone: Box::new(encryptable_customer.phone), phone_country_code: request_customer_details.phone_country_code, description: None, - connector_customer: None, + connector_customer: Box::new(None), metadata: None, address_id: None, }; @@ -3581,7 +3581,7 @@ pub async fn insert_merchant_connector_creds_to_config( #[derive(Clone)] pub enum MerchantConnectorAccountType { - DbVal(domain::MerchantConnectorAccount), + DbVal(Box<domain::MerchantConnectorAccount>), CacheVal(api_models::admin::MerchantConnectorDetails), } @@ -3795,7 +3795,7 @@ pub async fn get_merchant_connector_account( todo!() } }; - mca.map(MerchantConnectorAccountType::DbVal) + mca.map(Box::new).map(MerchantConnectorAccountType::DbVal) } } } diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 74339a88fb6..69cf19b09bb 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1496,7 +1496,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .event(AuditEvent::new(AuditEventType::PaymentConfirm { client_src, client_ver, - frm_message, + frm_message: Box::new(frm_message), })) .with(payment_data.to_event()) .emit(); diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index ae64fe41b1f..3e115ee74f0 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1500,7 +1500,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( let encoded_data = payment_data.payment_attempt.encoded_data.clone(); - let authentication_data = redirection_data + let authentication_data = (*redirection_data) .as_ref() .map(Encode::encode_to_value) .transpose() diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 060e93474b4..7fdccf9c60f 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -424,7 +424,7 @@ where }) => { let encoded_data = payment_data.get_payment_attempt().encoded_data.clone(); - let authentication_data = redirection_data + let authentication_data = (*redirection_data) .as_ref() .map(Encode::encode_to_value) .transpose() diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index b4e5ade5698..9809d40f7f6 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -157,10 +157,9 @@ where let (connector_mandate_id, mandate_metadata) = match responses { types::PaymentsResponseData::TransactionResponse { - ref mandate_reference, - .. + mandate_reference, .. } => { - if let Some(mandate_ref) = mandate_reference { + if let Some(ref mandate_ref) = *mandate_reference { ( mandate_ref.connector_mandate_id.clone(), mandate_ref.mandate_metadata.clone(), diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 58ea3b43462..66e5c996d34 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -436,8 +436,8 @@ where // [#44]: why should response be filled during request let response = Ok(types::PaymentsResponseData::TransactionResponse { resource_id, - redirection_data: None, - mandate_reference: None, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index c1b8f78eeb1..02c619b68d9 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -375,7 +375,7 @@ pub async fn payouts_confirm_core( &merchant_account, None, &key_store, - &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()), + &payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())), locale, ) .await?; @@ -448,7 +448,7 @@ pub async fn payouts_update_core( &merchant_account, None, &key_store, - &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()), + &payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())), locale, ) .await?; diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs index 8193109c250..a51b6c86a34 100644 --- a/crates/router/src/core/verification/utils.rs +++ b/crates/router/src/core/verification/utils.rs @@ -68,36 +68,36 @@ pub async fn check_existence_and_add_domain_to_db( let updated_mca = storage::MerchantConnectorAccountUpdate::Update { connector_type: None, connector_name: None, - connector_account_details: None, + connector_account_details: Box::new(None), test_mode: None, disabled: None, merchant_connector_id: None, payment_methods_enabled: None, metadata: None, frm_configs: None, - connector_webhook_details: None, + connector_webhook_details: Box::new(None), applepay_verified_domains: Some(already_verified_domains.clone()), - pm_auth_config: None, + pm_auth_config: Box::new(None), connector_label: None, status: None, - connector_wallets_details: None, - additional_merchant_data: None, + connector_wallets_details: Box::new(None), + additional_merchant_data: Box::new(None), }; #[cfg(feature = "v2")] let updated_mca = storage::MerchantConnectorAccountUpdate::Update { connector_type: None, - connector_account_details: None, + connector_account_details: Box::new(None), disabled: None, payment_methods_enabled: None, metadata: None, frm_configs: None, connector_webhook_details: None, applepay_verified_domains: Some(already_verified_domains.clone()), - pm_auth_config: None, + pm_auth_config: Box::new(None), connector_label: None, status: None, - connector_wallets_details: None, - additional_merchant_data: None, + connector_wallets_details: Box::new(None), + additional_merchant_data: Box::new(None), }; state .store diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 66de5106e6f..3627438547c 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -613,7 +613,7 @@ async fn payments_incoming_webhook_flow( enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, - api::OutgoingWebhookContent::PaymentDetails(payments_response), + api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), primary_object_created_at, )) .await?; @@ -745,7 +745,7 @@ async fn payouts_incoming_webhook_flow( enums::EventClass::Payouts, updated_payout_attempt.payout_id.clone(), enums::EventObjectType::PayoutDetails, - api::OutgoingWebhookContent::PayoutDetails(payout_create_response), + api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)), Some(updated_payout_attempt.created_at), )) .await?; @@ -852,7 +852,7 @@ async fn refunds_incoming_webhook_flow( enums::EventClass::Refunds, refund_id, enums::EventObjectType::RefundDetails, - api::OutgoingWebhookContent::RefundDetails(refund_response), + api::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)), Some(updated_refund.created_at), )) .await?; @@ -1128,7 +1128,9 @@ async fn external_authentication_incoming_webhook_flow( enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, - api::OutgoingWebhookContent::PaymentDetails(payments_response), + api::OutgoingWebhookContent::PaymentDetails(Box::new( + payments_response, + )), primary_object_created_at, )) .await?; @@ -1334,7 +1336,7 @@ async fn frm_incoming_webhook_flow( enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, - api::OutgoingWebhookContent::PaymentDetails(payments_response), + api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), primary_object_created_at, )) .await?; @@ -1498,7 +1500,7 @@ async fn bank_transfer_webhook_flow( enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, - api::OutgoingWebhookContent::PaymentDetails(payments_response), + api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), primary_object_created_at, )) .await?; diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs index fbf69278357..0a9c17ed3a0 100644 --- a/crates/router/src/core/webhooks/outgoing.rs +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -361,7 +361,7 @@ async fn trigger_webhook_to_merchant( &event_id, client_error, delivery_attempt, - ScheduleWebhookRetry::WithProcessTracker(process_tracker), + ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)), ) .await?; } @@ -391,7 +391,7 @@ async fn trigger_webhook_to_merchant( delivery_attempt, status_code.as_u16(), "An error occurred when sending webhook to merchant", - ScheduleWebhookRetry::WithProcessTracker(process_tracker), + ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)), ) .await?; } @@ -668,7 +668,7 @@ pub(crate) fn get_outgoing_webhook_request( #[derive(Debug)] enum ScheduleWebhookRetry { - WithProcessTracker(storage::ProcessTracker), + WithProcessTracker(Box<storage::ProcessTracker>), NoSchedule, } @@ -757,7 +757,7 @@ async fn api_client_error_handler( outgoing_webhook_retry::retry_webhook_delivery_task( &*state.store, merchant_id, - process_tracker, + *process_tracker, ) .await .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?; @@ -903,7 +903,7 @@ async fn error_response_handler( outgoing_webhook_retry::retry_webhook_delivery_task( &*state.store, merchant_id, - process_tracker, + *process_tracker, ) .await .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?; diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index 8680e43eff3..3d71f5f5553 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -64,7 +64,7 @@ pub async fn construct_webhook_router_data<'a>( request_details: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ApiErrorResponse> { let auth_type: types::ConnectorAuthType = - helpers::MerchantConnectorAccountType::DbVal(merchant_connector_account.clone()) + helpers::MerchantConnectorAccountType::DbVal(Box::new(merchant_connector_account.clone())) .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rs index 34a7c69d91a..64b52b7995e 100644 --- a/crates/router/src/core/webhooks/webhook_events.rs +++ b/crates/router/src/core/webhooks/webhook_events.rs @@ -14,8 +14,8 @@ const INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT: i64 = 100; #[derive(Debug)] enum MerchantAccountOrProfile { - MerchantAccount(domain::MerchantAccount), - Profile(domain::Profile), + MerchantAccount(Box<domain::MerchantAccount>), + Profile(Box<domain::Profile>), } #[instrument(skip(state))] @@ -302,7 +302,7 @@ async fn get_account_and_key_store( })?; Ok(( - MerchantAccountOrProfile::Profile(business_profile), + MerchantAccountOrProfile::Profile(Box::new(business_profile)), merchant_key_store, )) } @@ -318,7 +318,7 @@ async fn get_account_and_key_store( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok(( - MerchantAccountOrProfile::MerchantAccount(merchant_account), + MerchantAccountOrProfile::MerchantAccount(Box::new(merchant_account)), merchant_key_store, )) } diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index 3a8750feff9..2e2bb7dccbb 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -493,12 +493,12 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: kv::Updateable::AddressUpdate(Box::new( + updatable: Box::new(kv::Updateable::AddressUpdate(Box::new( kv::AddressUpdateMems { orig: address, update_data: address_update.into(), }, - )), + ))), }, }; @@ -597,7 +597,7 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::Address(Box::new(address_new)), + insertable: Box::new(kv::Insertable::Address(Box::new(address_new))), }, }; diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs index 5020c238e4a..ae23f81e2ea 100644 --- a/crates/router/src/db/customers.rs +++ b/crates/router/src/db/customers.rs @@ -446,10 +446,12 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems { - orig: customer, - update_data: customer_update.into(), - }), + updatable: Box::new(kv::Updateable::CustomerUpdate( + kv::CustomerUpdateMems { + orig: customer, + update_data: customer_update.into(), + }, + )), }, }; @@ -689,7 +691,7 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::Customer(new_customer.clone()), + insertable: Box::new(kv::Insertable::Customer(new_customer.clone())), }, }; let storage_customer = new_customer.into(); @@ -768,7 +770,7 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::Customer(new_customer.clone()), + insertable: Box::new(kv::Insertable::Customer(new_customer.clone())), }, }; let storage_customer = new_customer.into(); @@ -931,10 +933,12 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems { - orig: customer, - update_data: customer_update.into(), - }), + updatable: Box::new(kv::Updateable::CustomerUpdate( + kv::CustomerUpdateMems { + orig: customer, + update_data: customer_update.into(), + }, + )), }, }; diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs index 95733805b43..076cb768e61 100644 --- a/crates/router/src/db/mandate.rs +++ b/crates/router/src/db/mandate.rs @@ -274,10 +274,12 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: kv::Updateable::MandateUpdate(kv::MandateUpdateMems { - orig: mandate, - update_data: m_update, - }), + updatable: Box::new(kv::Updateable::MandateUpdate( + kv::MandateUpdateMems { + orig: mandate, + update_data: m_update, + }, + )), }, }; @@ -346,7 +348,7 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::Mandate(mandate), + insertable: Box::new(kv::Insertable::Mandate(mandate)), }, }; diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index e75fb940a35..ac66ed707f1 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -496,7 +496,7 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::PaymentMethod(payment_method_new), + insertable: Box::new(kv::Insertable::PaymentMethod(payment_method_new)), }, }; @@ -588,12 +588,12 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: kv::Updateable::PaymentMethodUpdate( + updatable: Box::new(kv::Updateable::PaymentMethodUpdate(Box::new( kv::PaymentMethodUpdateMems { orig: payment_method, update_data: p_update, }, - ), + ))), }, }; diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 41cb3cef5c6..745170d7075 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -445,7 +445,7 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::Refund(new), + insertable: Box::new(kv::Insertable::Refund(new)), }, }; @@ -617,10 +617,12 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: kv::Updateable::RefundUpdate(kv::RefundUpdateMems { - orig: this, - update_data: refund, - }), + updatable: Box::new(kv::Updateable::RefundUpdate( + kv::RefundUpdateMems { + orig: this, + update_data: refund, + }, + )), }, }; diff --git a/crates/router/src/db/reverse_lookup.rs b/crates/router/src/db/reverse_lookup.rs index 06bd84675b1..c022c70d9e2 100644 --- a/crates/router/src/db/reverse_lookup.rs +++ b/crates/router/src/db/reverse_lookup.rs @@ -116,7 +116,7 @@ mod storage { }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::ReverseLookUp(new), + insertable: Box::new(kv::Insertable::ReverseLookUp(new)), }, }; diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs index 367a573a93b..9b7a688f7eb 100644 --- a/crates/router/src/events/audit_events.rs +++ b/crates/router/src/events/audit_events.rs @@ -18,7 +18,7 @@ pub enum AuditEventType { PaymentConfirm { client_src: Option<String>, client_ver: Option<String>, - frm_message: Option<FraudCheck>, + frm_message: Box<Option<FraudCheck>>, }, PaymentCancelled { cancellation_reason: Option<String>, diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index a54c2bc8ad6..f56a741dc1a 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -1166,9 +1166,9 @@ where diesel_models::enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), diesel_models::enums::EventObjectType::PaymentDetails, - webhooks::OutgoingWebhookContent::PaymentDetails( + webhooks::OutgoingWebhookContent::PaymentDetails(Box::new( payments_response_json, - ), + )), primary_object_created_at, )) .await diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs index eb4530bbe54..1bfcc8ebe7b 100644 --- a/crates/router/src/workflows/outgoing_webhook_retry.rs +++ b/crates/router/src/workflows/outgoing_webhook_retry.rs @@ -423,7 +423,7 @@ async fn get_outgoing_webhook_content_and_event_type( logger::debug!(current_resource_status=%payments_response.status); Ok(( - OutgoingWebhookContent::PaymentDetails(payments_response), + OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), event_type, )) } @@ -449,7 +449,7 @@ async fn get_outgoing_webhook_content_and_event_type( let refund_response = RefundResponse::foreign_from(refund); Ok(( - OutgoingWebhookContent::RefundDetails(refund_response), + OutgoingWebhookContent::RefundDetails(Box::new(refund_response)), event_type, )) } @@ -548,7 +548,7 @@ async fn get_outgoing_webhook_content_and_event_type( logger::debug!(current_resource_status=%payout_data.payout_attempt.status); Ok(( - OutgoingWebhookContent::PayoutDetails(payout_create_response), + OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)), event_type, )) } diff --git a/crates/storage_impl/src/lookup.rs b/crates/storage_impl/src/lookup.rs index 54377e45267..eec85e267b9 100644 --- a/crates/storage_impl/src/lookup.rs +++ b/crates/storage_impl/src/lookup.rs @@ -93,7 +93,7 @@ impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> { }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::ReverseLookUp(new), + insertable: Box::new(kv::Insertable::ReverseLookUp(new)), }, }; diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 36a9da5944b..552630a0f76 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -538,9 +538,9 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::PaymentAttempt( + insertable: Box::new(kv::Insertable::PaymentAttempt(Box::new( payment_attempt.to_storage_model(), - ), + ))), }, }; @@ -645,12 +645,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: kv::Updateable::PaymentAttemptUpdate( + updatable: Box::new(kv::Updateable::PaymentAttemptUpdate(Box::new( kv::PaymentAttemptUpdateMems { orig: this.clone().to_storage_model(), update_data: payment_attempt.to_storage_model(), }, - ), + ))), }, }; diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 8ca63e79037..3fcd30f1e89 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -103,7 +103,9 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::PaymentIntent(new_payment_intent), + insertable: Box::new(kv::Insertable::PaymentIntent(Box::new( + new_payment_intent, + ))), }, }; @@ -219,12 +221,12 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: kv::Updateable::PaymentIntentUpdate( + updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new( kv::PaymentIntentUpdateMems { orig: origin_diesel_intent, update_data: diesel_intent_update, }, - ), + ))), }, }; diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs index 81d06a1cbd5..3ac66a2c301 100644 --- a/crates/storage_impl/src/payouts/payout_attempt.rs +++ b/crates/storage_impl/src/payouts/payout_attempt.rs @@ -93,9 +93,9 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> { let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::PayoutAttempt( + insertable: Box::new(kv::Insertable::PayoutAttempt( new_payout_attempt.to_storage_model(), - ), + )), }, }; @@ -182,12 +182,12 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: kv::Updateable::PayoutAttemptUpdate( + updatable: Box::new(kv::Updateable::PayoutAttemptUpdate( kv::PayoutAttemptUpdateMems { orig: origin_diesel_payout, update_data: diesel_payout_update, }, - ), + )), }, }; diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs index 9a94743da3f..2f6540732fd 100644 --- a/crates/storage_impl/src/payouts/payouts.rs +++ b/crates/storage_impl/src/payouts/payouts.rs @@ -130,7 +130,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { - insertable: kv::Insertable::Payouts(new.to_storage_model()), + insertable: Box::new(kv::Insertable::Payouts(new.to_storage_model())), }, }; @@ -201,10 +201,10 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: kv::Updateable::PayoutsUpdate(kv::PayoutsUpdateMems { + updatable: Box::new(kv::Updateable::PayoutsUpdate(kv::PayoutsUpdateMems { orig: origin_diesel_payout, update_data: diesel_payout_update, - }), + })), }, };
2024-10-22T13:48:39Z
## Description <!-- Describe your changes in detail --> This PR addresses the clippy lints occurring due to new rust version 1.82.0. Majorly addresses below warning - ![image](https://github.com/user-attachments/assets/f3f154e7-4062-4b48-a71b-ea5a2ea61e94) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This PR addresses clippy lint due to new rust version. So basic sanity testing should suffice.
673b8691e092e145ba211050db4f5c7e021a0ce2
This PR addresses clippy lint due to new rust version. So basic sanity testing should suffice.
[ "add_connector.md", "connector-template/transformers.rs", "crates/api_models/src/connector_onboarding.rs", "crates/api_models/src/payouts.rs", "crates/api_models/src/webhooks.rs", "crates/diesel_models/src/kv.rs", "crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs", "crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs", "crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs", "crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs", "crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs", "crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs", "crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs", "crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs", "crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs", "crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs", "crates/hyperswitch_connectors/src/connectors/forte/transformers.rs", "crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs", "crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs", "crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs", "crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs", "crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs", "crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs", "crates/hyperswitch_connectors/src/connectors/payu/transformers.rs", "crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs", "crates/hyperswitch_connectors/src/connectors/square/transformers.rs", "crates/hyperswitch_connectors/src/connectors/stax/transformers.rs", "crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs", "crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs", "crates/hyperswitch_connectors/src/connectors/volt/transformers.rs", "crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs", "crates/hyperswitch_connectors/src/connectors/zen/transformers.rs", "crates/hyperswitch_domain_models/src/customer.rs", "crates/hyperswitch_domain_models/src/merchant_connector_account.rs", "crates/hyperswitch_domain_models/src/router_response_types.rs", "crates/router/src/compatibility/stripe/webhooks.rs", "crates/router/src/connector/aci/transformers.rs", "crates/router/src/connector/adyen/transformers.rs", "crates/router/src/connector/airwallex/transformers.rs", "crates/router/src/connector/authorizedotnet/transformers.rs", "crates/router/src/connector/bamboraapac/transformers.rs", "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/bluesnap.rs", "crates/router/src/connector/bluesnap/transformers.rs", "crates/router/src/connector/boku/transformers.rs", "crates/router/src/connector/braintree/transformers.rs", "crates/router/src/connector/checkout/transformers.rs", "crates/router/src/connector/cybersource/transformers.rs", "crates/router/src/connector/datatrans/transformers.rs", "crates/router/src/connector/dummyconnector/transformers.rs", "crates/router/src/connector/globalpay/transformers.rs", "crates/router/src/connector/gocardless/transformers.rs", "crates/router/src/connector/iatapay/transformers.rs", "crates/router/src/connector/itaubank/transformers.rs", "crates/router/src/connector/klarna/transformers.rs", "crates/router/src/connector/mifinity/transformers.rs", "crates/router/src/connector/multisafepay/transformers.rs", "crates/router/src/connector/nmi/transformers.rs", "crates/router/src/connector/noon/transformers.rs", "crates/router/src/connector/nuvei/transformers.rs", "crates/router/src/connector/opayo/transformers.rs", "crates/router/src/connector/opennode/transformers.rs", "crates/router/src/connector/paybox/transformers.rs", "crates/router/src/connector/payme/transformers.rs", "crates/router/src/connector/paypal.rs", "crates/router/src/connector/paypal/transformers.rs", "crates/router/src/connector/placetopay/transformers.rs", "crates/router/src/connector/plaid/transformers.rs", "crates/router/src/connector/prophetpay/transformers.rs", "crates/router/src/connector/rapyd/transformers.rs", "crates/router/src/connector/razorpay/transformers.rs", "crates/router/src/connector/shift4/transformers.rs", "crates/router/src/connector/stripe/transformers.rs", "crates/router/src/connector/trustpay/transformers.rs", "crates/router/src/connector/wellsfargo/transformers.rs", "crates/router/src/connector/wellsfargopayout/transformers.rs", "crates/router/src/connector/worldpay.rs", "crates/router/src/connector/worldpay/transformers.rs", "crates/router/src/connector/zsl/transformers.rs", "crates/router/src/core/admin.rs", "crates/router/src/core/connector_onboarding.rs", "crates/router/src/core/customers.rs", "crates/router/src/core/mandate.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/operations/payment_confirm.rs", "crates/router/src/core/payments/operations/payment_response.rs", "crates/router/src/core/payments/retry.rs", "crates/router/src/core/payments/tokenization.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/core/payouts.rs", "crates/router/src/core/verification/utils.rs", "crates/router/src/core/webhooks/incoming.rs", "crates/router/src/core/webhooks/outgoing.rs", "crates/router/src/core/webhooks/utils.rs", "crates/router/src/core/webhooks/webhook_events.rs", "crates/router/src/db/address.rs", "crates/router/src/db/customers.rs", "crates/router/src/db/mandate.rs", "crates/router/src/db/payment_method.rs", "crates/router/src/db/refund.rs", "crates/router/src/db/reverse_lookup.rs", "crates/router/src/events/audit_events.rs", "crates/router/src/utils.rs", "crates/router/src/workflows/outgoing_webhook_retry.rs", "crates/storage_impl/src/lookup.rs", "crates/storage_impl/src/payments/payment_attempt.rs", "crates/storage_impl/src/payments/payment_intent.rs", "crates/storage_impl/src/payouts/payout_attempt.rs", "crates/storage_impl/src/payouts/payouts.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6398
Bug: fix(payments): total count issue for card-network filter To close issue https://github.com/juspay/hyperswitch-cloud/issues/7206
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index fd1286a555e..4fb5aaf28f2 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4585,6 +4585,7 @@ impl PaymentListFilterConstraints { && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() + && self.card_network.is_none() } } diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index 0627fa0048a..b4854e14923 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -382,6 +382,7 @@ impl PaymentAttempt { payment_method_type: Option<Vec<enums::PaymentMethodType>>, authentication_type: Option<Vec<enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, + card_network: Option<Vec<enums::CardNetwork>>, ) -> StorageResult<i64> { let mut filter = <Self as HasTable>::table() .count() @@ -405,6 +406,9 @@ impl PaymentAttempt { if let Some(merchant_connector_id) = merchant_connector_id { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id)) } + if let Some(card_network) = card_network { + filter = filter.filter(dsl::card_network.eq_any(card_network)) + } router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 8ecac77e54e..635c9744c56 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -159,6 +159,7 @@ pub trait PaymentAttemptInterface { payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>, authentication_type: Option<Vec<storage_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, + card_network: Option<Vec<storage_enums::CardNetwork>>, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<i64, errors::StorageError>; } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index fd45c475b6d..c37fd2af109 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3888,6 +3888,7 @@ pub async fn apply_filters_on_payments( constraints.payment_method_type, constraints.authentication_type, constraints.merchant_connector_id, + constraints.card_network, merchant.storage_scheme, ) .await diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 3ef9a2d0376..029a84ad500 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1601,6 +1601,7 @@ impl PaymentAttemptInterface for KafkaStore { payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, + card_network: Option<Vec<common_enums::CardNetwork>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::DataStorageError> { self.diesel_store @@ -1612,6 +1613,7 @@ impl PaymentAttemptInterface for KafkaStore { payment_method_type, authentication_type, merchant_connector_id, + card_network, storage_scheme, ) .await diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 121397cdfb9..a0c0a095084 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -52,6 +52,7 @@ impl PaymentAttemptInterface for MockDb { _payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, _authentication_type: Option<Vec<common_enums::AuthenticationType>>, _merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, + _card_network: Option<Vec<storage_enums::CardNetwork>>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<i64, StorageError> { Err(StorageError::MockDbError)? diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 5087e28b854..78f5b191635 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -406,6 +406,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, + card_network: Option<Vec<common_enums::CardNetwork>>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = self @@ -429,6 +430,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { payment_method_type, authentication_type, merchant_connector_id, + card_network, ) .await .map_err(|er| { @@ -1291,6 +1293,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, + card_network: Option<Vec<common_enums::CardNetwork>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.router_store @@ -1302,6 +1305,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { payment_method_type, authentication_type, merchant_connector_id, + card_network, storage_scheme, ) .await
2024-10-22T12:47:21Z
## Description <!-- Describe your changes in detail --> The total count in the payments response was incorrect when the card-network filter was applied. With this PR, the count will now be accurately filtered as well. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes issues https://github.com/juspay/hyperswitch-cloud/issues/7206 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Request : ``` curl 'http://localhost:8080/payments/list' \ -H 'authorization: Bearer JWT token' \ -H 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --data-raw '{"offset":0,"limit":50,"start_time":"2024-09-21T18:30:00Z","card_network":["Visa"]}' ``` Response Lets say the total number of payments are 50 , when you apply filter the total_count and count should come as the filtered number . For Eg: When card-network filter = Visa , then the count = 4 and total_count =4 ``` { "count": 4, "total_count": 4, "data": [ { "payment_id": "test_RoHcgHs3m6ZsJ0Y5MEMU", "merchant_id": "merchant_1729190909", "status": "failed", "amount": 10200, "net_amount": 10200, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "test_RoHcgHs3m6ZsJ0Y5MEMU_secret_wQHDmUUPatRIfmY8P8VO", "created": "2024-10-22T00:08:58.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_RoHcgHs3m6ZsJ0Y5MEMU_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lqOYR8GAg2uTrz5WaqA5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null }, { "payment_id": "test_EEe6rS8Mkv2vVDxZWowp", "merchant_id": "merchant_1729190909", "status": "succeeded", "amount": 18600, "net_amount": 18600, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "test_EEe6rS8Mkv2vVDxZWowp_secret_fvEF0uo7CYqPOgasFSrQ", "created": "2024-10-21T02:51:29.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_EEe6rS8Mkv2vVDxZWowp_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lqOYR8GAg2uTrz5WaqA5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null }, { "payment_id": "test_46x3ZcQVz6U9RtJitDO4", "merchant_id": "merchant_1729190909", "status": "succeeded", "amount": 18200, "net_amount": 18200, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "test_46x3ZcQVz6U9RtJitDO4_secret_hrOArvzAKBpwXvShhHo4", "created": "2024-10-20T18:06:38.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_46x3ZcQVz6U9RtJitDO4_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lqOYR8GAg2uTrz5WaqA5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null }, { "payment_id": "test_pghhoGT9kuPuXf2yopXO", "merchant_id": "merchant_1729190909", "status": "succeeded", "amount": 11800, "net_amount": 11800, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "paypal_test", "client_secret": "test_pghhoGT9kuPuXf2yopXO_secret_R0uu1JcxCBN1UFyMDVal", "created": "2024-10-16T05:26:35.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_pghhoGT9kuPuXf2yopXO_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lqOYR8GAg2uTrz5WaqA5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ] } ```
26e0c32f4da5689a1c01fbb456ac008a0b831710
Request : ``` curl 'http://localhost:8080/payments/list' \ -H 'authorization: Bearer JWT token' \ -H 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --data-raw '{"offset":0,"limit":50,"start_time":"2024-09-21T18:30:00Z","card_network":["Visa"]}' ``` Response Lets say the total number of payments are 50 , when you apply filter the total_count and count should come as the filtered number . For Eg: When card-network filter = Visa , then the count = 4 and total_count =4 ``` { "count": 4, "total_count": 4, "data": [ { "payment_id": "test_RoHcgHs3m6ZsJ0Y5MEMU", "merchant_id": "merchant_1729190909", "status": "failed", "amount": 10200, "net_amount": 10200, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "test_RoHcgHs3m6ZsJ0Y5MEMU_secret_wQHDmUUPatRIfmY8P8VO", "created": "2024-10-22T00:08:58.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_RoHcgHs3m6ZsJ0Y5MEMU_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lqOYR8GAg2uTrz5WaqA5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null }, { "payment_id": "test_EEe6rS8Mkv2vVDxZWowp", "merchant_id": "merchant_1729190909", "status": "succeeded", "amount": 18600, "net_amount": 18600, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "test_EEe6rS8Mkv2vVDxZWowp_secret_fvEF0uo7CYqPOgasFSrQ", "created": "2024-10-21T02:51:29.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_EEe6rS8Mkv2vVDxZWowp_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lqOYR8GAg2uTrz5WaqA5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null }, { "payment_id": "test_46x3ZcQVz6U9RtJitDO4", "merchant_id": "merchant_1729190909", "status": "succeeded", "amount": 18200, "net_amount": 18200, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "test_46x3ZcQVz6U9RtJitDO4_secret_hrOArvzAKBpwXvShhHo4", "created": "2024-10-20T18:06:38.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_46x3ZcQVz6U9RtJitDO4_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lqOYR8GAg2uTrz5WaqA5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null }, { "payment_id": "test_pghhoGT9kuPuXf2yopXO", "merchant_id": "merchant_1729190909", "status": "succeeded", "amount": 11800, "net_amount": 11800, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "paypal_test", "client_secret": "test_pghhoGT9kuPuXf2yopXO_secret_R0uu1JcxCBN1UFyMDVal", "created": "2024-10-16T05:26:35.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_pghhoGT9kuPuXf2yopXO_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lqOYR8GAg2uTrz5WaqA5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ] } ```
[ "crates/api_models/src/payments.rs", "crates/diesel_models/src/query/payment_attempt.rs", "crates/hyperswitch_domain_models/src/payments/payment_attempt.rs", "crates/router/src/core/payments.rs", "crates/router/src/db/kafka_store.rs", "crates/storage_impl/src/mock_db/payment_attempt.rs", "crates/storage_impl/src/payments/payment_attempt.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6395
Bug: [FEATURE] add payments get-intent API for v2 # Feature Description Add payments `get-intent` API for v2
diff --git a/api-reference-v2/api-reference/payments/payments--get-intent.mdx b/api-reference-v2/api-reference/payments/payments--get-intent.mdx new file mode 100644 index 00000000000..cd1321be217 --- /dev/null +++ b/api-reference-v2/api-reference/payments/payments--get-intent.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/payments/{id}/get-intent +--- \ No newline at end of file diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json index 974e530f311..17dd6dfb7ff 100644 --- a/api-reference-v2/mint.json +++ b/api-reference-v2/mint.json @@ -38,6 +38,7 @@ "group": "Payments", "pages": [ "api-reference/payments/payments--create-intent", + "api-reference/payments/payments--get-intent", "api-reference/payments/payments--session-token", "api-reference/payments/payments--confirm-intent" ] diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index bd9de3a2962..bb52eb23938 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -1832,7 +1832,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentsCreateIntentResponse" + "$ref": "#/components/schemas/PaymentsIntentResponse" } } } @@ -1848,6 +1848,47 @@ ] } }, + "/v2/payments/{id}/get-intent": { + "get": { + "tags": [ + "Payments" + ], + "summary": "Payments - Get Intent", + "description": "**Get a payment intent object when id is passed in path**\n\nYou will require the 'API - Key' from the Hyperswitch dashboard to make the call.", + "operationId": "Get the Payment Intent details", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The unique identifier for the Payment Intent", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Payment Intent", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsIntentResponse" + } + } + } + }, + "404": { + "description": "Payment Intent not found" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/v2/payments/{id}/confirm-intent": { "post": { "tags": [ @@ -13567,179 +13608,6 @@ }, "additionalProperties": false }, - "PaymentsCreateIntentResponse": { - "type": "object", - "required": [ - "id", - "amount_details", - "client_secret", - "capture_method", - "authentication_type", - "customer_present", - "setup_future_usage", - "apply_mit_exemption", - "payment_link_enabled", - "request_incremental_authorization", - "expires_on", - "request_external_three_ds_authentication" - ], - "properties": { - "id": { - "type": "string", - "description": "Global Payment Id for the payment" - }, - "amount_details": { - "$ref": "#/components/schemas/AmountDetailsResponse" - }, - "client_secret": { - "type": "string", - "description": "It's a token used for client side verification.", - "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo" - }, - "merchant_reference_id": { - "type": "string", - "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant.", - "example": "pay_mbabizu24mvu3mela5njyhpit4", - "nullable": true, - "maxLength": 30, - "minLength": 30 - }, - "routing_algorithm_id": { - "type": "string", - "description": "The routing algorithm id to be used for the payment", - "nullable": true - }, - "capture_method": { - "$ref": "#/components/schemas/CaptureMethod" - }, - "authentication_type": { - "allOf": [ - { - "$ref": "#/components/schemas/AuthenticationType" - } - ], - "default": "no_three_ds" - }, - "billing": { - "allOf": [ - { - "$ref": "#/components/schemas/Address" - } - ], - "nullable": true - }, - "shipping": { - "allOf": [ - { - "$ref": "#/components/schemas/Address" - } - ], - "nullable": true - }, - "customer_id": { - "type": "string", - "description": "The identifier for the customer", - "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", - "nullable": true, - "maxLength": 64, - "minLength": 1 - }, - "customer_present": { - "$ref": "#/components/schemas/PresenceOfCustomerDuringPayment" - }, - "description": { - "type": "string", - "description": "A description for the payment", - "example": "It's my first payment request", - "nullable": true - }, - "return_url": { - "type": "string", - "description": "The URL to which you want the user to be redirected after the completion of the payment operation", - "example": "https://hyperswitch.io", - "nullable": true - }, - "setup_future_usage": { - "$ref": "#/components/schemas/FutureUsage" - }, - "apply_mit_exemption": { - "$ref": "#/components/schemas/MitExemptionRequest" - }, - "statement_descriptor": { - "type": "string", - "description": "For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.", - "example": "Hyperswitch Router", - "nullable": true, - "maxLength": 22 - }, - "order_details": { - "type": "array", - "items": { - "$ref": "#/components/schemas/OrderDetailsWithAmount" - }, - "description": "Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount", - "example": "[{\n \"product_name\": \"Apple iPhone 16\",\n \"quantity\": 1,\n \"amount\" : 69000\n \"product_img_link\" : \"https://dummy-img-link.com\"\n }]", - "nullable": true - }, - "allowed_payment_method_types": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PaymentMethodType" - }, - "description": "Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent", - "nullable": true - }, - "metadata": { - "type": "object", - "description": "Metadata is useful for storing additional, unstructured information on an object.", - "nullable": true - }, - "connector_metadata": { - "allOf": [ - { - "$ref": "#/components/schemas/ConnectorMetadata" - } - ], - "nullable": true - }, - "feature_metadata": { - "allOf": [ - { - "$ref": "#/components/schemas/FeatureMetadata" - } - ], - "nullable": true - }, - "payment_link_enabled": { - "$ref": "#/components/schemas/EnablePaymentLinkRequest" - }, - "payment_link_config": { - "allOf": [ - { - "$ref": "#/components/schemas/PaymentLinkConfigRequest" - } - ], - "nullable": true - }, - "request_incremental_authorization": { - "$ref": "#/components/schemas/RequestIncrementalAuthorization" - }, - "expires_on": { - "type": "string", - "format": "date-time", - "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds" - }, - "frm_metadata": { - "type": "object", - "description": "Additional data related to some frm(Fraud Risk Management) connectors", - "nullable": true - }, - "request_external_three_ds_authentication": { - "$ref": "#/components/schemas/External3dsAuthenticationRequest" - } - }, - "additionalProperties": false - }, "PaymentsCreateResponseOpenApi": { "type": "object", "required": [ @@ -14433,6 +14301,179 @@ } } }, + "PaymentsIntentResponse": { + "type": "object", + "required": [ + "id", + "amount_details", + "client_secret", + "capture_method", + "authentication_type", + "customer_present", + "setup_future_usage", + "apply_mit_exemption", + "payment_link_enabled", + "request_incremental_authorization", + "expires_on", + "request_external_three_ds_authentication" + ], + "properties": { + "id": { + "type": "string", + "description": "Global Payment Id for the payment" + }, + "amount_details": { + "$ref": "#/components/schemas/AmountDetailsResponse" + }, + "client_secret": { + "type": "string", + "description": "It's a token used for client side verification.", + "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo" + }, + "merchant_reference_id": { + "type": "string", + "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant.", + "example": "pay_mbabizu24mvu3mela5njyhpit4", + "nullable": true, + "maxLength": 30, + "minLength": 30 + }, + "routing_algorithm_id": { + "type": "string", + "description": "The routing algorithm id to be used for the payment", + "nullable": true + }, + "capture_method": { + "$ref": "#/components/schemas/CaptureMethod" + }, + "authentication_type": { + "allOf": [ + { + "$ref": "#/components/schemas/AuthenticationType" + } + ], + "default": "no_three_ds" + }, + "billing": { + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], + "nullable": true + }, + "shipping": { + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], + "nullable": true + }, + "customer_id": { + "type": "string", + "description": "The identifier for the customer", + "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", + "nullable": true, + "maxLength": 64, + "minLength": 1 + }, + "customer_present": { + "$ref": "#/components/schemas/PresenceOfCustomerDuringPayment" + }, + "description": { + "type": "string", + "description": "A description for the payment", + "example": "It's my first payment request", + "nullable": true + }, + "return_url": { + "type": "string", + "description": "The URL to which you want the user to be redirected after the completion of the payment operation", + "example": "https://hyperswitch.io", + "nullable": true + }, + "setup_future_usage": { + "$ref": "#/components/schemas/FutureUsage" + }, + "apply_mit_exemption": { + "$ref": "#/components/schemas/MitExemptionRequest" + }, + "statement_descriptor": { + "type": "string", + "description": "For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.", + "example": "Hyperswitch Router", + "nullable": true, + "maxLength": 22 + }, + "order_details": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OrderDetailsWithAmount" + }, + "description": "Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount", + "example": "[{\n \"product_name\": \"Apple iPhone 16\",\n \"quantity\": 1,\n \"amount\" : 69000\n \"product_img_link\" : \"https://dummy-img-link.com\"\n }]", + "nullable": true + }, + "allowed_payment_method_types": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "description": "Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent", + "nullable": true + }, + "metadata": { + "type": "object", + "description": "Metadata is useful for storing additional, unstructured information on an object.", + "nullable": true + }, + "connector_metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/ConnectorMetadata" + } + ], + "nullable": true + }, + "feature_metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/FeatureMetadata" + } + ], + "nullable": true + }, + "payment_link_enabled": { + "$ref": "#/components/schemas/EnablePaymentLinkRequest" + }, + "payment_link_config": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkConfigRequest" + } + ], + "nullable": true + }, + "request_incremental_authorization": { + "$ref": "#/components/schemas/RequestIncrementalAuthorization" + }, + "expires_on": { + "type": "string", + "format": "date-time", + "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds" + }, + "frm_metadata": { + "type": "object", + "description": "Additional data related to some frm(Fraud Risk Management) connectors", + "nullable": true + }, + "request_external_three_ds_authentication": { + "$ref": "#/components/schemas/External3dsAuthenticationRequest" + } + }, + "additionalProperties": false + }, "PaymentsResponse": { "type": "object", "required": [ diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index 000343864b2..b9dc1476fdb 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -2,7 +2,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; #[cfg(feature = "v2")] use super::{ - PaymentsConfirmIntentResponse, PaymentsCreateIntentRequest, PaymentsCreateIntentResponse, + PaymentsConfirmIntentResponse, PaymentsCreateIntentRequest, PaymentsGetIntentRequest, + PaymentsIntentResponse, }; #[cfg(all( any(feature = "v2", feature = "v1"), @@ -150,7 +151,16 @@ impl ApiEventMetric for PaymentsCreateIntentRequest { } #[cfg(feature = "v2")] -impl ApiEventMetric for PaymentsCreateIntentResponse { +impl ApiEventMetric for PaymentsGetIntentRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Payment { + payment_id: self.id.clone(), + }) + } +} + +#[cfg(feature = "v2")] +impl ApiEventMetric for PaymentsIntentResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index fd8419e7f97..564149e4325 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -287,10 +287,17 @@ impl PaymentsCreateIntentRequest { } } +// This struct is only used internally, not visible in API Reference +#[derive(Debug, Clone, serde::Serialize)] +#[cfg(feature = "v2")] +pub struct PaymentsGetIntentRequest { + pub id: id_type::GlobalPaymentId, +} + #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] -pub struct PaymentsCreateIntentResponse { +pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs index 602c184139f..c43d72ce8de 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs @@ -57,7 +57,10 @@ pub struct CalculateTax; pub struct SdkSessionUpdate; #[derive(Debug, Clone)] -pub struct CreateIntent; +pub struct PaymentCreateIntent; + +#[derive(Debug, Clone)] +pub struct PaymentGetIntent; #[derive(Debug, Clone)] pub struct PostSessionTokens; diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 0a19c5a63c5..c4a734d152f 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -123,6 +123,7 @@ Never share your secret api keys. Keep them guarded and secure. //Routes for payments routes::payments::payments_create_intent, + routes::payments::payments_get_intent, routes::payments::payments_confirm_intent, //Routes for refunds @@ -325,7 +326,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsSessionRequest, api_models::payments::PaymentsSessionResponse, api_models::payments::PaymentsCreateIntentRequest, - api_models::payments::PaymentsCreateIntentResponse, + api_models::payments::PaymentsIntentResponse, api_models::payments::PazeWalletData, api_models::payments::AmountDetails, api_models::payments::SessionToken, diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index 3429de60ba7..e245c5af68a 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -620,7 +620,7 @@ pub fn payments_post_session_tokens() {} ), ), responses( - (status = 200, description = "Payment created", body = PaymentsCreateIntentResponse), + (status = 200, description = "Payment created", body = PaymentsIntentResponse), (status = 400, description = "Missing Mandatory fields") ), tag = "Payments", @@ -630,6 +630,25 @@ pub fn payments_post_session_tokens() {} #[cfg(feature = "v2")] pub fn payments_create_intent() {} +/// Payments - Get Intent +/// +/// **Get a payment intent object when id is passed in path** +/// +/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call. +#[utoipa::path( + get, + path = "/v2/payments/{id}/get-intent", + params (("id" = String, Path, description = "The unique identifier for the Payment Intent")), + responses( + (status = 200, description = "Payment Intent", body = PaymentsIntentResponse), + (status = 404, description = "Payment Intent not found") + ), + tag = "Payments", + operation_id = "Get the Payment Intent details", + security(("api_key" = [])), +)] +#[cfg(feature = "v2")] +pub fn payments_get_intent() {} /// Payments - Confirm Intent /// /// **Confirms a payment intent object with the payment method data** diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 2218197743a..ca142582c14 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1021,7 +1021,7 @@ pub async fn payments_intent_operation_core<F, Req, Op, D>( ) -> RouterResult<(D, Req, Option<domain::Customer>)> where F: Send + Clone + Sync, - Req: Authenticate + Clone, + Req: Clone, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { @@ -1454,7 +1454,7 @@ pub async fn payments_intent_core<F, Res, Req, Op, D>( where F: Send + Clone + Sync, Op: Operation<F, Req, Data = D> + Send + Sync + Clone, - Req: Debug + Authenticate + Clone, + Req: Debug + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, Res: transformers::ToResponse<F, D, Op>, { diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 6546638a62e..b03f41ac0fd 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -28,11 +28,12 @@ pub mod payments_incremental_authorization; #[cfg(feature = "v1")] pub mod tax_calculation; +#[cfg(feature = "v2")] +pub mod payment_confirm_intent; #[cfg(feature = "v2")] pub mod payment_create_intent; - #[cfg(feature = "v2")] -pub mod payment_confirm_intent; +pub mod payment_get_intent; use api_models::enums::FrmSuggestion; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] @@ -45,6 +46,8 @@ use router_env::{instrument, tracing}; pub use self::payment_confirm_intent::PaymentIntentConfirm; #[cfg(feature = "v2")] pub use self::payment_create_intent::PaymentIntentCreate; +#[cfg(feature = "v2")] +pub use self::payment_get_intent::PaymentGetIntent; pub use self::payment_response::PaymentResponse; #[cfg(feature = "v1")] pub use self::{ diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rs new file mode 100644 index 00000000000..55ddc3b482a --- /dev/null +++ b/crates/router/src/core/payments/operations/payment_get_intent.rs @@ -0,0 +1,231 @@ +use std::marker::PhantomData; + +use api_models::{enums::FrmSuggestion, payments::PaymentsGetIntentRequest}; +use async_trait::async_trait; +use common_utils::errors::CustomResult; +use router_env::{instrument, tracing}; + +use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; +use crate::{ + core::{ + errors::{self, RouterResult}, + payments::{self, helpers, operations}, + }, + db::errors::StorageErrorExt, + routes::{app::ReqState, SessionState}, + types::{ + api, domain, + storage::{self, enums}, + }, +}; + +#[derive(Debug, Clone, Copy)] +pub struct PaymentGetIntent; + +impl<F: Send + Clone> Operation<F, PaymentsGetIntentRequest> for &PaymentGetIntent { + type Data = payments::PaymentIntentData<F>; + fn to_validate_request( + &self, + ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsGetIntentRequest, Self::Data> + Send + Sync)> + { + Ok(*self) + } + fn to_get_tracker( + &self, + ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)> + { + Ok(*self) + } + fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsGetIntentRequest, Self::Data>)> { + Ok(*self) + } + fn to_update_tracker( + &self, + ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)> + { + Ok(*self) + } +} + +impl<F: Send + Clone> Operation<F, PaymentsGetIntentRequest> for PaymentGetIntent { + type Data = payments::PaymentIntentData<F>; + fn to_validate_request( + &self, + ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsGetIntentRequest, Self::Data> + Send + Sync)> + { + Ok(self) + } + fn to_get_tracker( + &self, + ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)> + { + Ok(self) + } + fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsGetIntentRequest, Self::Data>> { + Ok(self) + } + fn to_update_tracker( + &self, + ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)> + { + Ok(self) + } +} + +type PaymentsGetIntentOperation<'b, F> = + BoxedOperation<'b, F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>>; + +#[async_trait] +impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsGetIntentRequest> + for PaymentGetIntent +{ + #[instrument(skip_all)] + async fn get_trackers<'a>( + &'a self, + state: &'a SessionState, + _payment_id: &common_utils::id_type::GlobalPaymentId, + request: &PaymentsGetIntentRequest, + merchant_account: &domain::MerchantAccount, + _profile: &domain::Profile, + key_store: &domain::MerchantKeyStore, + _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + ) -> RouterResult< + operations::GetTrackerResponse< + 'a, + F, + PaymentsGetIntentRequest, + payments::PaymentIntentData<F>, + >, + > { + let db = &*state.store; + let key_manager_state = &state.into(); + let storage_scheme = merchant_account.storage_scheme; + let payment_intent = db + .find_payment_intent_by_id(key_manager_state, &request.id, key_store, storage_scheme) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + let payment_data = payments::PaymentIntentData { + flow: PhantomData, + payment_intent, + }; + + let get_trackers_response = operations::GetTrackerResponse { + operation: Box::new(self), + payment_data, + }; + + Ok(get_trackers_response) + } +} + +#[async_trait] +impl<F: Clone> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsGetIntentRequest> + for PaymentGetIntent +{ + #[instrument(skip_all)] + async fn update_trackers<'b>( + &'b self, + _state: &'b SessionState, + _req_state: ReqState, + payment_data: payments::PaymentIntentData<F>, + _customer: Option<domain::Customer>, + _storage_scheme: enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, + _key_store: &domain::MerchantKeyStore, + _frm_suggestion: Option<FrmSuggestion>, + _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + ) -> RouterResult<( + PaymentsGetIntentOperation<'b, F>, + payments::PaymentIntentData<F>, + )> + where + F: 'b + Send, + { + Ok((Box::new(self), payment_data)) + } +} + +impl<F: Send + Clone> ValidateRequest<F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>> + for PaymentGetIntent +{ + #[instrument(skip_all)] + fn validate_request<'a, 'b>( + &'b self, + _request: &PaymentsGetIntentRequest, + merchant_account: &'a domain::MerchantAccount, + ) -> RouterResult<( + PaymentsGetIntentOperation<'b, F>, + operations::ValidateResult, + )> { + Ok(( + Box::new(self), + operations::ValidateResult { + merchant_id: merchant_account.get_id().to_owned(), + storage_scheme: merchant_account.storage_scheme, + requeue: false, + }, + )) + } +} + +#[async_trait] +impl<F: Clone + Send> Domain<F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>> + for PaymentGetIntent +{ + #[instrument(skip_all)] + async fn get_customer_details<'a>( + &'a self, + state: &SessionState, + payment_data: &mut payments::PaymentIntentData<F>, + merchant_key_store: &domain::MerchantKeyStore, + storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult< + ( + BoxedOperation<'a, F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>>, + Option<domain::Customer>, + ), + errors::StorageError, + > { + Ok((Box::new(self), None)) + } + + #[instrument(skip_all)] + async fn make_pm_data<'a>( + &'a self, + _state: &'a SessionState, + _payment_data: &mut payments::PaymentIntentData<F>, + _storage_scheme: enums::MerchantStorageScheme, + _merchant_key_store: &domain::MerchantKeyStore, + _customer: &Option<domain::Customer>, + _business_profile: &domain::Profile, + ) -> RouterResult<( + PaymentsGetIntentOperation<'a, F>, + Option<domain::PaymentMethodData>, + Option<String>, + )> { + Ok((Box::new(self), None, None)) + } + + async fn get_connector<'a>( + &'a self, + _merchant_account: &domain::MerchantAccount, + state: &SessionState, + _request: &PaymentsGetIntentRequest, + _payment_intent: &storage::PaymentIntent, + _merchant_key_store: &domain::MerchantKeyStore, + ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { + helpers::get_connector_default(state, None).await + } + + #[instrument(skip_all)] + async fn guard_payment_against_blocklist<'a>( + &'a self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _payment_data: &mut payments::PaymentIntentData<F>, + ) -> CustomResult<bool, errors::ApiErrorResponse> { + Ok(false) + } +} diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 58ea3b43462..9f5aa7b0c59 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -754,7 +754,7 @@ where } #[cfg(feature = "v2")] -impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsCreateIntentResponse +impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsIntentResponse where F: Clone, Op: Debug, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 33699ed266a..ec68af2ed90 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -527,6 +527,10 @@ impl Payments { web::resource("/confirm-intent") .route(web::post().to(payments::payment_confirm_intent)), ) + .service( + web::resource("/get-intent") + .route(web::get().to(payments::payments_get_intent)), + ) .service( web::resource("/create-external-sdk-tokens") .route(web::post().to(payments::payments_connector_session)), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index a0c5c0f9902..eaaa7795c8c 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -139,6 +139,7 @@ impl From<Flow> for ApiIdentifier { | Flow::SessionUpdateTaxCalculation | Flow::PaymentsConfirmIntent | Flow::PaymentsCreateIntent + | Flow::PaymentsGetIntent | Flow::PaymentsPostSessionTokens => Self::Payments, Flow::PayoutsCreate diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index f13a873473a..ac00e009f17 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -127,11 +127,11 @@ pub async fn payments_create_intent( json_payload.into_inner(), |state, auth: auth::AuthenticationDataV2, req, req_state| { payments::payments_intent_core::< - api_types::CreateIntent, - payment_types::PaymentsCreateIntentResponse, + api_types::PaymentCreateIntent, + payment_types::PaymentsIntentResponse, _, _, - PaymentIntentData<api_types::CreateIntent>, + PaymentIntentData<api_types::PaymentCreateIntent>, >( state, req_state, @@ -159,6 +159,57 @@ pub async fn payments_create_intent( .await } +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::PaymentsGetIntent, payment_id))] +pub async fn payments_get_intent( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + path: web::Path<common_utils::id_type::GlobalPaymentId>, +) -> impl Responder { + use api_models::payments::PaymentsGetIntentRequest; + use hyperswitch_domain_models::payments::PaymentIntentData; + + let flow = Flow::PaymentsGetIntent; + let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { + Ok(headers) => headers, + Err(err) => { + return api::log_and_return_error_response(err); + } + }; + + let payload = PaymentsGetIntentRequest { + id: path.into_inner(), + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationDataV2, req, req_state| { + payments::payments_intent_core::< + api_types::PaymentGetIntent, + payment_types::PaymentsIntentResponse, + _, + _, + PaymentIntentData<api_types::PaymentGetIntent>, + >( + state, + req_state, + auth.merchant_account, + auth.profile, + auth.key_store, + payments::operations::PaymentGetIntent, + req, + header_payload.clone(), + ) + }, + &auth::HeaderAuth(auth::ApiKeyAuth), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "v1")] #[instrument(skip(state, req), fields(flow = ?Flow::PaymentsStart, payment_id))] pub async fn payments_start( diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 6f6eb381669..d9da8a7226f 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1263,10 +1263,8 @@ impl Authenticate for api_models::payments::PaymentsIncrementalAuthorizationRequ impl Authenticate for api_models::payments::PaymentsStartRequest {} // impl Authenticate for api_models::payments::PaymentsApproveRequest {} impl Authenticate for api_models::payments::PaymentsRejectRequest {} -#[cfg(feature = "v2")] -impl Authenticate for api_models::payments::PaymentsCreateIntentRequest {} // #[cfg(feature = "v2")] -// impl Authenticate for api_models::payments::PaymentsCreateIntentResponse {} +// impl Authenticate for api_models::payments::PaymentsIntentResponse {} pub fn build_redirection_form( form: &RedirectForm, diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index fc13cc6a22b..57ef1d3336f 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -19,13 +19,13 @@ pub use api_models::payments::{ VerifyResponse, WalletData, }; #[cfg(feature = "v2")] -pub use api_models::payments::{PaymentsCreateIntentRequest, PaymentsCreateIntentResponse}; +pub use api_models::payments::{PaymentsCreateIntentRequest, PaymentsIntentResponse}; use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, - CreateConnectorCustomer, CreateIntent, IncrementalAuthorization, InitPayment, PSync, - PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, - Session, SetupMandate, Void, + CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, PaymentCreateIntent, + PaymentGetIntent, PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, Reject, + SdkSessionUpdate, Session, SetupMandate, Void, }; pub use hyperswitch_interfaces::api::payments::{ ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 8d853ded338..3bd8a13628e 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -171,6 +171,8 @@ pub enum Flow { PaymentsAggregate, /// Payments Create Intent flow PaymentsCreateIntent, + /// Payments Get Intent flow + PaymentsGetIntent, #[cfg(feature = "payouts")] /// Payouts create flow PayoutsCreate,
2024-10-22T12:37:13Z
## Description Added `get-intent` API for payments ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6395 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1a. Request ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0192b3a0145173519abaa04d4b939558/get-intent' \ --header 'Content-Type: application/json' \ --header 'X-Profile-Id: pro_wcilqiS8axGFvpzfO9pw' \ --header 'api-key: dev_D3bTAROAIoP4nlqsaQXLzXoLdZznkpWQ3l4mzMRJEAP7V46pSnZucJM2zQiVwG0J' ``` 1b. Response ```json { "id": "12345_pay_0192b3a0145173519abaa04d4b939558", "amount_details": { "order_amount": { "Value": 100 }, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "skip_external_tax_calculation": "Skip", "skip_surcharge_calculation": "Skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "12345_pay_0192b3a0145173519abaa04d4b939558_secret_0192b3a0145173519abaa05c07ec3e61", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "no_three_ds", "billing": null, "shipping": null, "customer_id": null, "customer_present": "Present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2024-10-22T10:02:45.618Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ```
fbe395198aea7252e9c4e3fad97956a548d07002
1a. Request ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0192b3a0145173519abaa04d4b939558/get-intent' \ --header 'Content-Type: application/json' \ --header 'X-Profile-Id: pro_wcilqiS8axGFvpzfO9pw' \ --header 'api-key: dev_D3bTAROAIoP4nlqsaQXLzXoLdZznkpWQ3l4mzMRJEAP7V46pSnZucJM2zQiVwG0J' ``` 1b. Response ```json { "id": "12345_pay_0192b3a0145173519abaa04d4b939558", "amount_details": { "order_amount": { "Value": 100 }, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "skip_external_tax_calculation": "Skip", "skip_surcharge_calculation": "Skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "12345_pay_0192b3a0145173519abaa04d4b939558_secret_0192b3a0145173519abaa05c07ec3e61", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "no_three_ds", "billing": null, "shipping": null, "customer_id": null, "customer_present": "Present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2024-10-22T10:02:45.618Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ```
[ "api-reference-v2/api-reference/payments/payments--get-intent.mdx", "api-reference-v2/mint.json", "api-reference-v2/openapi_spec.json", "crates/api_models/src/events/payment.rs", "crates/api_models/src/payments.rs", "crates/hyperswitch_domain_models/src/router_flow_types/payments.rs", "crates/openapi/src/openapi_v2.rs", "crates/openapi/src/routes/payments.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/operations.rs", "crates/router/src/core/payments/operations/payment_get_intent.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/payments.rs", "crates/router/src/services/api.rs", "crates/router/src/types/api/payments.rs", "crates/router_env/src/logger/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6391
Bug: feat(authz): Make permissions entity and scope aware Currently the permissions we use doesn't have any entity level context. But some of our APIs need that context. For example, 1. `payment/list` - This can only be accessible by merchant level users or higher. Profile level users should not be able to access it. 2. `payment/profile/list` - This can be accessible by all level of users. With current setup, this is not directly possible by the permissions. We had to introduce `min_entity_level` to solve this, but this is very separated from the permissions. To solve this, we need to have entity level context at permissions level itself. ### Scope for permissions The write permissions currently doesn't have access to read APIs, but since write is a superset of read, they should be able to access read APIs as well. So, this PR also introduces scope context in permissions.
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index e64639646d1..19027c3cbf8 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -1,23 +1,9 @@ -use common_enums::PermissionGroup; +use common_enums::{ParentGroup, PermissionGroup}; use common_utils::pii; use masking::Secret; pub mod role; -#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash)] -pub enum ParentGroup { - Operations, - Connectors, - Workflows, - Analytics, - Users, - #[serde(rename = "MerchantAccess")] - Merchant, - #[serde(rename = "OrganizationAccess")] - Organization, - Recon, -} - #[derive(Debug, serde::Serialize)] pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>); diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 3ce9d079c63..c103153eec8 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2890,6 +2890,47 @@ pub enum PermissionGroup { ReconOps, } +#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] +pub enum ParentGroup { + Operations, + Connectors, + Workflows, + Analytics, + Users, + #[serde(rename = "MerchantAccess")] + Merchant, + #[serde(rename = "OrganizationAccess")] + Organization, + Recon, +} + +#[derive(Clone, Copy, Eq, PartialEq, Hash)] +pub enum Resource { + Payment, + Refund, + ApiKey, + Account, + Connector, + Routing, + Dispute, + Mandate, + Customer, + Analytics, + ThreeDsDecisionManager, + SurchargeDecisionManager, + User, + WebhookEvent, + Payout, + Report, + Recon, +} + +#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] +pub enum PermissionScope { + Read, + Write, +} + /// Name of banks supported by Hyperswitch #[derive( Clone, diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index aa6db56bb34..150931e9c8a 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -402,8 +402,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -441,8 +440,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Organization, + permission: Permission::OrganizationAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -487,8 +485,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -528,8 +525,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -567,8 +563,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Organization, + permission: Permission::OrganizationAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -613,8 +608,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -654,8 +648,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -693,8 +686,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Organization, + permission: Permission::OrganizationAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -739,8 +731,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -774,8 +765,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -813,8 +803,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -853,8 +842,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -893,8 +881,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -924,8 +911,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -953,8 +939,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Organization, + permission: Permission::OrganizationAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -989,8 +974,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1018,8 +1002,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1049,8 +1032,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1078,8 +1060,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Organization, + permission: Permission::OrganizationAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1114,8 +1095,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1139,8 +1119,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1168,8 +1147,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1201,8 +1179,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1235,8 +1212,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1267,8 +1243,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1318,8 +1293,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::GenerateReport, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantReportRead, }, api_locking::LockAction::NotApplicable, )) @@ -1367,8 +1341,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::GenerateReport, - minimum_entity_level: EntityType::Organization, + permission: Permission::OrganizationReportRead, }, api_locking::LockAction::NotApplicable, )) @@ -1423,8 +1396,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::GenerateReport, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileReportRead, }, api_locking::LockAction::NotApplicable, )) @@ -1474,8 +1446,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::GenerateReport, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantReportRead, }, api_locking::LockAction::NotApplicable, )) @@ -1523,8 +1494,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::GenerateReport, - minimum_entity_level: EntityType::Organization, + permission: Permission::OrganizationReportRead, }, api_locking::LockAction::NotApplicable, )) @@ -1579,8 +1549,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::GenerateReport, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileReportRead, }, api_locking::LockAction::NotApplicable, )) @@ -1630,8 +1599,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::GenerateReport, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantReportRead, }, api_locking::LockAction::NotApplicable, )) @@ -1679,8 +1647,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::GenerateReport, - minimum_entity_level: EntityType::Organization, + permission: Permission::OrganizationReportRead, }, api_locking::LockAction::NotApplicable, )) @@ -1734,8 +1701,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::GenerateReport, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileReportRead, }, api_locking::LockAction::NotApplicable, )) @@ -1773,8 +1739,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1798,8 +1763,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1830,8 +1794,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -1948,8 +1911,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -2065,8 +2027,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -2096,8 +2057,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -2132,8 +2092,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -2161,8 +2120,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Organization, + permission: Permission::OrganizationAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -2202,8 +2160,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -2248,8 +2205,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -2287,8 +2243,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Organization, + permission: Permission::OrganizationAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -2319,8 +2274,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -2349,8 +2303,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Organization, + permission: Permission::OrganizationAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) @@ -2386,8 +2339,7 @@ pub mod routes { .map(ApplicationResponse::Json) }, &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 1d188168e5c..284be4ab4ba 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -16,14 +16,14 @@ use crate::{ routes::{app::ReqState, SessionState}, services::{ authentication as auth, - authorization::{info, roles}, + authorization::{info, permission_groups::PermissionGroupExt, roles}, ApplicationResponse, }, types::domain, utils, }; pub mod role; -use common_enums::{EntityType, PermissionGroup}; +use common_enums::{EntityType, ParentGroup, PermissionGroup}; use strum::IntoEnumIterator; // TODO: To be deprecated @@ -44,11 +44,10 @@ pub async fn get_authorization_info_with_group_tag( ) -> UserResponse<user_role_api::AuthorizationInfoResponse> { static GROUPS_WITH_PARENT_TAGS: Lazy<Vec<user_role_api::ParentInfo>> = Lazy::new(|| { PermissionGroup::iter() - .map(|value| (info::get_parent_name(value), value)) + .map(|group| (group.parent(), group)) .fold( HashMap::new(), - |mut acc: HashMap<user_role_api::ParentGroup, Vec<PermissionGroup>>, - (key, value)| { + |mut acc: HashMap<ParentGroup, Vec<PermissionGroup>>, (key, value)| { acc.entry(key).or_default().push(value); acc }, diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 78238d3af07..b197101d65f 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -1,5 +1,4 @@ use actix_web::{web, HttpRequest, HttpResponse}; -use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -52,8 +51,7 @@ pub async fn organization_update( &auth::AdminApiAuth, &auth::JWTAuthOrganizationFromRoute { organization_id, - required_permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Organization, + required_permission: Permission::OrganizationAccountWrite, }, req.headers(), ), @@ -85,8 +83,7 @@ pub async fn organization_retrieve( &auth::AdminApiAuth, &auth::JWTAuthOrganizationFromRoute { organization_id, - required_permission: Permission::MerchantAccountRead, - minimum_entity_level: EntityType::Organization, + required_permission: Permission::OrganizationAccountRead, }, req.headers(), ), @@ -139,8 +136,11 @@ pub async fn retrieve_merchant_account( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: Permission::MerchantAccountRead, - minimum_entity_level: EntityType::Profile, + // This should ideally be MerchantAccountRead, but since FE is calling this API for + // profile level users currently keeping this as ProfileAccountRead. FE is removing + // this API call for profile level users. + // TODO: Convert this to MerchantAccountRead once FE changes are done. + required_permission: Permission::ProfileAccountRead, }, req.headers(), ), @@ -172,7 +172,6 @@ pub async fn merchant_account_list( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -200,7 +199,6 @@ pub async fn merchant_account_list( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -232,7 +230,6 @@ pub async fn update_merchant_account( &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -298,8 +295,7 @@ pub async fn connector_create( &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), - required_permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Profile, + required_permission: Permission::ProfileConnectorWrite, }, req.headers(), ), @@ -336,8 +332,7 @@ pub async fn connector_create( auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { - required_permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantConnectorWrite, }, req.headers(), ), @@ -399,8 +394,7 @@ pub async fn connector_retrieve( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: Permission::MerchantConnectorAccountRead, - minimum_entity_level: EntityType::Profile, + required_permission: Permission::ProfileConnectorRead, }, req.headers(), ), @@ -438,8 +432,7 @@ pub async fn connector_retrieve( auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { - required_permission: Permission::MerchantConnectorAccountRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantConnectorRead, }, req.headers(), ), @@ -469,8 +462,7 @@ pub async fn connector_list( auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { - required_permission: Permission::MerchantConnectorAccountRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantConnectorRead, }, req.headers(), ), @@ -517,8 +509,7 @@ pub async fn connector_list( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: Permission::MerchantConnectorAccountRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantConnectorRead, }, req.headers(), ), @@ -569,8 +560,7 @@ pub async fn connector_list_profile( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: Permission::MerchantConnectorAccountRead, - minimum_entity_level: EntityType::Profile, + required_permission: Permission::ProfileConnectorRead, }, req.headers(), ), @@ -631,8 +621,7 @@ pub async fn connector_update( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), - required_permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Profile, + required_permission: Permission::ProfileConnectorWrite, }, req.headers(), ), @@ -683,8 +672,7 @@ pub async fn connector_update( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), - required_permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantConnectorWrite, }, req.headers(), ), @@ -739,8 +727,7 @@ pub async fn connector_delete( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantConnectorWrite, }, req.headers(), ), @@ -778,8 +765,7 @@ pub async fn connector_delete( auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { - required_permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantConnectorWrite, }, req.headers(), ), diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index bbecaae9e80..1a2f60bcccb 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -1,5 +1,4 @@ use actix_web::{web, HttpRequest, Responder}; -use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -33,8 +32,7 @@ pub async fn api_key_create( &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), - required_permission: Permission::ApiKeyWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantApiKeyWrite, }, req.headers(), ), @@ -64,8 +62,7 @@ pub async fn api_key_create( auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { - required_permission: Permission::ApiKeyWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantApiKeyWrite, }, req.headers(), ), @@ -99,8 +96,7 @@ pub async fn api_key_retrieve( auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { - required_permission: Permission::ApiKeyRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantApiKeyRead, }, req.headers(), ), @@ -132,8 +128,7 @@ pub async fn api_key_retrieve( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), - required_permission: Permission::ApiKeyRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantApiKeyRead, }, req.headers(), ), @@ -169,8 +164,7 @@ pub async fn api_key_update( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: Permission::ApiKeyWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantApiKeyWrite, }, req.headers(), ), @@ -203,8 +197,7 @@ pub async fn api_key_update( auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { - required_permission: Permission::ApiKeyRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantApiKeyRead, }, req.headers(), ), @@ -236,8 +229,7 @@ pub async fn api_key_revoke( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), - required_permission: Permission::ApiKeyWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantApiKeyWrite, }, req.headers(), ), @@ -269,8 +261,7 @@ pub async fn api_key_revoke( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), - required_permission: Permission::ApiKeyWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantApiKeyWrite, }, req.headers(), ), @@ -305,8 +296,7 @@ pub async fn api_key_list( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: Permission::ApiKeyRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantApiKeyRead, }, req.headers(), ), @@ -336,8 +326,7 @@ pub async fn api_key_list( auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { - required_permission: Permission::ApiKeyRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantApiKeyRead, }, req.headers(), ), diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs index 4738df5ed2c..f54f61d8a00 100644 --- a/crates/router/src/routes/blocklist.rs +++ b/crates/router/src/routes/blocklist.rs @@ -1,6 +1,5 @@ use actix_web::{web, HttpRequest, HttpResponse}; use api_models::blocklist as api_blocklist; -use common_enums::EntityType; use router_env::Flow; use crate::{ @@ -39,7 +38,6 @@ pub async fn add_entry_to_blocklist( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -78,7 +76,6 @@ pub async fn remove_entry_from_blocklist( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -119,7 +116,6 @@ pub async fn list_blocked_payment_methods( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::MerchantAccountRead, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -160,7 +156,6 @@ pub async fn toggle_blocklist_guard( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), diff --git a/crates/router/src/routes/connector_onboarding.rs b/crates/router/src/routes/connector_onboarding.rs index f7494e182c1..8ecd321df94 100644 --- a/crates/router/src/routes/connector_onboarding.rs +++ b/crates/router/src/routes/connector_onboarding.rs @@ -1,6 +1,5 @@ use actix_web::{web, HttpRequest, HttpResponse}; use api_models::connector_onboarding as api_types; -use common_enums::EntityType; use router_env::Flow; use super::AppState; @@ -24,7 +23,6 @@ pub async fn get_action_url( core::get_action_url, &auth::JWTAuth { permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, }, api_locking::LockAction::NotApplicable, )) @@ -46,7 +44,6 @@ pub async fn sync_onboarding_status( core::sync_onboarding_status, &auth::JWTAuth { permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, }, api_locking::LockAction::NotApplicable, )) @@ -68,7 +65,6 @@ pub async fn reset_tracking_id( core::reset_tracking_id, &auth::JWTAuth { permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 536bca10f3d..5ff155966a0 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -1,5 +1,4 @@ use actix_web::{web, HttpRequest, HttpResponse, Responder}; -use common_enums::EntityType; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use common_utils::id_type; use router_env::{instrument, tracing, Flow}; @@ -29,8 +28,7 @@ pub async fn customers_create( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::CustomerWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantCustomerWrite, }, req.headers(), ), @@ -55,8 +53,7 @@ pub async fn customers_retrieve( let auth = if auth::is_jwt_auth(req.headers()) { Box::new(auth::JWTAuth { - permission: Permission::CustomerRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantCustomerRead, }) } else { match auth::is_ephemeral_auth(req.headers()) { @@ -98,8 +95,7 @@ pub async fn customers_retrieve( let auth = if auth::is_jwt_auth(req.headers()) { Box::new(auth::JWTAuth { - permission: Permission::CustomerRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantCustomerRead, }) } else { match auth::is_ephemeral_auth(req.headers()) { @@ -148,8 +144,7 @@ pub async fn customers_list( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::CustomerRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantCustomerRead, }, req.headers(), ), @@ -187,8 +182,7 @@ pub async fn customers_update( auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth { - permission: Permission::CustomerWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantCustomerWrite, }, req.headers(), ), @@ -225,8 +219,7 @@ pub async fn customers_update( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::CustomerWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantCustomerWrite, }, req.headers(), ), @@ -256,8 +249,7 @@ pub async fn customers_delete( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::CustomerWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantCustomerWrite, }, req.headers(), ), @@ -290,8 +282,7 @@ pub async fn customers_delete( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::CustomerWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantCustomerWrite, }, req.headers(), ), @@ -328,8 +319,7 @@ pub async fn get_customer_mandates( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::MandateRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantMandateRead, }, req.headers(), ), diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs index 22c1e3f1988..5577bb96ef0 100644 --- a/crates/router/src/routes/disputes.rs +++ b/crates/router/src/routes/disputes.rs @@ -1,7 +1,6 @@ use actix_multipart::Multipart; use actix_web::{web, HttpRequest, HttpResponse}; use api_models::disputes as dispute_models; -use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use crate::{core::api_locking, services::authorization::permissions::Permission}; @@ -50,8 +49,7 @@ pub async fn retrieve_dispute( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileDisputeRead, }, req.headers(), ), @@ -102,8 +100,7 @@ pub async fn retrieve_disputes_list( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantDisputeRead, }, req.headers(), ), @@ -160,8 +157,7 @@ pub async fn retrieve_disputes_list_profile( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileDisputeRead, }, req.headers(), ), @@ -195,8 +191,7 @@ pub async fn get_disputes_filters(state: web::Data<AppState>, req: HttpRequest) auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantDisputeRead, }, req.headers(), ), @@ -237,8 +232,7 @@ pub async fn get_disputes_filters_profile( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileDisputeRead, }, req.headers(), ), @@ -289,8 +283,7 @@ pub async fn accept_dispute( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileDisputeWrite, }, req.headers(), ), @@ -335,8 +328,7 @@ pub async fn submit_dispute_evidence( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileDisputeWrite, }, req.headers(), ), @@ -389,8 +381,7 @@ pub async fn attach_dispute_evidence( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileDisputeWrite, }, req.headers(), ), @@ -435,8 +426,7 @@ pub async fn retrieve_dispute_evidence( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileDisputeRead, }, req.headers(), ), @@ -478,8 +468,7 @@ pub async fn delete_dispute_evidence( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileDisputeWrite, }, req.headers(), ), @@ -508,8 +497,7 @@ pub async fn get_disputes_aggregate( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantDisputeRead, }, req.headers(), ), @@ -543,8 +531,7 @@ pub async fn get_disputes_aggregate_profile( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::DisputeRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileDisputeRead, }, req.headers(), ), diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index c0ccbfa9f8f..cb832d81a16 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -1,5 +1,4 @@ use actix_web::{web, HttpRequest, HttpResponse}; -use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -117,8 +116,7 @@ pub async fn retrieve_mandates_list( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::MandateRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantMandateRead, }, req.headers(), ), diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 8d95ee64ad0..0dbddbef77b 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -4,7 +4,6 @@ ))] use actix_multipart::form::MultipartForm; use actix_web::{web, HttpRequest, HttpResponse}; -use common_enums::EntityType; use common_utils::{errors::CustomResult, id_type}; use diesel_models::enums::IntentStatus; use error_stack::ResultExt; @@ -881,15 +880,13 @@ pub async fn list_countries_currencies_for_connector_payment_method( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileConnectorWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileConnectorWrite, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index f13a873473a..bca7bd37ccc 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -5,7 +5,6 @@ use crate::{ pub mod helpers; use actix_web::{web, Responder}; -use common_enums::EntityType; use error_stack::report; use hyperswitch_domain_models::payments::HeaderPayload; use masking::PeekInterface; @@ -93,8 +92,7 @@ pub async fn payments_create( _ => auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PaymentWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePaymentWrite, }, req.headers(), ), @@ -148,8 +146,7 @@ pub async fn payments_create_intent( _ => auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PaymentWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePaymentWrite, }, req.headers(), ), @@ -285,8 +282,7 @@ pub async fn payments_retrieve( auth::auth_type( &*auth_type, &auth::JWTAuth { - permission: Permission::PaymentRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePaymentRead, }, req.headers(), ), @@ -995,8 +991,7 @@ pub async fn payments_list( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PaymentRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantPaymentRead, }, req.headers(), ), @@ -1031,8 +1026,7 @@ pub async fn profile_payments_list( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PaymentRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePaymentRead, }, req.headers(), ), @@ -1065,8 +1059,7 @@ pub async fn payments_list_by_filter( ) }, &auth::JWTAuth { - permission: Permission::PaymentRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantPaymentRead, }, api_locking::LockAction::NotApplicable, )) @@ -1097,8 +1090,7 @@ pub async fn profile_payments_list_by_filter( ) }, &auth::JWTAuth { - permission: Permission::PaymentRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePaymentRead, }, api_locking::LockAction::NotApplicable, )) @@ -1123,8 +1115,7 @@ pub async fn get_filters_for_payments( payments::get_filters_for_payments(state, auth.merchant_account, auth.key_store, req) }, &auth::JWTAuth { - permission: Permission::PaymentRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantPaymentRead, }, api_locking::LockAction::NotApplicable, )) @@ -1147,8 +1138,7 @@ pub async fn get_payment_filters( payments::get_payment_filters(state, auth.merchant_account, None) }, &auth::JWTAuth { - permission: Permission::PaymentRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantPaymentRead, }, api_locking::LockAction::NotApplicable, )) @@ -1175,8 +1165,7 @@ pub async fn get_payment_filters_profile( ) }, &auth::JWTAuth { - permission: Permission::PaymentRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePaymentRead, }, api_locking::LockAction::NotApplicable, )) @@ -1201,8 +1190,7 @@ pub async fn get_payments_aggregates( payments::get_aggregates_for_payments(state, auth.merchant_account, None, req) }, &auth::JWTAuth { - permission: Permission::PaymentRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantPaymentRead, }, api_locking::LockAction::NotApplicable, )) @@ -1262,8 +1250,7 @@ pub async fn payments_approve( _ => auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PaymentWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePaymentWrite, }, http_req.headers(), ), @@ -1327,8 +1314,7 @@ pub async fn payments_reject( _ => auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PaymentWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePaymentWrite, }, http_req.headers(), ), @@ -1970,8 +1956,7 @@ pub async fn get_payments_aggregates_profile( ) }, &auth::JWTAuth { - permission: Permission::PaymentRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePaymentRead, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs index ad860195a2a..62d16c4c4d5 100644 --- a/crates/router/src/routes/payouts.rs +++ b/crates/router/src/routes/payouts.rs @@ -3,7 +3,6 @@ use actix_web::{ http::header::HeaderMap, web, HttpRequest, HttpResponse, Responder, }; -use common_enums::EntityType; use common_utils::consts; use router_env::{instrument, tracing, Flow}; @@ -84,8 +83,7 @@ pub async fn payouts_retrieve( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PayoutRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePayoutRead, }, req.headers(), ), @@ -237,8 +235,7 @@ pub async fn payouts_list( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PayoutRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantPayoutRead, }, req.headers(), ), @@ -277,8 +274,7 @@ pub async fn payouts_list_profile( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PayoutRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePayoutRead, }, req.headers(), ), @@ -317,8 +313,7 @@ pub async fn payouts_list_by_filter( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PayoutRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantPayoutRead, }, req.headers(), ), @@ -357,8 +352,7 @@ pub async fn payouts_list_by_filter_profile( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PayoutRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePayoutRead, }, req.headers(), ), @@ -390,8 +384,7 @@ pub async fn payouts_list_available_filters_for_merchant( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PayoutRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantPayoutRead, }, req.headers(), ), @@ -429,8 +422,7 @@ pub async fn payouts_list_available_filters_for_profile( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::PayoutRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfilePayoutRead, }, req.headers(), ), diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rs index f2dc322af17..cbb7957987f 100644 --- a/crates/router/src/routes/profiles.rs +++ b/crates/router/src/routes/profiles.rs @@ -1,5 +1,4 @@ use actix_web::{web, HttpRequest, HttpResponse}; -use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -34,7 +33,6 @@ pub async fn profile_create( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -65,7 +63,6 @@ pub async fn profile_create( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: permissions::Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -97,8 +94,7 @@ pub async fn profile_retrieve( &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), - required_permission: permissions::Permission::MerchantAccountRead, - minimum_entity_level: EntityType::Profile, + required_permission: permissions::Permission::ProfileAccountRead, }, req.headers(), ), @@ -127,7 +123,6 @@ pub async fn profile_retrieve( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: permissions::Permission::MerchantAccountRead, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -161,8 +156,7 @@ pub async fn profile_update( &auth::JWTAuthMerchantAndProfileFromRoute { merchant_id: merchant_id.clone(), profile_id: profile_id.clone(), - required_permission: permissions::Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Profile, + required_permission: permissions::Permission::ProfileAccountWrite, }, req.headers(), ), @@ -192,7 +186,6 @@ pub async fn profile_update( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: permissions::Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -244,7 +237,6 @@ pub async fn profiles_list( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountRead, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -278,8 +270,7 @@ pub async fn profiles_list_at_profile_level( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: permissions::Permission::MerchantAccountRead, - minimum_entity_level: EntityType::Profile, + required_permission: permissions::Permission::ProfileAccountRead, }, req.headers(), ), @@ -312,8 +303,7 @@ pub async fn toggle_connector_agnostic_mit( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: permissions::Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + permission: permissions::Permission::MerchantRoutingWrite, }, req.headers(), ), @@ -372,8 +362,7 @@ pub async fn payment_connector_list_profile( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: permissions::Permission::MerchantConnectorAccountRead, - minimum_entity_level: EntityType::Profile, + required_permission: permissions::Permission::ProfileConnectorRead, }, req.headers(), ), diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs index 1ec571ff7c9..cdc2ae758e9 100644 --- a/crates/router/src/routes/recon.rs +++ b/crates/router/src/routes/recon.rs @@ -1,5 +1,5 @@ use actix_web::{web, HttpRequest, HttpResponse}; -use api_models::{enums::EntityType, recon as recon_api}; +use api_models::recon as recon_api; use router_env::Flow; use super::AppState; @@ -38,8 +38,7 @@ pub async fn request_for_recon(state: web::Data<AppState>, http_req: HttpRequest (), |state, user, _, _| recon::send_recon_request(state, user), &authentication::JWTAuth { - permission: Permission::ReconAdmin, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantReconWrite, }, api_locking::LockAction::NotApplicable, )) @@ -55,8 +54,7 @@ pub async fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> Ht (), |state, user, _, _| recon::generate_recon_token(state, user), &authentication::JWTAuth { - permission: Permission::ReconAdmin, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantReconWrite, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index c76ee600efe..cbcfbcdcbf1 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -1,5 +1,4 @@ use actix_web::{web, HttpRequest, HttpResponse}; -use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -49,8 +48,7 @@ pub async fn refunds_create( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RefundWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRefundWrite, }, req.headers(), ), @@ -113,8 +111,7 @@ pub async fn refunds_retrieve( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RefundRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRefundRead, }, req.headers(), ), @@ -245,8 +242,7 @@ pub async fn refunds_list( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RefundRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRefundRead, }, req.headers(), ), @@ -293,8 +289,7 @@ pub async fn refunds_list_profile( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RefundRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRefundRead, }, req.headers(), ), @@ -336,8 +331,7 @@ pub async fn refunds_filter_list( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RefundRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRefundRead, }, req.headers(), ), @@ -374,8 +368,7 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) - auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RefundRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRefundRead, }, req.headers(), ), @@ -419,8 +412,7 @@ pub async fn get_refunds_filters_profile( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RefundRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRefundRead, }, req.headers(), ), @@ -449,8 +441,7 @@ pub async fn get_refunds_aggregates( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RefundRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRefundRead, }, req.headers(), ), @@ -507,8 +498,7 @@ pub async fn get_refunds_aggregate_profile( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RefundRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRefundRead, }, req.headers(), ), diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index 4c8d89fa87d..3e0355a884a 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -5,7 +5,6 @@ use actix_web::{web, HttpRequest, Responder}; use api_models::{enums, routing as routing_types, routing::RoutingRetrieveQuery}; -use common_enums::EntityType; use router_env::{ tracing::{self, instrument}, Flow, @@ -44,15 +43,13 @@ pub async fn routing_create_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingWrite, }, api_locking::LockAction::NotApplicable, )) @@ -87,15 +84,13 @@ pub async fn routing_link_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingWrite, }, api_locking::LockAction::NotApplicable, )) @@ -137,16 +132,14 @@ pub async fn routing_link_config( &auth::ApiKeyAuth, &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, - required_permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, - required_permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantRoutingWrite, }, api_locking::LockAction::NotApplicable, )) @@ -180,15 +173,13 @@ pub async fn routing_retrieve_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingRead, }, api_locking::LockAction::NotApplicable, )) @@ -222,15 +213,13 @@ pub async fn list_routing_configs( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRoutingRead, }, api_locking::LockAction::NotApplicable, )) @@ -264,15 +253,13 @@ pub async fn list_routing_configs_for_profile( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingRead, }, api_locking::LockAction::NotApplicable, )) @@ -308,16 +295,14 @@ pub async fn routing_unlink_config( &auth::ApiKeyAuth, &auth::JWTAuthProfileFromRoute { profile_id: path, - required_permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: path, - required_permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantRoutingWrite, }, api_locking::LockAction::NotApplicable, )) @@ -352,15 +337,13 @@ pub async fn routing_unlink_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingWrite, }, api_locking::LockAction::NotApplicable, )) @@ -397,15 +380,13 @@ pub async fn routing_update_default_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRoutingWrite, }, api_locking::LockAction::NotApplicable, )) @@ -437,15 +418,13 @@ pub async fn routing_update_default_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRoutingWrite, }, api_locking::LockAction::NotApplicable, )) @@ -478,16 +457,14 @@ pub async fn routing_retrieve_default_config( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuthProfileFromRoute { profile_id: path, - required_permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: path, - required_permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantRoutingRead, }, api_locking::LockAction::NotApplicable, )) @@ -513,15 +490,13 @@ pub async fn routing_retrieve_default_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingRead, }, api_locking::LockAction::NotApplicable, )) @@ -553,15 +528,13 @@ pub async fn upsert_surcharge_decision_manager_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantSurchargeDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantSurchargeDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) @@ -590,15 +563,13 @@ pub async fn delete_surcharge_decision_manager_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantSurchargeDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantSurchargeDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) @@ -627,15 +598,13 @@ pub async fn retrieve_surcharge_decision_manager_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantSurchargeDecisionManagerRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantSurchargeDecisionManagerRead, }, api_locking::LockAction::NotApplicable, )) @@ -667,15 +636,13 @@ pub async fn upsert_decision_manager_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantThreeDsDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantThreeDsDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) @@ -705,15 +672,13 @@ pub async fn delete_decision_manager_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantThreeDsDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantThreeDsDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) @@ -739,15 +704,13 @@ pub async fn retrieve_decision_manager_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantThreeDsDecisionManagerRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::SurchargeDecisionManagerRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantThreeDsDecisionManagerRead, }, api_locking::LockAction::NotApplicable, )) @@ -786,16 +749,14 @@ pub async fn routing_retrieve_linked_config( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuthProfileFromRoute { profile_id, - required_permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + required_permission: Permission::ProfileRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id, - required_permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + required_permission: Permission::ProfileRoutingRead, }, api_locking::LockAction::NotApplicable, )) @@ -820,15 +781,13 @@ pub async fn routing_retrieve_linked_config( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileRoutingRead, }, api_locking::LockAction::NotApplicable, )) @@ -871,16 +830,14 @@ pub async fn routing_retrieve_linked_config( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, - required_permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + required_permission: Permission::ProfileRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, - required_permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + required_permission: Permission::ProfileRoutingRead, }, api_locking::LockAction::NotApplicable, )) @@ -911,8 +868,7 @@ pub async fn routing_retrieve_default_config_for_profiles( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRoutingRead, }, req.headers(), ), @@ -920,8 +876,7 @@ pub async fn routing_retrieve_default_config_for_profiles( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantRoutingRead, }, req.headers(), ), @@ -963,16 +918,14 @@ pub async fn routing_update_default_config_for_profile( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, - required_permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Profile, + required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, - required_permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Profile, + required_permission: Permission::ProfileRoutingWrite, }, api_locking::LockAction::NotApplicable, )) @@ -1013,8 +966,7 @@ pub async fn toggle_success_based_routing( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, - required_permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Profile, + required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index e07a2fa10ef..f52d0dca7a8 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -5,7 +5,7 @@ use api_models::{ errors::types::ApiErrorResponse, user::{self as user_api}, }; -use common_enums::{EntityType, TokenPurpose}; +use common_enums::TokenPurpose; use common_utils::errors::ReportSwitchExt; use router_env::Flow; @@ -176,8 +176,7 @@ pub async fn set_dashboard_metadata( payload, user_core::dashboard_metadata::set_metadata, &auth::JWTAuth { - permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAccountWrite, }, api_locking::LockAction::NotApplicable, )) @@ -243,8 +242,7 @@ pub async fn user_merchant_account_create( user_core::create_merchant_account(state, auth, json_payload) }, &auth::JWTAuth { - permission: Permission::MerchantAccountCreate, - minimum_entity_level: EntityType::Merchant, + permission: Permission::OrganizationAccountWrite, }, api_locking::LockAction::NotApplicable, )) @@ -267,8 +265,7 @@ pub async fn generate_sample_data( payload.into_inner(), sample_data::generate_sample_data_for_user, &auth::JWTAuth { - permission: Permission::PaymentWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantPaymentWrite, }, api_locking::LockAction::NotApplicable, )) @@ -292,7 +289,6 @@ pub async fn delete_sample_data( sample_data::delete_sample_data_for_user, &auth::JWTAuth { permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, }, api_locking::LockAction::NotApplicable, )) @@ -312,8 +308,7 @@ pub async fn list_user_roles_details( payload.into_inner(), user_core::list_user_roles_details, &auth::JWTAuth { - permission: Permission::UsersRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) @@ -395,8 +390,7 @@ pub async fn invite_multiple_user( user_core::invite_multiple_user(state, user, payload, req_state, auth_id.clone()) }, &auth::JWTAuth { - permission: Permission::UsersWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileUserWrite, }, api_locking::LockAction::NotApplicable, )) @@ -421,8 +415,7 @@ pub async fn resend_invite( user_core::resend_invite(state, user, req_payload, auth_id.clone()) }, &auth::JWTAuth { - permission: Permission::UsersWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileUserWrite, }, api_locking::LockAction::NotApplicable, )) @@ -504,8 +497,7 @@ pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpReques (), |state, user, _req, _| user_core::verify_token(state, user), &auth::JWTAuth { - permission: Permission::ReconAdmin, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantReconWrite, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 777cbe1fd95..74847f06474 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -1,6 +1,6 @@ use actix_web::{web, HttpRequest, HttpResponse}; use api_models::user_role::{self as user_role_api, role as role_api}; -use common_enums::{EntityType, TokenPurpose}; +use common_enums::TokenPurpose; use router_env::Flow; use super::AppState; @@ -31,8 +31,7 @@ pub async fn get_authorization_info( user_role_core::get_authorization_info_with_groups(state).await }, &auth::JWTAuth { - permission: Permission::UsersRead, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantUserRead, }, api_locking::LockAction::NotApplicable, )) @@ -69,8 +68,7 @@ pub async fn create_role( json_payload.into_inner(), role_core::create_role, &auth::JWTAuth { - permission: Permission::UsersWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantUserWrite, }, api_locking::LockAction::NotApplicable, )) @@ -95,8 +93,7 @@ pub async fn get_role( role_core::get_role_with_groups(state, user, payload).await }, &auth::JWTAuth { - permission: Permission::UsersRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) @@ -119,8 +116,7 @@ pub async fn update_role( json_payload.into_inner(), |state, user, req, _| role_core::update_role(state, user, req, &role_id), &auth::JWTAuth { - permission: Permission::UsersWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantUserWrite, }, api_locking::LockAction::NotApplicable, )) @@ -141,8 +137,7 @@ pub async fn update_user_role( payload, user_role_core::update_user_role, &auth::JWTAuth { - permission: Permission::UsersWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileUserWrite, }, api_locking::LockAction::NotApplicable, )) @@ -202,8 +197,7 @@ pub async fn delete_user_role( payload.into_inner(), user_role_core::delete_user_role, &auth::JWTAuth { - permission: Permission::UsersWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileUserWrite, }, api_locking::LockAction::NotApplicable, )) @@ -225,8 +219,7 @@ pub async fn get_role_information( user_role_core::get_authorization_info_with_group_tag().await }, &auth::JWTAuth { - permission: Permission::UsersRead, - minimum_entity_level: EntityType::Profile + permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) @@ -270,8 +263,7 @@ pub async fn list_roles_with_info( role_core::list_roles_with_info(state, user_from_token, request) }, &auth::JWTAuth { - permission: Permission::UsersRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) @@ -299,8 +291,7 @@ pub async fn list_invitable_roles_at_entity_level( ) }, &auth::JWTAuth { - permission: Permission::UsersRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) @@ -328,8 +319,7 @@ pub async fn list_updatable_roles_at_entity_level( ) }, &auth::JWTAuth { - permission: Permission::UsersRead, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs index 17c946c4810..56ad42947c2 100644 --- a/crates/router/src/routes/verification.rs +++ b/crates/router/src/routes/verification.rs @@ -1,6 +1,5 @@ use actix_web::{web, HttpRequest, Responder}; use api_models::verifications; -use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -34,8 +33,7 @@ pub async fn apple_pay_merchant_registration( auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { - permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Profile, + permission: Permission::ProfileAccountWrite, }, req.headers(), ), @@ -70,7 +68,6 @@ pub async fn retrieve_apple_pay_verified_domains( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::MerchantAccountRead, - minimum_entity_level: EntityType::Merchant, }, req.headers(), ), diff --git a/crates/router/src/routes/verify_connector.rs b/crates/router/src/routes/verify_connector.rs index 29f8c154bc0..b8e089f0660 100644 --- a/crates/router/src/routes/verify_connector.rs +++ b/crates/router/src/routes/verify_connector.rs @@ -1,6 +1,5 @@ use actix_web::{web, HttpRequest, HttpResponse}; use api_models::verify_connector::VerifyConnectorRequest; -use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::AppState; @@ -25,8 +24,7 @@ pub async fn payment_connector_verify( verify_connector::verify_connector_credentials(state, req, auth.profile_id) }, &auth::JWTAuth { - permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Merchant, + permission: Permission::MerchantConnectorWrite, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/webhook_events.rs b/crates/router/src/routes/webhook_events.rs index 8b94fb61f56..5039f72db31 100644 --- a/crates/router/src/routes/webhook_events.rs +++ b/crates/router/src/routes/webhook_events.rs @@ -1,5 +1,4 @@ use actix_web::{web, HttpRequest, Responder}; -use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use crate::{ @@ -44,8 +43,7 @@ pub async fn list_initial_webhook_delivery_attempts( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: Permission::WebhookEventRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantWebhookEventRead, }, req.headers(), ), @@ -84,8 +82,7 @@ pub async fn list_webhook_delivery_attempts( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: Permission::WebhookEventRead, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantWebhookEventRead, }, req.headers(), ), @@ -124,8 +121,7 @@ pub async fn retry_webhook_delivery_attempt( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: Permission::WebhookEventWrite, - minimum_entity_level: EntityType::Merchant, + required_permission: Permission::MerchantWebhookEventWrite, }, req.headers(), ), diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index b64c5d14f32..e6da2b23301 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -10,7 +10,7 @@ use api_models::payment_methods::PaymentMethodIntentConfirm; use api_models::payouts; use api_models::{payment_methods::PaymentMethodListRequest, payments}; use async_trait::async_trait; -use common_enums::{EntityType, TokenPurpose}; +use common_enums::TokenPurpose; use common_utils::{date_time, id_type}; use error_stack::{report, ResultExt}; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; @@ -1232,7 +1232,6 @@ where #[derive(Debug)] pub(crate) struct JWTAuth { pub permission: Permission, - pub minimum_entity_level: EntityType, } #[async_trait] @@ -1252,7 +1251,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; Ok(( (), @@ -1282,7 +1280,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; Ok(( UserFromToken { @@ -1318,7 +1315,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -1359,7 +1355,6 @@ where pub struct JWTAuthOrganizationFromRoute { pub organization_id: id_type::OrganizationId, pub required_permission: Permission, - pub minimum_entity_level: EntityType, } #[async_trait] @@ -1379,7 +1374,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; // Check if token has access to Organization that has been requested in the route if payload.org_id != self.organization_id { @@ -1398,12 +1392,10 @@ where pub struct JWTAuthMerchantFromRoute { pub merchant_id: id_type::MerchantId, pub required_permission: Permission, - pub minimum_entity_level: EntityType, } pub struct JWTAuthMerchantFromHeader { pub required_permission: Permission, - pub minimum_entity_level: EntityType, } #[async_trait] @@ -1423,7 +1415,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; @@ -1459,7 +1450,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; @@ -1526,7 +1516,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; // Check if token has access to MerchantId that has been requested through query param if payload.merchant_id != self.merchant_id { @@ -1563,7 +1552,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -1606,7 +1594,6 @@ pub struct JWTAuthMerchantAndProfileFromRoute { pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub required_permission: Permission, - pub minimum_entity_level: EntityType, } #[async_trait] @@ -1638,7 +1625,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -1682,7 +1668,6 @@ where pub struct JWTAuthProfileFromRoute { pub profile_id: id_type::ProfileId, pub required_permission: Permission, - pub minimum_entity_level: EntityType, } #[async_trait] @@ -1702,7 +1687,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.required_permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -1798,7 +1782,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -1859,7 +1842,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -1923,7 +1905,6 @@ where let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state @@ -2349,7 +2330,6 @@ where } let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(&self.permission, &role_info)?; - authorization::check_entity(self.minimum_entity_level, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index 78af4c00884..fe6ffac6ffc 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -112,18 +112,6 @@ pub fn check_permission( ) } -pub fn check_entity( - required_minimum_entity: common_enums::EntityType, - role_info: &roles::RoleInfo, -) -> RouterResult<()> { - if required_minimum_entity > role_info.get_entity_type() { - Err(ApiErrorResponse::AccessForbidden { - resource: required_minimum_entity.to_string(), - })?; - } - Ok(()) -} - fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { state .store() diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index 031e0b56729..dba96dac188 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -1,5 +1,5 @@ -use api_models::user_role::{GroupInfo, ParentGroup}; -use common_enums::PermissionGroup; +use api_models::user_role::GroupInfo; +use common_enums::{ParentGroup, PermissionGroup}; use strum::IntoEnumIterator; // TODO: To be deprecated diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs index aafc9cee943..3d1a0c8ea5b 100644 --- a/crates/router/src/services/authorization/permission_groups.rs +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -1,97 +1,122 @@ -use common_enums::PermissionGroup; - -use super::permissions::Permission; - -pub fn get_permissions_vec(permission_group: &PermissionGroup) -> &[Permission] { - match permission_group { - PermissionGroup::OperationsView => &OPERATIONS_VIEW, - PermissionGroup::OperationsManage => &OPERATIONS_MANAGE, - PermissionGroup::ConnectorsView => &CONNECTORS_VIEW, - PermissionGroup::ConnectorsManage => &CONNECTORS_MANAGE, - PermissionGroup::WorkflowsView => &WORKFLOWS_VIEW, - PermissionGroup::WorkflowsManage => &WORKFLOWS_MANAGE, - PermissionGroup::AnalyticsView => &ANALYTICS_VIEW, - PermissionGroup::UsersView => &USERS_VIEW, - PermissionGroup::UsersManage => &USERS_MANAGE, - PermissionGroup::MerchantDetailsView => &MERCHANT_DETAILS_VIEW, - PermissionGroup::MerchantDetailsManage => &MERCHANT_DETAILS_MANAGE, - PermissionGroup::OrganizationManage => &ORGANIZATION_MANAGE, - PermissionGroup::ReconOps => &RECON, - } +use common_enums::{ParentGroup, PermissionGroup, PermissionScope, Resource}; + +pub trait PermissionGroupExt { + fn scope(&self) -> PermissionScope; + fn parent(&self) -> ParentGroup; + fn resources(&self) -> Vec<Resource>; + fn accessible_groups(&self) -> Vec<PermissionGroup>; } -pub static OPERATIONS_VIEW: [Permission; 8] = [ - Permission::PaymentRead, - Permission::RefundRead, - Permission::MandateRead, - Permission::DisputeRead, - Permission::CustomerRead, - Permission::GenerateReport, - Permission::PayoutRead, - Permission::MerchantAccountRead, -]; +impl PermissionGroupExt for PermissionGroup { + fn scope(&self) -> PermissionScope { + match self { + Self::OperationsView + | Self::ConnectorsView + | Self::WorkflowsView + | Self::AnalyticsView + | Self::UsersView + | Self::MerchantDetailsView => PermissionScope::Read, -pub static OPERATIONS_MANAGE: [Permission; 7] = [ - Permission::PaymentWrite, - Permission::RefundWrite, - Permission::MandateWrite, - Permission::DisputeWrite, - Permission::CustomerWrite, - Permission::PayoutWrite, - Permission::MerchantAccountRead, -]; + Self::OperationsManage + | Self::ConnectorsManage + | Self::WorkflowsManage + | Self::UsersManage + | Self::MerchantDetailsManage + | Self::OrganizationManage + | Self::ReconOps => PermissionScope::Write, + } + } -pub static CONNECTORS_VIEW: [Permission; 2] = [ - Permission::MerchantConnectorAccountRead, - Permission::MerchantAccountRead, -]; + fn parent(&self) -> ParentGroup { + match self { + Self::OperationsView | Self::OperationsManage => ParentGroup::Operations, + Self::ConnectorsView | Self::ConnectorsManage => ParentGroup::Connectors, + Self::WorkflowsView | Self::WorkflowsManage => ParentGroup::Workflows, + Self::AnalyticsView => ParentGroup::Analytics, + Self::UsersView | Self::UsersManage => ParentGroup::Users, + Self::MerchantDetailsView | Self::MerchantDetailsManage => ParentGroup::Merchant, + Self::OrganizationManage => ParentGroup::Organization, + Self::ReconOps => ParentGroup::Recon, + } + } -pub static CONNECTORS_MANAGE: [Permission; 2] = [ - Permission::MerchantConnectorAccountWrite, - Permission::MerchantAccountRead, -]; + fn resources(&self) -> Vec<Resource> { + self.parent().resources() + } -pub static WORKFLOWS_VIEW: [Permission; 5] = [ - Permission::RoutingRead, - Permission::ThreeDsDecisionManagerRead, - Permission::SurchargeDecisionManagerRead, - Permission::MerchantConnectorAccountRead, - Permission::MerchantAccountRead, -]; + fn accessible_groups(&self) -> Vec<Self> { + match self { + Self::OperationsView => vec![Self::OperationsView], + Self::OperationsManage => vec![Self::OperationsView, Self::OperationsManage], -pub static WORKFLOWS_MANAGE: [Permission; 5] = [ - Permission::RoutingWrite, - Permission::ThreeDsDecisionManagerWrite, - Permission::SurchargeDecisionManagerWrite, - Permission::MerchantConnectorAccountRead, - Permission::MerchantAccountRead, -]; + Self::ConnectorsView => vec![Self::ConnectorsView], + Self::ConnectorsManage => vec![Self::ConnectorsView, Self::ConnectorsManage], -pub static ANALYTICS_VIEW: [Permission; 3] = [ - Permission::Analytics, - Permission::GenerateReport, - Permission::MerchantAccountRead, -]; + Self::WorkflowsView => vec![Self::WorkflowsView], + Self::WorkflowsManage => vec![Self::WorkflowsView, Self::WorkflowsManage], + + Self::AnalyticsView => vec![Self::AnalyticsView], -pub static USERS_VIEW: [Permission; 2] = [Permission::UsersRead, Permission::MerchantAccountRead]; + Self::UsersView => vec![Self::UsersView], + Self::UsersManage => { + vec![Self::UsersView, Self::UsersManage] + } -pub static USERS_MANAGE: [Permission; 2] = - [Permission::UsersWrite, Permission::MerchantAccountRead]; + Self::ReconOps => vec![Self::ReconOps], -pub static MERCHANT_DETAILS_VIEW: [Permission; 1] = [Permission::MerchantAccountRead]; + Self::MerchantDetailsView => vec![Self::MerchantDetailsView], + Self::MerchantDetailsManage => { + vec![Self::MerchantDetailsView, Self::MerchantDetailsManage] + } -pub static MERCHANT_DETAILS_MANAGE: [Permission; 6] = [ - Permission::MerchantAccountWrite, - Permission::ApiKeyRead, - Permission::ApiKeyWrite, - Permission::MerchantAccountRead, - Permission::WebhookEventRead, - Permission::WebhookEventWrite, + Self::OrganizationManage => vec![Self::OrganizationManage], + } + } +} + +pub trait ParentGroupExt { + fn resources(&self) -> Vec<Resource>; +} + +impl ParentGroupExt for ParentGroup { + fn resources(&self) -> Vec<Resource> { + match self { + Self::Operations => OPERATIONS.to_vec(), + Self::Connectors => CONNECTORS.to_vec(), + Self::Workflows => WORKFLOWS.to_vec(), + Self::Analytics => ANALYTICS.to_vec(), + Self::Users => USERS.to_vec(), + Self::Merchant | Self::Organization => ACCOUNT.to_vec(), + Self::Recon => RECON.to_vec(), + } + } +} + +pub static OPERATIONS: [Resource; 8] = [ + Resource::Payment, + Resource::Refund, + Resource::Mandate, + Resource::Dispute, + Resource::Customer, + Resource::Payout, + Resource::Report, + Resource::Account, ]; -pub static ORGANIZATION_MANAGE: [Permission; 2] = [ - Permission::MerchantAccountCreate, - Permission::MerchantAccountRead, +pub static CONNECTORS: [Resource; 2] = [Resource::Connector, Resource::Account]; + +pub static WORKFLOWS: [Resource; 5] = [ + Resource::Routing, + Resource::ThreeDsDecisionManager, + Resource::SurchargeDecisionManager, + Resource::Connector, + Resource::Account, ]; -pub static RECON: [Permission; 1] = [Permission::ReconAdmin]; +pub static ANALYTICS: [Resource; 3] = [Resource::Analytics, Resource::Report, Resource::Account]; + +pub static USERS: [Resource; 2] = [Resource::User, Resource::Account]; + +pub static ACCOUNT: [Resource; 3] = [Resource::Account, Resource::ApiKey, Resource::WebhookEvent]; + +pub static RECON: [Resource; 1] = [Resource::Recon]; diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 2121ba0f944..0521db7acc1 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -1,39 +1,75 @@ -use strum::Display; +use common_enums::{EntityType, PermissionScope, Resource}; +use router_derive::generate_permissions; -#[derive( - PartialEq, Display, Clone, Debug, Copy, Eq, Hash, serde::Deserialize, serde::Serialize, -)] -pub enum Permission { - PaymentRead, - PaymentWrite, - RefundRead, - RefundWrite, - ApiKeyRead, - ApiKeyWrite, - MerchantAccountRead, - MerchantAccountWrite, - MerchantConnectorAccountRead, - MerchantConnectorAccountWrite, - RoutingRead, - RoutingWrite, - DisputeRead, - DisputeWrite, - MandateRead, - MandateWrite, - CustomerRead, - CustomerWrite, - Analytics, - ThreeDsDecisionManagerWrite, - ThreeDsDecisionManagerRead, - SurchargeDecisionManagerWrite, - SurchargeDecisionManagerRead, - UsersRead, - UsersWrite, - MerchantAccountCreate, - WebhookEventRead, - WebhookEventWrite, - PayoutRead, - PayoutWrite, - GenerateReport, - ReconAdmin, +generate_permissions! { + permissions: [ + Payment: { + scopes: [Read, Write], + entities: [Profile, Merchant] + }, + Refund: { + scopes: [Read, Write], + entities: [Profile, Merchant] + }, + Dispute: { + scopes: [Read, Write], + entities: [Profile, Merchant] + }, + Mandate: { + scopes: [Read, Write], + entities: [Merchant] + }, + Customer: { + scopes: [Read, Write], + entities: [Merchant] + }, + Payout: { + scopes: [Read], + entities: [Profile, Merchant] + }, + ApiKey: { + scopes: [Read, Write], + entities: [Merchant] + }, + Account: { + scopes: [Read, Write], + entities: [Profile, Merchant, Organization] + }, + Connector: { + scopes: [Read, Write], + entities: [Profile, Merchant] + }, + Routing: { + scopes: [Read, Write], + entities: [Profile, Merchant] + }, + ThreeDsDecisionManager: { + scopes: [Read, Write], + entities: [Merchant] + }, + SurchargeDecisionManager: { + scopes: [Read, Write], + entities: [Merchant] + }, + Analytics: { + scopes: [Read], + entities: [Profile, Merchant, Organization] + }, + Report: { + scopes: [Read], + entities: [Profile, Merchant, Organization] + }, + User: { + scopes: [Read, Write], + entities: [Profile, Merchant] + }, + WebhookEvent: { + scopes: [Read, Write], + entities: [Merchant] + }, + Recon: { + scopes: [Write], + entities: [Merchant] + }, + ] } diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs index 19383f010f2..63d547bfa67 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -1,9 +1,9 @@ use std::collections::HashSet; -use common_enums::{EntityType, PermissionGroup, RoleScope}; +use common_enums::{EntityType, PermissionGroup, Resource, RoleScope}; use common_utils::{errors::CustomResult, id_type}; -use super::{permission_groups::get_permissions_vec, permissions::Permission}; +use super::{permission_groups::PermissionGroupExt, permissions::Permission}; use crate::{core::errors, routes::SessionState}; pub mod predefined_roles; @@ -30,8 +30,13 @@ impl RoleInfo { &self.role_name } - pub fn get_permission_groups(&self) -> &Vec<PermissionGroup> { - &self.groups + pub fn get_permission_groups(&self) -> Vec<PermissionGroup> { + self.groups + .iter() + .flat_map(|group| group.accessible_groups()) + .collect::<HashSet<_>>() + .into_iter() + .collect() } pub fn get_scope(&self) -> RoleScope { @@ -58,17 +63,19 @@ impl RoleInfo { self.is_updatable } - pub fn get_permissions_set(&self) -> HashSet<Permission> { - self.groups + pub fn get_resources_set(&self) -> HashSet<Resource> { + self.get_permission_groups() .iter() - .flat_map(|group| get_permissions_vec(group).iter().copied()) + .flat_map(|group| group.resources()) .collect() } pub fn check_permission_exists(&self, required_permission: &Permission) -> bool { - self.groups - .iter() - .any(|group| get_permissions_vec(group).contains(required_permission)) + required_permission.entity_type() <= self.entity_type + && self.get_permission_groups().iter().any(|group| { + required_permission.scope() <= group.scope() + && group.resources().contains(&required_permission.resource()) + }) } pub async fn from_role_id_in_merchant_scope( diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index 02179934e38..69865512a37 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -694,3 +694,58 @@ pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenSt proc_macro::TokenStream::from(expanded) } + +/// Generates the permissions enum and implematations for the permissions +/// +/// **NOTE:** You have to make sure that all the identifiers used +/// in the macro input are present in the respective enums as well. +/// +/// ## Usage +/// ``` +/// use router_derive::generate_permissions; +/// +/// enum Scope { +/// Read, +/// Write, +/// } +/// +/// enum EntityType { +/// Profile, +/// Merchant, +/// Org, +/// } +/// +/// enum Resource { +/// Payments, +/// Refunds, +/// } +/// +/// generate_permissions! { +/// permissions: [ +/// Payments: { +/// scopes: [Read, Write], +/// entities: [Profile, Merchant, Org] +/// }, +/// Refunds: { +/// scopes: [Read], +/// entities: [Profile, Org] +/// } +/// ] +/// } +/// ``` +/// This will generate the following enum. +/// ``` +/// enum Permission { +/// ProfilePaymentsRead, +/// ProfilePaymentsWrite, +/// MerchantPaymentsRead, +/// MerchantPaymentsWrite, +/// OrgPaymentsRead, +/// OrgPaymentsWrite, +/// ProfileRefundsRead, +/// OrgRefundsRead, +/// ``` +#[proc_macro] +pub fn generate_permissions(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + macros::generate_permissions_inner(input) +} diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rs index 9a8e514c5c1..32e6c213ca6 100644 --- a/crates/router_derive/src/macros.rs +++ b/crates/router_derive/src/macros.rs @@ -1,5 +1,6 @@ pub(crate) mod api_error; pub(crate) mod diesel; +pub(crate) mod generate_permissions; pub(crate) mod generate_schema; pub(crate) mod misc; pub(crate) mod operation; @@ -14,6 +15,7 @@ use syn::DeriveInput; pub(crate) use self::{ api_error::api_error_derive_inner, diesel::{diesel_enum_derive_inner, diesel_enum_text_derive_inner}, + generate_permissions::generate_permissions_inner, generate_schema::polymorphic_macro_derive_inner, }; diff --git a/crates/router_derive/src/macros/generate_permissions.rs b/crates/router_derive/src/macros/generate_permissions.rs new file mode 100644 index 00000000000..9b388f102cb --- /dev/null +++ b/crates/router_derive/src/macros/generate_permissions.rs @@ -0,0 +1,135 @@ +use proc_macro::TokenStream; +use quote::{format_ident, quote}; +use syn::{ + braced, bracketed, + parse::{Parse, ParseBuffer, ParseStream}, + parse_macro_input, + punctuated::Punctuated, + token::Comma, + Ident, Token, +}; + +struct ResourceInput { + resource_name: Ident, + scopes: Punctuated<Ident, Token![,]>, + entities: Punctuated<Ident, Token![,]>, +} + +struct Input { + permissions: Punctuated<ResourceInput, Token![,]>, +} + +impl Parse for Input { + fn parse(input: ParseStream<'_>) -> syn::Result<Self> { + let (_permission_label, permissions) = parse_label_with_punctuated_data(input)?; + + Ok(Self { permissions }) + } +} + +impl Parse for ResourceInput { + fn parse(input: ParseStream<'_>) -> syn::Result<Self> { + let resource_name: Ident = input.parse()?; + input.parse::<Token![:]>()?; // Expect ':' + + let content; + braced!(content in input); + + let (_scopes_label, scopes) = parse_label_with_punctuated_data(&content)?; + content.parse::<Comma>()?; + + let (_entities_label, entities) = parse_label_with_punctuated_data(&content)?; + + Ok(Self { + resource_name, + scopes, + entities, + }) + } +} + +fn parse_label_with_punctuated_data<T: Parse>( + input: &ParseBuffer<'_>, +) -> syn::Result<(Ident, Punctuated<T, Token![,]>)> { + let label: Ident = input.parse()?; + input.parse::<Token![:]>()?; // Expect ':' + + let content; + bracketed!(content in input); // Parse the list inside [] + let data = Punctuated::<T, Token![,]>::parse_terminated(&content)?; + + Ok((label, data)) +} + +pub fn generate_permissions_inner(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as Input); + + let res = input.permissions.iter(); + + let mut enum_keys = Vec::new(); + let mut scope_impl_per = Vec::new(); + let mut entity_impl_per = Vec::new(); + let mut resource_impl_per = Vec::new(); + + let mut entity_impl_res = Vec::new(); + + for per in res { + let resource_name = &per.resource_name; + let mut permissions = Vec::new(); + + for scope in per.scopes.iter() { + for entity in per.entities.iter() { + let key = format_ident!("{}{}{}", entity, per.resource_name, scope); + + enum_keys.push(quote! { #key }); + scope_impl_per.push(quote! { Permission::#key => PermissionScope::#scope }); + entity_impl_per.push(quote! { Permission::#key => EntityType::#entity }); + resource_impl_per.push(quote! { Permission::#key => Resource::#resource_name }); + permissions.push(quote! { Permission::#key }); + } + let entities_iter = per.entities.iter(); + entity_impl_res + .push(quote! { Resource::#resource_name => vec![#(EntityType::#entities_iter),*] }); + } + } + + let expanded = quote! { + #[derive( + Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, serde::Serialize, serde::Deserialize, strum::Display + )] + pub enum Permission { + #(#enum_keys),* + } + + impl Permission { + pub fn scope(&self) -> PermissionScope { + match self { + #(#scope_impl_per),* + } + } + pub fn entity_type(&self) -> EntityType { + match self { + #(#entity_impl_per),* + } + } + pub fn resource(&self) -> Resource { + match self { + #(#resource_impl_per),* + } + } + } + + pub trait ResourceExt { + fn entities(&self) -> Vec<EntityType>; + } + + impl ResourceExt for Resource { + fn entities(&self) -> Vec<EntityType> { + match self { + #(#entity_impl_res),* + } + } + } + }; + expanded.into() +}
2024-10-22T12:12:38Z
## Description <!-- Describe your changes in detail --> ### Entity level context in Permissions Currently the permissions we use doesn't have any entity level context. But some of our APIs need that context. For example, 1. `payment/list` - This can only be accessible by merchant level users or higher. Profile level users should not be able to access it. 2. `payment/profile/list` - This can be accessible by all level of users. With current setup, this is not directly possible by the permissions. We had to introduce `min_entity_level` to solve this, but this is very separated from the permissions. To solve this, we need to have entity level context at permissions level itself. ### Scope for permissions The write permissions currently doesn't have access to read APIs, but since write is a superset of read, they should be able to access read APIs as well. So, this PR also introduces scope context in permissions. --- This PR also improves the scalability of permissions, as the more entity levels being added in the control center, this will make it easy to extend the permissions as well. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 4. `crates/router/src/configs` 5. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes [#6391](https://github.com/juspay/hyperswitch/issues/6391). ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This is an internal change, no APIs should be affected and all the APIs should be working as usual.
c7c1e1adabceeb0a03659bf8feb9aa06d85960ea
This is an internal change, no APIs should be affected and all the APIs should be working as usual.
[ "crates/api_models/src/user_role.rs", "crates/common_enums/src/enums.rs", "crates/router/src/analytics.rs", "crates/router/src/core/user_role.rs", "crates/router/src/routes/admin.rs", "crates/router/src/routes/api_keys.rs", "crates/router/src/routes/blocklist.rs", "crates/router/src/routes/connector_onboarding.rs", "crates/router/src/routes/customers.rs", "crates/router/src/routes/disputes.rs", "crates/router/src/routes/mandates.rs", "crates/router/src/routes/payment_methods.rs", "crates/router/src/routes/payments.rs", "crates/router/src/routes/payouts.rs", "crates/router/src/routes/profiles.rs", "crates/router/src/routes/recon.rs", "crates/router/src/routes/refunds.rs", "crates/router/src/routes/routing.rs", "crates/router/src/routes/user.rs", "crates/router/src/routes/user_role.rs", "crates/router/src/routes/verification.rs", "crates/router/src/routes/verify_connector.rs", "crates/router/src/routes/webhook_events.rs", "crates/router/src/services/authentication.rs", "crates/router/src/services/authorization.rs", "crates/router/src/services/authorization/info.rs", "crates/router/src/services/authorization/permission_groups.rs", "crates/router/src/services/authorization/permissions.rs", "crates/router/src/services/authorization/roles.rs", "crates/router_derive/src/lib.rs", "crates/router_derive/src/macros.rs", "crates/router_derive/src/macros/generate_permissions.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6390
Bug: [FIX] fix tenant nomenclature in the code
diff --git a/config/config.example.toml b/config/config.example.toml index 8f04ba49831..b0d3c743673 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -741,7 +741,7 @@ enabled = false global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant +public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant [user_auth_methods] encryption_key = "" # Encryption key used for encrypting data in user_authentication_methods table diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index cfefe9a130f..0eab330652a 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -305,7 +305,7 @@ enabled = false global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } +public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } [user_auth_methods] encryption_key = "user_auth_table_encryption_key" # Encryption key used for encrypting data in user_authentication_methods table diff --git a/config/development.toml b/config/development.toml index d32c3610132..274e605193f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -750,7 +750,7 @@ enabled = false global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} +public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [user_auth_methods] encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index dde0902af91..c8436efd022 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -575,7 +575,7 @@ enabled = false global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } +public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } [user_auth_methods] encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F" diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index 05226739504..5b391b492e0 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -125,21 +125,56 @@ impl Multitenancy { pub fn get_tenants(&self) -> &HashMap<String, Tenant> { &self.tenants.0 } - pub fn get_tenant_names(&self) -> Vec<String> { - self.tenants.0.keys().cloned().collect() + pub fn get_tenant_ids(&self) -> Vec<String> { + self.tenants + .0 + .values() + .map(|tenant| tenant.tenant_id.clone()) + .collect() } pub fn get_tenant(&self, tenant_id: &str) -> Option<&Tenant> { self.tenants.0.get(tenant_id) } } -#[derive(Debug, Deserialize, Clone, Default)] -#[serde(transparent)] +#[derive(Debug, Clone, Default)] pub struct TenantConfig(pub HashMap<String, Tenant>); +impl<'de> Deserialize<'de> for TenantConfig { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + #[derive(Deserialize)] + struct Inner { + base_url: String, + schema: String, + redis_key_prefix: String, + clickhouse_database: String, + } + + let hashmap = <HashMap<String, Inner>>::deserialize(deserializer)?; + + Ok(Self( + hashmap + .into_iter() + .map(|(key, value)| { + ( + key.clone(), + Tenant { + tenant_id: key, + base_url: value.base_url, + schema: value.schema, + redis_key_prefix: value.redis_key_prefix, + clickhouse_database: value.clickhouse_database, + }, + ) + }) + .collect(), + )) + } +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct Tenant { - pub name: String, + pub tenant_id: String, pub base_url: String, pub schema: String, pub redis_key_prefix: String, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 149ee2b8456..61e026ae2c5 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -141,8 +141,12 @@ impl Multitenancy { pub fn get_tenants(&self) -> &HashMap<String, Tenant> { &self.tenants.0 } - pub fn get_tenant_names(&self) -> Vec<String> { - self.tenants.0.keys().cloned().collect() + pub fn get_tenant_ids(&self) -> Vec<String> { + self.tenants + .0 + .values() + .map(|tenant| tenant.tenant_id.clone()) + .collect() } pub fn get_tenant(&self, tenant_id: &str) -> Option<&Tenant> { self.tenants.0.get(tenant_id) @@ -154,13 +158,12 @@ pub struct DecisionConfig { pub base_url: String, } -#[derive(Debug, Deserialize, Clone, Default)] -#[serde(transparent)] +#[derive(Debug, Clone, Default)] pub struct TenantConfig(pub HashMap<String, Tenant>); -#[derive(Debug, Deserialize, Clone, Default)] +#[derive(Debug, Clone, Default)] pub struct Tenant { - pub name: String, + pub tenant_id: String, pub base_url: String, pub schema: String, pub redis_key_prefix: String, @@ -1102,6 +1105,38 @@ where })? } +impl<'de> Deserialize<'de> for TenantConfig { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + #[derive(Deserialize)] + struct Inner { + base_url: String, + schema: String, + redis_key_prefix: String, + clickhouse_database: String, + } + + let hashmap = <HashMap<String, Inner>>::deserialize(deserializer)?; + + Ok(Self( + hashmap + .into_iter() + .map(|(key, value)| { + ( + key.clone(), + Tenant { + tenant_id: key, + base_url: value.base_url, + schema: value.schema, + redis_key_prefix: value.redis_key_prefix, + clickhouse_database: value.clickhouse_database, + }, + ) + }) + .collect(), + )) + } +} + #[cfg(test)] mod hashmap_deserialization_test { #![allow(clippy::unwrap_used)] diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 067b35e1e5e..990a0f0e9ad 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2058,7 +2058,7 @@ pub async fn get_payment_method_from_hs_locker<'a>( merchant_id, payment_method_reference, locker_choice, - state.tenant.name.clone(), + state.tenant.tenant_id.clone(), state.request_id, ) .await @@ -2112,7 +2112,7 @@ pub async fn add_card_to_hs_locker( locker, payload, locker_choice, - state.tenant.name.clone(), + state.tenant.tenant_id.clone(), state.request_id, ) .await?; @@ -2309,7 +2309,7 @@ pub async fn get_card_from_hs_locker<'a>( merchant_id, card_reference, Some(locker_choice), - state.tenant.name.clone(), + state.tenant.tenant_id.clone(), state.request_id, ) .await @@ -2355,7 +2355,7 @@ pub async fn delete_card_from_hs_locker<'a>( customer_id, merchant_id, card_reference, - state.tenant.name.clone(), + state.tenant.tenant_id.clone(), state.request_id, ) .await diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 6b584583174..31cd4234714 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -739,7 +739,7 @@ pub async fn push_metrics_for_success_based_routing( &metrics::CONTEXT, 1, &add_attributes([ - ("tenant", state.tenant.name.clone()), + ("tenant", state.tenant.tenant_id.clone()), ( "merchant_id", payment_attempt.merchant_id.get_string_repr().to_string(), diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs index c80d14b9e25..0185d8a0768 100644 --- a/crates/router/src/middleware.rs +++ b/crates/router/src/middleware.rs @@ -147,10 +147,11 @@ where .and_then(|i| i.to_str().ok()) .map(|s| s.to_owned()); let response_fut = self.service.call(req); + let tenant_id_clone = tenant_id.clone(); Box::pin( async move { - if let Some(tenant_id) = tenant_id { - router_env::tracing::Span::current().record("tenant_id", &tenant_id); + if let Some(tenant) = tenant_id_clone { + router_env::tracing::Span::current().record("tenant_id", tenant); } let response = response_fut.await; router_env::tracing::Span::current().record("golden_log_line", true); @@ -166,7 +167,7 @@ where status_code = Empty, flow = "UNKNOWN", golden_log_line = Empty, - tenant_id = "ta" + tenant_id = &tenant_id ) .or_current(), ), diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 33699ed266a..f11840edf63 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -207,7 +207,7 @@ pub struct AppState { } impl scheduler::SchedulerAppState for AppState { fn get_tenants(&self) -> Vec<String> { - self.conf.multitenancy.get_tenant_names() + self.conf.multitenancy.get_tenant_ids() } } pub trait AppStateInfo { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 6f6eb381669..02d4950a47d 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -721,31 +721,27 @@ where .change_context(errors::ApiErrorResponse::InternalServerError.switch())?; let mut event_type = payload.get_api_event_type(); - let tenants: HashSet<_> = state - .conf - .multitenancy - .get_tenant_names() - .into_iter() - .collect(); let tenant_id = if !state.conf.multitenancy.enabled { DEFAULT_TENANT.to_string() } else { - incoming_request_header + let request_tenant_id = incoming_request_header .get(TENANT_HEADER) .and_then(|value| value.to_str().ok()) - .ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch()) - .map(|req_tenant_id| { - if !tenants.contains(req_tenant_id) { - Err(errors::ApiErrorResponse::InvalidTenant { - tenant_id: req_tenant_id.to_string(), - } - .switch()) - } else { - Ok(req_tenant_id.to_string()) + .ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch())?; + + state + .conf + .multitenancy + .get_tenant(request_tenant_id) + .map(|tenant| tenant.tenant_id.clone()) + .ok_or( + errors::ApiErrorResponse::InvalidTenant { + tenant_id: request_tenant_id.to_string(), } - })?? + .switch(), + )? }; - // let tenant_id = "public".to_string(); + let mut session_state = Arc::new(app_state.clone()).get_session_state(tenant_id.as_str(), || { errors::ApiErrorResponse::InvalidTenant { diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index 98f51725bbe..0291374d54f 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -221,7 +221,7 @@ mod tests { let store = state .stores - .get(state.conf.multitenancy.get_tenant_names().first().unwrap()) + .get(state.conf.multitenancy.get_tenant_ids().first().unwrap()) .unwrap(); let response = store .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly) @@ -304,7 +304,7 @@ mod tests { }; let store = state .stores - .get(state.conf.multitenancy.get_tenant_names().first().unwrap()) + .get(state.conf.multitenancy.get_tenant_ids().first().unwrap()) .unwrap(); store .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly) @@ -401,7 +401,7 @@ mod tests { }; let store = state .stores - .get(state.conf.multitenancy.get_tenant_names().first().unwrap()) + .get(state.conf.multitenancy.get_tenant_ids().first().unwrap()) .unwrap(); store .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly) diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index c8a5ccf9228..11268e15e54 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -369,7 +369,7 @@ enabled = false global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} +public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [email] sender_email = "example@example.com"
2024-10-22T09:27:55Z
## Description <!-- Describe your changes in detail --> This fixes the inconsistent nomenclature used for tenants in router and drainer code ### Additional Changes - [x] This PR modifies application configuration/environment variables ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This will eradicate confusion between `name` and `tenant_id` names in the tenant config. In the config below `public = { base_url = "http://localhost:8080/", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}` The key `public` will be the tenant_id. This PR adds a custom deserializer for this part ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **This cannot be tested on sandbox without enabling Multi Tenancy** 1. Application runs with the changed config and so does drainer 2. Do a request with a valid `x-tenant-id` ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-tenant-id: public' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "1729601216", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` It should return 200 and `tenant-id` should be the which has been passed 3. Try the request with invalid `tenant-id`, It should return an error
04c969866816be286720377e73982e21a3302ba9
**This cannot be tested on sandbox without enabling Multi Tenancy** 1. Application runs with the changed config and so does drainer 2. Do a request with a valid `x-tenant-id` ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-tenant-id: public' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "1729601216", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` It should return 200 and `tenant-id` should be the which has been passed 3. Try the request with invalid `tenant-id`, It should return an error
[ "config/config.example.toml", "config/deployments/env_specific.toml", "config/development.toml", "config/docker_compose.toml", "crates/drainer/src/settings.rs", "crates/router/src/configs/settings.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/routing/helpers.rs", "crates/router/src/middleware.rs", "crates/router/src/routes/app.rs", "crates/router/src/services/api.rs", "crates/router/src/types/storage/payment_attempt.rs", "loadtest/config/development.toml" ]
juspay/hyperswitch
juspay__hyperswitch-6387
Bug: include the payment_processing_details_at Hyperswitch option only if apple pay token decryption flow is supported for the connector While configuring apple pay iOS flow `payment_processing_details_at` option is shown that can take two values ,`Connector` or `Hyperswitch`. But the `payment_processing_details_at` can be `Hyperswitch` only if the apple pay token decryption flow is implemented for the connector.
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 78f3c627fca..180aadffde3 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -281,7 +281,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[adyen.metadata.google_pay]] name="merchant_name" @@ -484,7 +484,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[authorizedotnet.metadata.google_pay]] name="merchant_name" @@ -813,7 +813,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[bluesnap.metadata.google_pay]] name="merchant_name" @@ -1115,7 +1115,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[checkout.metadata.google_pay]] name="merchant_name" @@ -1941,7 +1941,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [nexixpay] [[nexixpay.credit]] @@ -2062,7 +2062,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[nmi.metadata.google_pay]] name="merchant_name" @@ -2202,7 +2202,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[noon.metadata.google_pay]] name="merchant_name" @@ -2379,7 +2379,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[nuvei.metadata.google_pay]] name="merchant_name" @@ -2839,7 +2839,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [shift4] [[shift4.credit]] @@ -3244,7 +3244,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[trustpay.metadata.google_pay]] name="merchant_name" @@ -3473,7 +3473,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[worldpay.metadata.google_pay]] name="merchant_name" @@ -4196,7 +4196,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Hyperswitch"] [fiuu.connector_webhook_details] merchant_secret="Source verification key" \ No newline at end of file diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 9ca992ecad4..c7849fcc227 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -188,7 +188,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[adyen.metadata.google_pay]] name="merchant_name" @@ -352,7 +352,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[authorizedotnet.metadata.google_pay]] name="merchant_name" @@ -477,7 +477,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[bluesnap.metadata.google_pay]] name="merchant_name" @@ -970,7 +970,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[checkout.metadata.google_pay]] name="merchant_name" @@ -1680,7 +1680,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [nexixpay] [[nexixpay.credit]] @@ -2054,7 +2054,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [shift4] [[shift4.credit]] @@ -2359,7 +2359,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[trustpay.metadata.google_pay]] name="merchant_name" @@ -2529,7 +2529,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[worldpay.metadata.google_pay]] name="merchant_name" @@ -3191,7 +3191,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Hyperswitch"] [fiuu.connector_webhook_details] merchant_secret="Source verification key" \ No newline at end of file diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 39421babc87..2a753008e81 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -280,7 +280,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[adyen.metadata.google_pay]] name="merchant_name" @@ -488,7 +488,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[authorizedotnet.metadata.google_pay]] name="merchant_name" @@ -814,7 +814,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[bluesnap.metadata.google_pay]] name="merchant_name" @@ -1115,7 +1115,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[checkout.metadata.google_pay]] name="merchant_name" @@ -1939,7 +1939,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [nexixpay] [[nexixpay.credit]] @@ -2059,7 +2059,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[nmi.metadata.google_pay]] name="merchant_name" @@ -2198,7 +2198,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[noon.metadata.google_pay]] name="merchant_name" @@ -2374,7 +2374,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[nuvei.metadata.google_pay]] name="merchant_name" @@ -2832,7 +2832,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [shift4] [[shift4.credit]] @@ -3235,7 +3235,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[trustpay.metadata.google_pay]] name="merchant_name" @@ -3462,7 +3462,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Connector"] [[worldpay.metadata.google_pay]] name="merchant_name" @@ -4190,7 +4190,7 @@ label="Payment Processing Details At" placeholder="Enter Payment Processing Details At" required=true type="Radio" -options=["Connector","Hyperswitch"] +options=["Hyperswitch"] [fiuu.connector_webhook_details] merchant_secret="Source verification key" \ No newline at end of file
2024-10-22T06:55:26Z
## Description <!-- Describe your changes in detail --> While configuring apple pay iOS flow `payment_processing_details_at` option is shown that can take two values ,`Connector` or `Hyperswitch`. But the `payment_processing_details_at` can be `Hyperswitch` only if the apple pay token decryption flow is implemented for the connector. Currently both connector tokenization and decrypted flow is supported only by Stripe, BOA and Cybersource. And Fiu supports only the decrypted flow. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This pr includes wasam changes to not show the `payment_processing_details_at` `Hyperswitch` when the web apple pay flow is not enabled. Things to test the below radio button with Hyperswitch option should not be shown if apple pay web flow is not enalbed. <img width="562" alt="image" src="https://github.com/user-attachments/assets/1153ebaf-59ca-4098-beeb-afff707fa405">
f3a869ea9a430f3b5177852fb74d0910dc8fbe17
This pr includes wasam changes to not show the `payment_processing_details_at` `Hyperswitch` when the web apple pay flow is not enabled. Things to test the below radio button with Hyperswitch option should not be shown if apple pay web flow is not enalbed. <img width="562" alt="image" src="https://github.com/user-attachments/assets/1153ebaf-59ca-4098-beeb-afff707fa405">
[ "crates/connector_configs/toml/development.toml", "crates/connector_configs/toml/production.toml", "crates/connector_configs/toml/sandbox.toml" ]
juspay/hyperswitch
juspay__hyperswitch-6488
Bug: feat(users): Add profile level custom role Currently only merchant level custom role is allowed with role scope as Merchant and organization The requirement is to add profile level custom role at Organization , Merchant and Profile scope
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs index 7c877cd7477..46e15aafc70 100644 --- a/crates/api_models/src/user_role/role.rs +++ b/crates/api_models/src/user_role/role.rs @@ -7,6 +7,7 @@ pub struct CreateRoleRequest { pub role_name: String, pub groups: Vec<PermissionGroup>, pub role_scope: RoleScope, + pub entity_type: Option<EntityType>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] @@ -21,6 +22,7 @@ pub struct RoleInfoWithGroupsResponse { pub groups: Vec<PermissionGroup>, pub role_name: String, pub role_scope: RoleScope, + pub entity_type: Option<EntityType>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 917030c1e80..e645b884677 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2679,6 +2679,8 @@ pub enum TransactionType { Debug, Eq, PartialEq, + Ord, + PartialOrd, serde::Deserialize, serde::Serialize, strum::Display, @@ -2688,8 +2690,19 @@ pub enum TransactionType { #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoleScope { - Merchant, - Organization, + Organization = 2, + Merchant = 1, + Profile = 0, +} + +impl From<RoleScope> for EntityType { + fn from(role_scope: RoleScope) -> Self { + match role_scope { + RoleScope::Organization => Self::Organization, + RoleScope::Merchant => Self::Merchant, + RoleScope::Profile => Self::Profile, + } + } } /// Indicates the transaction status @@ -3132,6 +3145,7 @@ pub enum ApiVersion { serde::Serialize, strum::Display, strum::EnumString, + strum::EnumIter, ToSchema, Hash, )] diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs index 065a5b6e114..07d2cf2f0a1 100644 --- a/crates/diesel_models/src/query/role.rs +++ b/crates/diesel_models/src/query/role.rs @@ -1,4 +1,5 @@ use async_bb8_diesel::AsyncRunQueryDsl; +use common_enums::EntityType; use common_utils::id_type; use diesel::{ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError, @@ -106,7 +107,7 @@ impl Role { conn: &PgPooledConn, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, - entity_type: Option<common_enums::EntityType>, + entity_type: Option<EntityType>, limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() @@ -131,6 +132,97 @@ impl Role { router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); + match generics::db_metrics::track_database_call::<Self, _, _>( + query.get_results_async(conn), + generics::db_metrics::DatabaseOperation::Filter, + ) + .await + { + Ok(value) => Ok(value), + Err(err) => match err { + DieselError::NotFound => { + Err(report!(err)).change_context(errors::DatabaseError::NotFound) + } + _ => Err(report!(err)).change_context(errors::DatabaseError::Others), + }, + } + } + pub async fn generic_list_roles_by_entity_type( + conn: &PgPooledConn, + entity_type: ListRolesByEntityPayload, + is_lineage_data_required: bool, + limit: Option<u32>, + ) -> StorageResult<Vec<Self>> { + let mut query = <Self as HasTable>::table().into_boxed(); + + match entity_type { + ListRolesByEntityPayload::Organization(org_id) => { + let entity_in_vec = if is_lineage_data_required { + vec![ + EntityType::Organization, + EntityType::Merchant, + EntityType::Profile, + ] + } else { + vec![EntityType::Organization] + }; + query = query + .filter(dsl::org_id.eq(org_id)) + .filter( + dsl::scope + .eq(RoleScope::Organization) + .or(dsl::scope.eq(RoleScope::Merchant)) + .or(dsl::scope.eq(RoleScope::Profile)), + ) + .filter(dsl::entity_type.eq_any(entity_in_vec)) + } + + ListRolesByEntityPayload::Merchant(org_id, merchant_id) => { + let entity_in_vec = if is_lineage_data_required { + vec![EntityType::Merchant, EntityType::Profile] + } else { + vec![EntityType::Merchant] + }; + query = query + .filter(dsl::org_id.eq(org_id)) + .filter( + dsl::scope + .eq(RoleScope::Organization) + .or(dsl::scope + .eq(RoleScope::Merchant) + .and(dsl::merchant_id.eq(merchant_id.clone()))) + .or(dsl::scope + .eq(RoleScope::Profile) + .and(dsl::merchant_id.eq(merchant_id))), + ) + .filter(dsl::entity_type.eq_any(entity_in_vec)) + } + + ListRolesByEntityPayload::Profile(org_id, merchant_id, profile_id) => { + let entity_in_vec = vec![EntityType::Profile]; + query = query + .filter(dsl::org_id.eq(org_id)) + .filter( + dsl::scope + .eq(RoleScope::Organization) + .or(dsl::scope + .eq(RoleScope::Merchant) + .and(dsl::merchant_id.eq(merchant_id.clone()))) + .or(dsl::scope + .eq(RoleScope::Profile) + .and(dsl::merchant_id.eq(merchant_id)) + .and(dsl::profile_id.eq(profile_id))), + ) + .filter(dsl::entity_type.eq_any(entity_in_vec)) + } + }; + + if let Some(limit) = limit { + query = query.limit(limit.into()); + } + + router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); + match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs index 8199bd3979c..d96421f2db8 100644 --- a/crates/diesel_models/src/role.rs +++ b/crates/diesel_models/src/role.rs @@ -19,6 +19,7 @@ pub struct Role { pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, + pub profile_id: Option<id_type::ProfileId>, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -36,6 +37,7 @@ pub struct RoleNew { pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, + pub profile_id: Option<id_type::ProfileId>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] @@ -73,3 +75,13 @@ impl From<RoleUpdate> for RoleUpdateInternal { } } } + +pub enum ListRolesByEntityPayload { + Profile( + id_type::OrganizationId, + id_type::MerchantId, + id_type::ProfileId, + ), + Merchant(id_type::OrganizationId, id_type::MerchantId), + Organization(id_type::OrganizationId), +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index e2ab676b2d3..fd3752cecc9 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1236,6 +1236,8 @@ diesel::table! { last_modified_by -> Varchar, #[max_length = 64] entity_type -> Varchar, + #[max_length = 64] + profile_id -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 5651bf95dd9..c694751f5bd 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1182,6 +1182,8 @@ diesel::table! { last_modified_by -> Varchar, #[max_length = 64] entity_type -> Varchar, + #[max_length = 64] + profile_id -> Nullable<Varchar>, } } diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 0250415d4fd..48f5faccc58 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -3,7 +3,7 @@ use std::collections::HashSet; use api_models::user_role::role::{self as role_api}; use common_enums::{EntityType, ParentGroup, PermissionGroup, RoleScope}; use common_utils::generate_id_with_default_len; -use diesel_models::role::{RoleNew, RoleUpdate}; +use diesel_models::role::{ListRolesByEntityPayload, RoleNew, RoleUpdate}; use error_stack::{report, ResultExt}; use crate::{ @@ -65,6 +65,39 @@ pub async fn create_role( _req_state: ReqState, ) -> UserResponse<role_api::RoleInfoWithGroupsResponse> { let now = common_utils::date_time::now(); + + let user_entity_type = user_from_token + .get_role_info_from_db(&state) + .await + .attach_printable("Invalid role_id in JWT")? + .get_entity_type(); + + let role_entity_type = req.entity_type.unwrap_or(EntityType::Merchant); + + if matches!(role_entity_type, EntityType::Organization) { + return Err(report!(UserErrors::InvalidRoleOperation)) + .attach_printable("User trying to create org level custom role"); + } + + let requestor_entity_from_role_scope = EntityType::from(req.role_scope); + + if !(user_entity_type >= role_entity_type) { + return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( + "{} is trying to create {} ", + user_entity_type, role_entity_type + )); + } else if !(user_entity_type >= requestor_entity_from_role_scope) { + return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( + "{} is trying to create role of scope {} ", + user_entity_type, requestor_entity_from_role_scope + )); + } else if !(requestor_entity_from_role_scope >= role_entity_type) { + return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( + "User is trying to create role of type {} and scope {}", + requestor_entity_from_role_scope, role_entity_type + )); + } + let role_name = RoleName::new(req.role_name)?; utils::user_role::validate_role_groups(&req.groups)?; @@ -76,12 +109,9 @@ pub async fn create_role( ) .await?; - if matches!(req.role_scope, RoleScope::Organization) - && user_from_token.role_id != common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN - { - return Err(report!(UserErrors::InvalidRoleOperation)) - .attach_printable("Non org admin user creating org level role"); - } + let profile_id = matches!(role_entity_type, EntityType::Profile) + .then_some(user_from_token.profile_id) + .flatten(); let role = state .store @@ -92,11 +122,12 @@ pub async fn create_role( org_id: user_from_token.org_id, groups: req.groups, scope: req.role_scope, - entity_type: EntityType::Merchant, + entity_type: role_entity_type, created_by: user_from_token.user_id.clone(), last_modified_by: user_from_token.user_id, created_at: now, last_modified_at: now, + profile_id, }) .await .to_duplicate_response(UserErrors::RoleNameAlreadyExists)?; @@ -107,6 +138,7 @@ pub async fn create_role( role_id: role.role_id, role_name: role.role_name, role_scope: role.scope, + entity_type: Some(role.entity_type), }, )) } @@ -135,6 +167,7 @@ pub async fn get_role_with_groups( role_id: role.role_id, role_name: role_info.get_role_name().to_string(), role_scope: role_info.get_scope(), + entity_type: Some(role_info.get_entity_type()), }, )) } @@ -245,6 +278,7 @@ pub async fn update_role( role_id: updated_role.role_id, role_name: updated_role.role_name, role_scope: updated_role.scope, + entity_type: Some(updated_role.entity_type), }, )) } @@ -276,10 +310,9 @@ pub async fn list_roles_with_info( match utils::user_role::get_min_entity(user_role_entity, request.entity_type)? { EntityType::Organization => state .store - .list_roles_for_org_by_parameters( - &user_from_token.org_id, - None, - request.entity_type, + .generic_list_roles_by_entity_type( + ListRolesByEntityPayload::Organization(user_from_token.org_id), + request.entity_type.is_none(), None, ) .await @@ -287,17 +320,37 @@ pub async fn list_roles_with_info( .attach_printable("Failed to get roles")?, EntityType::Merchant => state .store - .list_roles_for_org_by_parameters( - &user_from_token.org_id, - Some(&user_from_token.merchant_id), - request.entity_type, + .generic_list_roles_by_entity_type( + ListRolesByEntityPayload::Merchant( + user_from_token.org_id, + user_from_token.merchant_id, + ), + request.entity_type.is_none(), None, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get roles")?, - // TODO: Populate this from Db function when support for profile id and profile level custom roles is added - EntityType::Profile => Vec::new(), + + EntityType::Profile => { + let Some(profile_id) = user_from_token.profile_id else { + return Err(UserErrors::JwtProfileIdMissing.into()); + }; + state + .store + .generic_list_roles_by_entity_type( + ListRolesByEntityPayload::Profile( + user_from_token.org_id, + user_from_token.merchant_id, + profile_id, + ), + request.entity_type.is_none(), + None, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get roles")? + } }; role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from)); @@ -349,10 +402,9 @@ pub async fn list_roles_at_entity_level( let custom_roles = match req.entity_type { EntityType::Organization => state .store - .list_roles_for_org_by_parameters( - &user_from_token.org_id, - None, - Some(req.entity_type), + .generic_list_roles_by_entity_type( + ListRolesByEntityPayload::Organization(user_from_token.org_id), + false, None, ) .await @@ -361,17 +413,38 @@ pub async fn list_roles_at_entity_level( EntityType::Merchant => state .store - .list_roles_for_org_by_parameters( - &user_from_token.org_id, - Some(&user_from_token.merchant_id), - Some(req.entity_type), + .generic_list_roles_by_entity_type( + ListRolesByEntityPayload::Merchant( + user_from_token.org_id, + user_from_token.merchant_id, + ), + false, None, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get roles")?, - // TODO: Populate this from Db function when support for profile id and profile level custom roles is added - EntityType::Profile => Vec::new(), + + EntityType::Profile => { + let Some(profile_id) = user_from_token.profile_id else { + return Err(UserErrors::JwtProfileIdMissing.into()); + }; + + state + .store + .generic_list_roles_by_entity_type( + ListRolesByEntityPayload::Profile( + user_from_token.org_id, + user_from_token.merchant_id, + profile_id, + ), + false, + None, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get roles")? + } }; role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from)); diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 8ca0b293766..58c439c7371 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3534,6 +3534,17 @@ impl RoleInterface for KafkaStore { .list_roles_for_org_by_parameters(org_id, merchant_id, entity_type, limit) .await } + + async fn generic_list_roles_by_entity_type( + &self, + entity_type: diesel_models::role::ListRolesByEntityPayload, + is_lineage_data_required: bool, + limit: Option<u32>, + ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { + self.diesel_store + .generic_list_roles_by_entity_type(entity_type, is_lineage_data_required, limit) + .await + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs index d13508356e5..4ec50de023d 100644 --- a/crates/router/src/db/role.rs +++ b/crates/router/src/db/role.rs @@ -1,6 +1,8 @@ -use common_enums::enums; use common_utils::id_type; -use diesel_models::role as storage; +use diesel_models::{ + enums::{EntityType, RoleScope}, + role as storage, +}; use error_stack::report; use router_env::{instrument, tracing}; @@ -57,7 +59,14 @@ pub trait RoleInterface { &self, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, - entity_type: Option<enums::EntityType>, + entity_type: Option<EntityType>, + limit: Option<u32>, + ) -> CustomResult<Vec<storage::Role>, errors::StorageError>; + + async fn generic_list_roles_by_entity_type( + &self, + entity_type: storage::ListRolesByEntityPayload, + is_lineage_data_required: bool, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError>; } @@ -151,7 +160,7 @@ impl RoleInterface for Store { &self, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, - entity_type: Option<enums::EntityType>, + entity_type: Option<EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -165,6 +174,24 @@ impl RoleInterface for Store { .await .map_err(|error| report!(errors::StorageError::from(error))) } + + #[instrument(skip_all)] + async fn generic_list_roles_by_entity_type( + &self, + entity_type: storage::ListRolesByEntityPayload, + is_lineage_data_required: bool, + limit: Option<u32>, + ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::Role::generic_list_roles_by_entity_type( + &conn, + entity_type, + is_lineage_data_required, + limit, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } } #[async_trait::async_trait] @@ -195,6 +222,7 @@ impl RoleInterface for MockDb { created_at: role.created_at, last_modified_at: role.last_modified_at, last_modified_by: role.last_modified_by, + profile_id: role.profile_id, }; roles.push(role.clone()); Ok(role) @@ -229,7 +257,7 @@ impl RoleInterface for MockDb { .find(|role| { role.role_id == role_id && (role.merchant_id == *merchant_id - || (role.org_id == *org_id && role.scope == enums::RoleScope::Organization)) + || (role.org_id == *org_id && role.scope == RoleScope::Organization)) }) .cloned() .ok_or( @@ -319,8 +347,7 @@ impl RoleInterface for MockDb { .iter() .filter(|role| { role.merchant_id == *merchant_id - || (role.org_id == *org_id - && role.scope == diesel_models::enums::RoleScope::Organization) + || (role.org_id == *org_id && role.scope == RoleScope::Organization) }) .cloned() .collect(); @@ -341,7 +368,7 @@ impl RoleInterface for MockDb { &self, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, - entity_type: Option<enums::EntityType>, + entity_type: Option<EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let roles = self.roles.lock().await; @@ -362,4 +389,83 @@ impl RoleInterface for MockDb { Ok(roles_list) } + + #[instrument(skip_all)] + async fn generic_list_roles_by_entity_type( + &self, + entity_type: storage::ListRolesByEntityPayload, + is_lineage_data_required: bool, + limit: Option<u32>, + ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { + let roles = self.roles.lock().await; + let limit_usize = limit.unwrap_or(u32::MAX).try_into().unwrap_or(usize::MAX); + let roles_list: Vec<_> = roles + .iter() + .filter(|role| match &entity_type { + storage::ListRolesByEntityPayload::Organization(org_id) => { + let entity_in_vec = if is_lineage_data_required { + vec![ + EntityType::Organization, + EntityType::Merchant, + EntityType::Profile, + ] + } else { + vec![EntityType::Organization] + }; + + let matches_scope = role.scope == RoleScope::Organization + || role.scope == RoleScope::Merchant + || role.scope == RoleScope::Profile; + + role.org_id == *org_id + && (matches_scope) + && entity_in_vec.contains(&role.entity_type) + } + storage::ListRolesByEntityPayload::Merchant(org_id, merchant_id) => { + let entity_in_vec = if is_lineage_data_required { + vec![EntityType::Merchant, EntityType::Profile] + } else { + vec![EntityType::Merchant] + }; + + let matches_merchant = + role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant; + let matches_profile = + role.merchant_id == *merchant_id && role.scope == RoleScope::Profile; + + role.org_id == *org_id + && (role.scope == RoleScope::Organization + || matches_merchant + || matches_profile) + && entity_in_vec.contains(&role.entity_type) + } + storage::ListRolesByEntityPayload::Profile(org_id, merchant_id, profile_id) => { + let entity_in_vec = [EntityType::Profile]; + + let matches_merchant = + role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant; + + let matches_profile = role.merchant_id == *merchant_id + && role + .profile_id + .as_ref() + .map(|profile_id_from_role| { + profile_id_from_role == profile_id + && role.scope == RoleScope::Profile + }) + .unwrap_or(true); + + role.org_id == *org_id + && (role.scope == RoleScope::Organization + || matches_merchant + || matches_profile) + && entity_in_vec.contains(&role.entity_type) + } + }) + .take(limit_usize) + .cloned() + .collect(); + + Ok(roles_list) + } } diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 9910cef3950..79b9be6b803 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -88,7 +88,7 @@ pub async fn create_role( json_payload.into_inner(), role_core::create_role, &auth::JWTAuth { - permission: Permission::MerchantUserWrite, + permission: Permission::ProfileUserWrite, }, api_locking::LockAction::NotApplicable, )) diff --git a/migrations/2024-10-17-073555_add-profile-id-to-roles/down.sql b/migrations/2024-10-17-073555_add-profile-id-to-roles/down.sql new file mode 100644 index 00000000000..d611be2c3da --- /dev/null +++ b/migrations/2024-10-17-073555_add-profile-id-to-roles/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE roles DROP COLUMN IF EXISTS profile_id; \ No newline at end of file diff --git a/migrations/2024-10-17-073555_add-profile-id-to-roles/up.sql b/migrations/2024-10-17-073555_add-profile-id-to-roles/up.sql new file mode 100644 index 00000000000..b3873266fec --- /dev/null +++ b/migrations/2024-10-17-073555_add-profile-id-to-roles/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE roles ADD COLUMN IF NOT EXISTS profile_id VARCHAR(64); \ No newline at end of file diff --git a/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/down.sql b/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/down.sql new file mode 100644 index 00000000000..c7c9cbeb401 --- /dev/null +++ b/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +SELECT 1; \ No newline at end of file diff --git a/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/up.sql b/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/up.sql new file mode 100644 index 00000000000..6fd9b07fd50 --- /dev/null +++ b/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TYPE "RoleScope" +ADD VALUE IF NOT EXISTS 'profile'; \ No newline at end of file
2024-10-21T12:06:08Z
## Description <!-- Describe your changes in detail --> Earlier we only had access to create Merchant level custom role at Org and Merchant scope . But after this user can be able to create custom role at Profile level at Organization , Merchant and Profile scope ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes [6488](https://github.com/juspay/hyperswitch/issues/6488) ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **Create Custom role at profile level** ```sh curl --location 'http://localhost:8080/user/role' \ --header 'authorization: Bearer user JWT Token' \ --data '{ "role_scope": "organization", "groups": [ "operations_view", "operations_manage", "connectors_view" ], "role_name": "org-scope-profile-role-org-user", "entity_type":"profile" }' ``` Response : ```json { "role_id": "some_role_id", "groups": [ "operations_view", "operations_manage", "connectors_view" ], "role_name": "org-scope-profile-role-org-user", "role_scope": "organization", "entity_type": "profile" } ``` To create a profile level custom role , the following scenarios the operation should be allowed | Role scope | Org level user | merchant level user | Profile level user | |-------------|----------------|---------------------|--------------------| | Org | true | false | false | | Merchant | true | true | false | | Profile | true | true | true | **Create Custom role at merchant level** ```sh curl --location 'http://localhost:8080/user/role' \ --header 'authorization: Bearer user JWT Token' \ --data '{ "role_scope": "organization", "groups": [ "operations_view", "operations_manage", "connectors_view" ], "role_name": "org-scope-merchnant-role-org-user", "entity_type":"merchant" }' ``` Response : ```json { "role_id": "some_role_id", "groups": [ "operations_view", "operations_manage", "connectors_view" ], "role_name": "org-scope-merchnant-role-org-user", "role_scope": "organization", "entity_type": "merchant" } ``` To create a merchant level custom role , the following scenarios the operation should be allowed | Role scope | Org level user | merchant level user | Profile level user | |-------------|----------------|---------------------|--------------------| | Org | true | false | false | | Merchant | true | true | false | | Profile | false | false | false |
adc5262f130e25e9d711915ea9ad587bcbd0118f
**Create Custom role at profile level** ```sh curl --location 'http://localhost:8080/user/role' \ --header 'authorization: Bearer user JWT Token' \ --data '{ "role_scope": "organization", "groups": [ "operations_view", "operations_manage", "connectors_view" ], "role_name": "org-scope-profile-role-org-user", "entity_type":"profile" }' ``` Response : ```json { "role_id": "some_role_id", "groups": [ "operations_view", "operations_manage", "connectors_view" ], "role_name": "org-scope-profile-role-org-user", "role_scope": "organization", "entity_type": "profile" } ``` To create a profile level custom role , the following scenarios the operation should be allowed | Role scope | Org level user | merchant level user | Profile level user | |-------------|----------------|---------------------|--------------------| | Org | true | false | false | | Merchant | true | true | false | | Profile | true | true | true | **Create Custom role at merchant level** ```sh curl --location 'http://localhost:8080/user/role' \ --header 'authorization: Bearer user JWT Token' \ --data '{ "role_scope": "organization", "groups": [ "operations_view", "operations_manage", "connectors_view" ], "role_name": "org-scope-merchnant-role-org-user", "entity_type":"merchant" }' ``` Response : ```json { "role_id": "some_role_id", "groups": [ "operations_view", "operations_manage", "connectors_view" ], "role_name": "org-scope-merchnant-role-org-user", "role_scope": "organization", "entity_type": "merchant" } ``` To create a merchant level custom role , the following scenarios the operation should be allowed | Role scope | Org level user | merchant level user | Profile level user | |-------------|----------------|---------------------|--------------------| | Org | true | false | false | | Merchant | true | true | false | | Profile | false | false | false |
[ "crates/api_models/src/user_role/role.rs", "crates/common_enums/src/enums.rs", "crates/diesel_models/src/query/role.rs", "crates/diesel_models/src/role.rs", "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/schema_v2.rs", "crates/router/src/core/user_role/role.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/db/role.rs", "crates/router/src/routes/user_role.rs", "migrations/2024-10-17-073555_add-profile-id-to-roles/down.sql", "migrations/2024-10-17-073555_add-profile-id-to-roles/up.sql", "migrations/2024-10-17-123943_add-profile-enum-in-role-scope/down.sql", "migrations/2024-10-17-123943_add-profile-enum-in-role-scope/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-6375
Bug: refactor(permissions): Deprecate permissions from permission info API response The permissions in the permission info API are not being used and should be removed.
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index ab32651e729..e64639646d1 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -4,42 +4,6 @@ use masking::Secret; pub mod role; -#[derive(Debug, serde::Serialize)] -pub enum Permission { - PaymentRead, - PaymentWrite, - RefundRead, - RefundWrite, - ApiKeyRead, - ApiKeyWrite, - MerchantAccountRead, - MerchantAccountWrite, - MerchantConnectorAccountRead, - MerchantConnectorAccountWrite, - RoutingRead, - RoutingWrite, - DisputeRead, - DisputeWrite, - MandateRead, - MandateWrite, - CustomerRead, - CustomerWrite, - Analytics, - ThreeDsDecisionManagerWrite, - ThreeDsDecisionManagerRead, - SurchargeDecisionManagerWrite, - SurchargeDecisionManagerRead, - UsersRead, - UsersWrite, - MerchantAccountCreate, - WebhookEventRead, - PayoutWrite, - PayoutRead, - WebhookEventWrite, - GenerateReport, - ReconAdmin, -} - #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash)] pub enum ParentGroup { Operations, @@ -69,7 +33,6 @@ pub enum AuthorizationInfo { pub struct GroupInfo { pub group: PermissionGroup, pub description: &'static str, - pub permissions: Vec<PermissionInfo>, } #[derive(Debug, serde::Serialize, Clone)] @@ -79,12 +42,6 @@ pub struct ParentInfo { pub groups: Vec<PermissionGroup>, } -#[derive(Debug, serde::Serialize)] -pub struct PermissionInfo { - pub enum_name: Permission, - pub description: &'static str, -} - #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateUserRoleRequest { pub email: pii::Email, diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index 7cfde3efeea..031e0b56729 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -1,9 +1,7 @@ -use api_models::user_role::{GroupInfo, ParentGroup, PermissionInfo}; +use api_models::user_role::{GroupInfo, ParentGroup}; use common_enums::PermissionGroup; use strum::IntoEnumIterator; -use super::{permission_groups::get_permissions_vec, permissions::Permission}; - // TODO: To be deprecated pub fn get_group_authorization_info() -> Vec<GroupInfo> { PermissionGroup::iter() @@ -11,25 +9,10 @@ pub fn get_group_authorization_info() -> Vec<GroupInfo> { .collect() } -// TODO: To be deprecated -pub fn get_permission_info_from_permissions(permissions: &[Permission]) -> Vec<PermissionInfo> { - permissions - .iter() - .map(|&per| PermissionInfo { - description: Permission::get_permission_description(&per), - enum_name: per.into(), - }) - .collect() -} - // TODO: To be deprecated fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo { let description = get_group_description(group); - GroupInfo { - group, - description, - permissions: get_permission_info_from_permissions(get_permissions_vec(&group)), - } + GroupInfo { group, description } } // TODO: To be deprecated diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 2f0617557ca..2121ba0f944 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -37,48 +37,3 @@ pub enum Permission { GenerateReport, ReconAdmin, } - -impl Permission { - pub fn get_permission_description(&self) -> &'static str { - match self { - Self::PaymentRead => "View all payments", - Self::PaymentWrite => "Create payment, download payments data", - Self::RefundRead => "View all refunds", - Self::RefundWrite => "Create refund, download refunds data", - Self::ApiKeyRead => "View API keys", - Self::ApiKeyWrite => "Create and update API keys", - Self::MerchantAccountRead => "View merchant account details", - Self::MerchantAccountWrite => { - "Update merchant account details, configure webhooks, manage api keys" - } - Self::MerchantConnectorAccountRead => "View connectors configured", - Self::MerchantConnectorAccountWrite => { - "Create, update, verify and delete connector configurations" - } - Self::RoutingRead => "View routing configuration", - Self::RoutingWrite => "Create and activate routing configurations", - Self::DisputeRead => "View disputes", - Self::DisputeWrite => "Create and update disputes", - Self::MandateRead => "View mandates", - Self::MandateWrite => "Create and update mandates", - Self::CustomerRead => "View customers", - Self::CustomerWrite => "Create, update and delete customers", - Self::Analytics => "Access to analytics module", - Self::ThreeDsDecisionManagerWrite => "Create and update 3DS decision rules", - Self::ThreeDsDecisionManagerRead => { - "View all 3DS decision rules configured for a merchant" - } - Self::SurchargeDecisionManagerWrite => "Create and update the surcharge decision rules", - Self::SurchargeDecisionManagerRead => "View all the surcharge decision rules", - Self::UsersRead => "View all the users for a merchant", - Self::UsersWrite => "Invite users, assign and update roles", - Self::MerchantAccountCreate => "Create merchant account", - Self::WebhookEventRead => "View webhook events", - Self::WebhookEventWrite => "Trigger retries for webhook events", - Self::PayoutRead => "View all payouts", - Self::PayoutWrite => "Create payout, download payout data", - Self::GenerateReport => "Generate reports for payments, refunds and disputes", - Self::ReconAdmin => "View and manage reconciliation reports", - } - } -} diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 0ea423989f5..6f0d94d2927 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,6 +1,5 @@ use std::{cmp, collections::HashSet}; -use api_models::user_role as user_role_api; use common_enums::{EntityType, PermissionGroup}; use common_utils::id_type; use diesel_models::{ @@ -16,49 +15,10 @@ use crate::{ core::errors::{UserErrors, UserResult}, db::user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload}, routes::SessionState, - services::authorization::{self as authz, permissions::Permission, roles}, + services::authorization::{self as authz, roles}, types::domain, }; -impl From<Permission> for user_role_api::Permission { - fn from(value: Permission) -> Self { - match value { - Permission::PaymentRead => Self::PaymentRead, - Permission::PaymentWrite => Self::PaymentWrite, - Permission::RefundRead => Self::RefundRead, - Permission::RefundWrite => Self::RefundWrite, - Permission::ApiKeyRead => Self::ApiKeyRead, - Permission::ApiKeyWrite => Self::ApiKeyWrite, - Permission::MerchantAccountRead => Self::MerchantAccountRead, - Permission::MerchantAccountWrite => Self::MerchantAccountWrite, - Permission::MerchantConnectorAccountRead => Self::MerchantConnectorAccountRead, - Permission::MerchantConnectorAccountWrite => Self::MerchantConnectorAccountWrite, - Permission::RoutingRead => Self::RoutingRead, - Permission::RoutingWrite => Self::RoutingWrite, - Permission::DisputeRead => Self::DisputeRead, - Permission::DisputeWrite => Self::DisputeWrite, - Permission::MandateRead => Self::MandateRead, - Permission::MandateWrite => Self::MandateWrite, - Permission::CustomerRead => Self::CustomerRead, - Permission::CustomerWrite => Self::CustomerWrite, - Permission::Analytics => Self::Analytics, - Permission::ThreeDsDecisionManagerWrite => Self::ThreeDsDecisionManagerWrite, - Permission::ThreeDsDecisionManagerRead => Self::ThreeDsDecisionManagerRead, - Permission::SurchargeDecisionManagerWrite => Self::SurchargeDecisionManagerWrite, - Permission::SurchargeDecisionManagerRead => Self::SurchargeDecisionManagerRead, - Permission::UsersRead => Self::UsersRead, - Permission::UsersWrite => Self::UsersWrite, - Permission::MerchantAccountCreate => Self::MerchantAccountCreate, - Permission::WebhookEventRead => Self::WebhookEventRead, - Permission::WebhookEventWrite => Self::WebhookEventWrite, - Permission::PayoutRead => Self::PayoutRead, - Permission::PayoutWrite => Self::PayoutWrite, - Permission::GenerateReport => Self::GenerateReport, - Permission::ReconAdmin => Self::ReconAdmin, - } - } -} - pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> { if groups.is_empty() { return Err(report!(UserErrors::InvalidRoleOperation))
2024-10-21T06:56:03Z
## Description <!-- Describe your changes in detail --> The permissions in the permission info API are not being used and this PR will remove them. This will help the future PRs which will introduce new kind of Permissions. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes [#6375](https://github.com/juspay/hyperswitch/issues/6375). ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'https://sandbox.hyperswitch.io/user/permission_info' \ --header 'Authorization: Bearer JWT' ``` This API will no longer have permissions field in the response. ```json [ { "group": "operations_view", "description": "View Payments, Refunds, Payouts, Mandates, Disputes and Customers" }, { "group": "operations_manage", "description": "Create, modify and delete Payments, Refunds, Payouts, Mandates, Disputes and Customers" } ] ```
0dba763c3a1c69fa282ffa644a12d37dc14d8f7b
``` curl --location 'https://sandbox.hyperswitch.io/user/permission_info' \ --header 'Authorization: Bearer JWT' ``` This API will no longer have permissions field in the response. ```json [ { "group": "operations_view", "description": "View Payments, Refunds, Payouts, Mandates, Disputes and Customers" }, { "group": "operations_manage", "description": "Create, modify and delete Payments, Refunds, Payouts, Mandates, Disputes and Customers" } ] ```
[ "crates/api_models/src/user_role.rs", "crates/router/src/services/authorization/info.rs", "crates/router/src/services/authorization/permissions.rs", "crates/router/src/utils/user_role.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6177
Bug: [FEATURE] integrate 3DS for Worldpay connector ### Feature Description WorldPay offers 3DS capabilities for a card txn. Same needs to be integrated in HyperSwitch. Flow - https://developer.worldpay.com/products/access/3ds/web ### Possible Implementation Implementing 3DS for WorldPay requires one additional step of running DDC flows. Flow can be looked at in WorldPay's dev docs 1. Redirect to Worldpay's DDC 2. Redirect to Wordlpay's 3DS redirection form 3. Capture details in HyperSwitch's `/redirect/complete` flow 4. Perform a PSync (optional) Reference https://developer.worldpay.com/products/access/3ds/web ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index 85c69824892..0627fa0048a 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -171,11 +171,23 @@ impl PaymentAttempt { merchant_id: &common_utils::id_type::MerchantId, connector_txn_id: &str, ) -> StorageResult<Self> { + let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data( + connector_txn_id.to_string(), + ); + let connector_transaction_id = txn_id + .get_txn_id(txn_data.as_ref()) + .change_context(DatabaseError::Others) + .attach_printable_lazy(|| { + format!( + "Failed to retrieve txn_id for ({:?}, {:?})", + txn_id, txn_data + ) + })?; generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) - .and(dsl::connector_transaction_id.eq(connector_txn_id.to_owned())), + .and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())), ) .await } diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index eca56b8c866..6682ac1ad44 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -163,6 +163,12 @@ pub enum RedirectForm { Mifinity { initialization_token: String, }, + WorldpayDDCForm { + endpoint: url::Url, + method: Method, + form_fields: HashMap<String, String>, + collection_id: Option<String>, + }, } impl From<(url::Url, Method)> for RedirectForm { diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index 7a4c4c5da97..97da36f39b3 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -624,6 +624,113 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } +impl api::PaymentsCompleteAuthorize for Worldpay {} +impl + ConnectorIntegration< + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > for Worldpay +{ + fn get_headers( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req + .request + .connector_transaction_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; + let stage = match req.status { + enums::AttemptStatus::DeviceDataCollectionPending => "3dsDeviceData".to_string(), + _ => "3dsChallenges".to_string(), + }; + Ok(format!( + "{}api/payments/{connector_payment_id}/{stage}", + self.base_url(connectors), + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let req_obj = WorldpayCompleteAuthorizationRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { + let response: WorldpayPaymentsResponse = res + .response + .parse_struct("WorldpayPaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + let optional_correlation_id = res.headers.and_then(|headers| { + headers + .get("WP-CorrelationId") + .and_then(|header_value| header_value.to_str().ok()) + .map(|id| id.to_string()) + }); + types::RouterData::foreign_try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + optional_correlation_id, + )) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + impl api::Refund for Worldpay {} impl api::RefundExecute for Worldpay {} impl api::RefundSync for Worldpay {} @@ -900,3 +1007,20 @@ impl api::IncomingWebhook for Worldpay { Ok(Box::new(psync_body)) } } + +impl services::ConnectorRedirectResponse for Worldpay { + fn get_flow_type( + &self, + _query_params: &str, + _json_payload: Option<serde_json::Value>, + action: services::PaymentAction, + ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> { + match action { + services::PaymentAction::CompleteAuthorize => Ok(enums::CallConnectorAction::Trigger), + services::PaymentAction::PSync + | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => { + Ok(enums::CallConnectorAction::Avoid) + } + } + } +} diff --git a/crates/router/src/connector/worldpay/requests.rs b/crates/router/src/connector/worldpay/requests.rs index 3d0be891ebb..b0fa85a64c3 100644 --- a/crates/router/src/connector/worldpay/requests.rs +++ b/crates/router/src/connector/worldpay/requests.rs @@ -31,6 +31,8 @@ pub struct Instruction { pub value: PaymentValue, #[serde(skip_serializing_if = "Option::is_none")] pub debt_repayment: Option<bool>, + #[serde(rename = "threeDS")] + pub three_ds: Option<ThreeDSRequest>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -187,6 +189,44 @@ pub struct AutoSettlement { pub auto: bool, } +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ThreeDSRequest { + #[serde(rename = "type")] + pub three_ds_type: String, + pub mode: String, + pub device_data: ThreeDSRequestDeviceData, + pub challenge: ThreeDSRequestChallenge, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ThreeDSRequestDeviceData { + pub accept_header: String, + pub user_agent_header: String, + pub browser_language: Option<String>, + pub browser_screen_width: Option<u32>, + pub browser_screen_height: Option<u32>, + pub browser_color_depth: Option<String>, + pub time_zone: Option<String>, + pub browser_java_enabled: Option<bool>, + pub browser_javascript_enabled: Option<bool>, + pub channel: Option<ThreeDSRequestChannel>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ThreeDSRequestChannel { + Browser, + Native, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ThreeDSRequestChallenge { + pub return_url: String, +} + #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PaymentMethod { @@ -237,3 +277,10 @@ pub struct WorldpayPartialRequest { pub value: PaymentValue, pub reference: String, } + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WorldpayCompleteAuthorizationRequest { + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_reference: Option<String>, +} diff --git a/crates/router/src/connector/worldpay/response.rs b/crates/router/src/connector/worldpay/response.rs index 0a7f690c3aa..edc3c26948f 100644 --- a/crates/router/src/connector/worldpay/response.rs +++ b/crates/router/src/connector/worldpay/response.rs @@ -1,6 +1,7 @@ use error_stack::ResultExt; use masking::Secret; use serde::{Deserialize, Serialize}; +use url::Url; use super::requests::*; use crate::core::errors; @@ -10,7 +11,7 @@ pub struct WorldpayPaymentsResponse { pub outcome: PaymentOutcome, pub transaction_reference: Option<String>, #[serde(flatten)] - pub other_fields: WorldpayPaymentResponseFields, + pub other_fields: Option<WorldpayPaymentResponseFields>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -20,13 +21,13 @@ pub enum WorldpayPaymentResponseFields { DDCResponse(DDCResponse), FraudHighRisk(FraudHighRiskResponse), RefusedResponse(RefusedResponse), + ThreeDsChallenged(ThreeDsChallengedResponse), } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedResponse { - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_instrument: Option<PaymentsResPaymentInstrument>, + pub payment_instrument: PaymentsResPaymentInstrument, #[serde(skip_serializing_if = "Option::is_none")] pub issuer: Option<Issuer>, #[serde(skip_serializing_if = "Option::is_none")] @@ -67,6 +68,34 @@ pub struct ThreeDsResponse { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +pub struct ThreeDsChallengedResponse { + pub authentication: AuthenticationResponse, + pub challenge: ThreeDsChallenge, + #[serde(rename = "_actions")] + pub actions: CompleteThreeDsActionLink, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct AuthenticationResponse { + pub version: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ThreeDsChallenge { + pub reference: String, + pub url: Url, + pub jwt: Secret<String>, + pub payload: Secret<String>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CompleteThreeDsActionLink { + #[serde(rename = "complete3dsChallenge")] + pub complete_three_ds_challenge: ActionLink, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] pub enum IssuerResponse { Challenged, Frictionless, @@ -82,16 +111,15 @@ pub struct DDCResponse { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DDCToken { - pub jwt: String, - pub url: String, - pub bin: String, + pub jwt: Secret<String>, + pub url: Url, + pub bin: Secret<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DDCActionLink { #[serde(rename = "supply3dsDeviceData")] supply_ddc_data: ActionLink, - method: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -105,11 +133,32 @@ pub enum PaymentOutcome { FraudHighRisk, #[serde(alias = "3dsDeviceDataRequired")] ThreeDsDeviceDataRequired, - ThreeDsChallenged, SentForCancellation, #[serde(alias = "3dsAuthenticationFailed")] ThreeDsAuthenticationFailed, SentForPartialRefund, + #[serde(alias = "3dsChallenged")] + ThreeDsChallenged, + #[serde(alias = "3dsUnavailable")] + ThreeDsUnavailable, +} + +impl std::fmt::Display for PaymentOutcome { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Authorized => write!(f, "authorized"), + Self::Refused => write!(f, "refused"), + Self::SentForSettlement => write!(f, "sentForSettlement"), + Self::SentForRefund => write!(f, "sentForRefund"), + Self::FraudHighRisk => write!(f, "fraudHighRisk"), + Self::ThreeDsDeviceDataRequired => write!(f, "3dsDeviceDataRequired"), + Self::SentForCancellation => write!(f, "sentForCancellation"), + Self::ThreeDsAuthenticationFailed => write!(f, "3dsAuthenticationFailed"), + Self::SentForPartialRefund => write!(f, "sentForPartialRefund"), + Self::ThreeDsChallenged => write!(f, "3dsChallenged"), + Self::ThreeDsUnavailable => write!(f, "3dsUnavailable"), + } + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -202,30 +251,33 @@ pub fn get_resource_id<T, F>( where F: Fn(String) -> T, { - let reference_id = match response.other_fields { - WorldpayPaymentResponseFields::AuthorizedResponse(res) => res - .links - .as_ref() - .and_then(|link| link.self_link.href.rsplit_once('/')) - .map(|(_, h)| urlencoding::decode(h)) - .transpose() - .change_context(errors::ConnectorError::ResponseHandlingFailed)? - .map(|s| transform_fn(s.into_owned())), - WorldpayPaymentResponseFields::DDCResponse(res) => res - .actions - .supply_ddc_data - .href - .split('/') - .rev() - .nth(1) - .map(urlencoding::decode) - .transpose() - .change_context(errors::ConnectorError::ResponseHandlingFailed)? - .map(|s| transform_fn(s.into_owned())), - WorldpayPaymentResponseFields::FraudHighRisk(_) => None, - WorldpayPaymentResponseFields::RefusedResponse(_) => None, - }; - reference_id + let optional_reference_id = response + .other_fields + .as_ref() + .and_then(|other_fields| match other_fields { + WorldpayPaymentResponseFields::AuthorizedResponse(res) => res + .links + .as_ref() + .and_then(|link| link.self_link.href.rsplit_once('/').map(|(_, h)| h)), + WorldpayPaymentResponseFields::DDCResponse(res) => { + res.actions.supply_ddc_data.href.split('/').nth_back(1) + } + WorldpayPaymentResponseFields::ThreeDsChallenged(res) => res + .actions + .complete_three_ds_challenge + .href + .split('/') + .nth_back(1), + WorldpayPaymentResponseFields::FraudHighRisk(_) + | WorldpayPaymentResponseFields::RefusedResponse(_) => None, + }) + .map(|href| { + urlencoding::decode(href) + .map(|s| transform_fn(s.into_owned())) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + }) + .transpose()?; + optional_reference_id .or_else(|| connector_transaction_id.map(transform_fn)) .ok_or_else(|| { errors::ConnectorError::MissingRequiredField { @@ -256,8 +308,8 @@ impl Issuer { #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentsResPaymentInstrument { - #[serde(rename = "type", skip_serializing_if = "Option::is_none")] - pub payment_instrument_type: Option<String>, + #[serde(rename = "type")] + pub payment_instrument_type: String, pub card_bin: Option<String>, pub last_four: Option<String>, pub expiry_date: Option<ExpiryDate>, @@ -268,22 +320,6 @@ pub struct PaymentsResPaymentInstrument { pub payment_account_reference: Option<String>, } -impl PaymentsResPaymentInstrument { - pub fn new() -> Self { - Self { - payment_instrument_type: None, - card_bin: None, - last_four: None, - category: None, - expiry_date: None, - card_brand: None, - funding_type: None, - issuer_name: None, - payment_account_reference: None, - } - } -} - #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RiskFactorsInner { diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index a0f2bfd2508..a28d3bff7ed 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -1,17 +1,20 @@ +use std::collections::HashMap; + use api_models::payments::Address; use base64::Engine; use common_utils::{errors::CustomResult, ext_traits::OptionExt, pii, types::MinorUnit}; use diesel_models::enums; use error_stack::ResultExt; -use hyperswitch_connectors::utils::RouterData; +use hyperswitch_connectors::utils::{PaymentsAuthorizeRequestData, RouterData}; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use super::{requests::*, response::*}; use crate::{ - connector::utils, + connector::utils::{self, AddressData}, consts, core::errors, + services, types::{ self, domain, transformers::ForeignTryFrom, PaymentsAuthorizeData, PaymentsResponseData, }, @@ -65,49 +68,40 @@ impl TryFrom<&Option<pii::SecretSerdeValue>> for WorldpayConnectorMetadataObject fn fetch_payment_instrument( payment_method: domain::PaymentMethodData, billing_address: Option<&Address>, - auth_type: enums::AuthenticationType, ) -> CustomResult<PaymentInstrument, errors::ConnectorError> { match payment_method { - domain::PaymentMethodData::Card(card) => { - if auth_type == enums::AuthenticationType::ThreeDs { - return Err(errors::ConnectorError::NotImplemented( - "ThreeDS flow through worldpay".to_string(), - ) - .into()); - } - Ok(PaymentInstrument::Card(CardPayment { - payment_type: PaymentType::Plain, - expiry_date: ExpiryDate { - month: utils::CardData::get_expiry_month_as_i8(&card)?, - year: utils::CardData::get_expiry_year_as_i32(&card)?, - }, - card_number: card.card_number, - cvc: card.card_cvc, - card_holder_name: card.nick_name, - billing_address: if let Some(address) = - billing_address.and_then(|addr| addr.address.clone()) - { - Some(BillingAddress { - address1: address.line1, - address2: address.line2, - address3: address.line3, - city: address.city, - state: address.state, - postal_code: address.zip.get_required_value("zip").change_context( - errors::ConnectorError::MissingRequiredField { field_name: "zip" }, - )?, - country_code: address - .country - .get_required_value("country_code") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "country_code", - })?, - }) - } else { - None - }, - })) - } + domain::PaymentMethodData::Card(card) => Ok(PaymentInstrument::Card(CardPayment { + payment_type: PaymentType::Plain, + expiry_date: ExpiryDate { + month: utils::CardData::get_expiry_month_as_i8(&card)?, + year: utils::CardData::get_expiry_year_as_i32(&card)?, + }, + card_number: card.card_number, + cvc: card.card_cvc, + card_holder_name: billing_address.and_then(|address| address.get_optional_full_name()), + billing_address: if let Some(address) = + billing_address.and_then(|addr| addr.address.clone()) + { + Some(BillingAddress { + address1: address.line1, + address2: address.line2, + address3: address.line3, + city: address.city, + state: address.state, + postal_code: address.zip.get_required_value("zip").change_context( + errors::ConnectorError::MissingRequiredField { field_name: "zip" }, + )?, + country_code: address + .country + .get_required_value("country_code") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "country_code", + })?, + }) + } else { + None + }, + })), domain::PaymentMethodData::Wallet(wallet) => match wallet { domain::WalletData::GooglePay(data) => { Ok(PaymentInstrument::Googlepay(WalletPayment { @@ -230,6 +224,53 @@ impl config: "metadata.merchant_name", }, )?; + let three_ds = match item.router_data.auth_type { + enums::AuthenticationType::ThreeDs => { + let browser_info = item + .router_data + .request + .browser_info + .clone() + .get_required_value("browser_info") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "browser_info", + })?; + let accept_header = browser_info + .accept_header + .get_required_value("accept_header") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "accept_header", + })?; + let user_agent_header = browser_info + .user_agent + .get_required_value("user_agent") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "user_agent", + })?; + Some(ThreeDSRequest { + three_ds_type: "integrated".to_string(), + mode: "always".to_string(), + device_data: ThreeDSRequestDeviceData { + accept_header, + user_agent_header, + browser_language: browser_info.language.clone(), + browser_screen_width: browser_info.screen_width, + browser_screen_height: browser_info.screen_height, + browser_color_depth: browser_info + .color_depth + .map(|depth| depth.to_string()), + time_zone: browser_info.time_zone.map(|tz| tz.to_string()), + browser_java_enabled: browser_info.java_enabled, + browser_javascript_enabled: browser_info.java_script_enabled, + channel: Some(ThreeDSRequestChannel::Browser), + }, + challenge: ThreeDSRequestChallenge { + return_url: item.router_data.request.get_complete_authorize_url()?, + }, + }) + } + _ => None, + }; Ok(Self { instruction: Instruction { settlement: item @@ -252,7 +293,6 @@ impl payment_instrument: fetch_payment_instrument( item.router_data.request.payment_method_data.clone(), item.router_data.get_optional_billing(), - item.router_data.auth_type, )?, narrative: InstructionNarrative { line1: merchant_name.expose(), @@ -262,6 +302,7 @@ impl currency: item.router_data.request.currency, }, debt_repayment: None, + three_ds, }, merchant: Merchant { entity: entity_id.clone(), @@ -321,6 +362,7 @@ impl From<PaymentOutcome> for enums::AttemptStatus { Self::AutoRefunded } PaymentOutcome::Refused | PaymentOutcome::FraudHighRisk => Self::Failure, + PaymentOutcome::ThreeDsUnavailable => Self::AuthenticationFailed, } } } @@ -363,42 +405,105 @@ impl From<EventType> for enums::RefundStatus { } } -impl +impl<F, T> ForeignTryFrom<( - types::PaymentsResponseRouterData<WorldpayPaymentsResponse>, + types::ResponseRouterData<F, WorldpayPaymentsResponse, T, PaymentsResponseData>, Option<String>, - )> for types::PaymentsAuthorizeRouterData + )> for types::RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from( item: ( - types::PaymentsResponseRouterData<WorldpayPaymentsResponse>, + types::ResponseRouterData<F, WorldpayPaymentsResponse, T, PaymentsResponseData>, Option<String>, ), ) -> Result<Self, Self::Error> { let (router_data, optional_correlation_id) = item; - let description = match router_data.response.other_fields { - WorldpayPaymentResponseFields::AuthorizedResponse(ref res) => res.description.clone(), - WorldpayPaymentResponseFields::DDCResponse(_) - | WorldpayPaymentResponseFields::FraudHighRisk(_) - | WorldpayPaymentResponseFields::RefusedResponse(_) => None, + let (description, redirection_data) = router_data + .response + .other_fields + .as_ref() + .map(|other_fields| match other_fields { + WorldpayPaymentResponseFields::AuthorizedResponse(res) => { + (res.description.clone(), None) + } + WorldpayPaymentResponseFields::DDCResponse(res) => ( + None, + Some(services::RedirectForm::WorldpayDDCForm { + endpoint: res.device_data_collection.url.clone(), + method: common_utils::request::Method::Post, + collection_id: Some("SessionId".to_string()), + form_fields: HashMap::from([ + ( + "Bin".to_string(), + res.device_data_collection.bin.clone().expose(), + ), + ( + "JWT".to_string(), + res.device_data_collection.jwt.clone().expose(), + ), + ]), + }), + ), + WorldpayPaymentResponseFields::ThreeDsChallenged(res) => ( + None, + Some(services::RedirectForm::Form { + endpoint: res.challenge.url.to_string(), + method: common_utils::request::Method::Post, + form_fields: HashMap::from([( + "JWT".to_string(), + res.challenge.jwt.clone().expose(), + )]), + }), + ), + WorldpayPaymentResponseFields::FraudHighRisk(_) + | WorldpayPaymentResponseFields::RefusedResponse(_) => (None, None), + }) + .unwrap_or((None, None)); + let worldpay_status = router_data.response.outcome.clone(); + let optional_reason = match worldpay_status { + PaymentOutcome::ThreeDsAuthenticationFailed => { + Some("3DS authentication failed from issuer".to_string()) + } + PaymentOutcome::ThreeDsUnavailable => { + Some("3DS authentication unavailable from issuer".to_string()) + } + PaymentOutcome::FraudHighRisk => { + Some("Transaction marked as high risk by Worldpay".to_string()) + } + PaymentOutcome::Refused => Some("Transaction refused by issuer".to_string()), + _ => None, }; - Ok(Self { - status: enums::AttemptStatus::from(router_data.response.outcome.clone()), - description, - response: Ok(PaymentsResponseData::TransactionResponse { + let status = enums::AttemptStatus::from(worldpay_status.clone()); + let response = optional_reason.map_or( + Ok(PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::foreign_try_from(( router_data.response, optional_correlation_id.clone(), ))?, - redirection_data: None, + redirection_data, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: optional_correlation_id, + connector_response_reference_id: optional_correlation_id.clone(), incremental_authorization_allowed: None, charge_id: None, }), + |reason| { + Err(types::ErrorResponse { + code: worldpay_status.to_string(), + message: reason.clone(), + reason: Some(reason), + status_code: router_data.http_code, + attempt_status: Some(status), + connector_transaction_id: optional_correlation_id, + }) + }, + ); + Ok(Self { + status, + description, + response, ..router_data.data }) } @@ -459,3 +564,17 @@ impl ForeignTryFrom<(WorldpayPaymentsResponse, Option<String>)> for types::Respo get_resource_id(item.0, item.1, Self::ConnectorTransactionId) } } + +impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for WorldpayCompleteAuthorizationRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> { + let params = item + .request + .redirect_response + .as_ref() + .and_then(|redirect_response| redirect_response.params.as_ref()) + .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; + serde_urlencoded::from_str::<Self>(params.peek()) + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + } +} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index babf393bb3a..700fff16cf5 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -240,7 +240,6 @@ default_imp_for_complete_authorize!( connector::Wise, connector::Wellsfargo, connector::Wellsfargopayout, - connector::Worldpay, connector::Zen, connector::Zsl ); @@ -472,7 +471,6 @@ default_imp_for_connector_redirect_response!( connector::Wellsfargo, connector::Wellsfargopayout, connector::Wise, - connector::Worldpay, connector::Zsl ); diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 579a4ac4ffd..0d84ba9c30f 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1809,6 +1809,135 @@ pub fn build_redirection_form( } } + RedirectForm::WorldpayDDCForm { + endpoint, + method, + form_fields, + collection_id, + } => maud::html! { + (maud::DOCTYPE) + html { + meta name="viewport" content="width=device-width, initial-scale=1"; + head { + (PreEscaped(r##" + <style> + #loader1 { + width: 500px; + } + @media max-width: 600px { + #loader1 { + width: 200px; + } + } + </style> + "##)) + } + + body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { + div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-left: auto; margin-right: auto;" { "" } + (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) + (PreEscaped(r#" + <script> + var anime = bodymovin.loadAnimation({ + container: document.getElementById('loader1'), + renderer: 'svg', + loop: true, + autoplay: true, + name: 'hyperswitch loader', + animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} + }) + </script> + "#)) + h3 style="text-align: center;" { "Please wait while we process your payment..." } + + script { + (PreEscaped(format!( + r#" + function submitCollectionReference(collectionReference) {{ + var redirectPathname = window.location.pathname.replace(/payments\/redirect\/(\w+)\/(\w+)\/\w+/, "payments/$1/$2/redirect/complete/worldpay"); + var redirectUrl = window.location.origin + redirectPathname; + try {{ + if (typeof collectionReference === "string" && collectionReference.length > 0) {{ + var form = document.createElement("form"); + form.action = redirectPathname; + form.method = "GET"; + var input = document.createElement("input"); + input.type = "hidden"; + input.name = "collectionReference"; + input.value = collectionReference; + form.appendChild(input); + document.body.appendChild(form); + form.submit();; + }} else {{ + window.location.replace(redirectUrl); + }} + }} catch (error) {{ + window.location.replace(redirectUrl); + }} + }} + var allowedHost = "{}"; + var collectionField = "{}"; + window.addEventListener("message", function(event) {{ + if (event.origin === allowedHost) {{ + try {{ + var data = JSON.parse(event.data); + if (collectionField.length > 0) {{ + var collectionReference = data[collectionField]; + return submitCollectionReference(collectionReference); + }} else {{ + console.error("Collection field not found in event data (" + collectionField + ")"); + }} + }} catch (error) {{ + console.error("Error parsing event data: ", error); + }} + }} else {{ + console.error("Invalid origin: " + event.origin, "Expected origin: " + allowedHost); + }} + + submitCollectionReference(""); + }}); + + // Redirect within 8 seconds if no collection reference is received + window.setTimeout(submitCollectionReference, 8000); + "#, + endpoint.host_str().map_or(endpoint.as_ref().split('/').take(3).collect::<Vec<&str>>().join("/"), |host| format!("{}://{}", endpoint.scheme(), host)), + collection_id.clone().unwrap_or("".to_string()))) + ) + } + + iframe + style="display: none;" + srcdoc=( + maud::html! { + (maud::DOCTYPE) + html { + body { + form action=(PreEscaped(endpoint.to_string())) method=(method.to_string()) #payment_form { + @for (field, value) in form_fields { + input type="hidden" name=(field) value=(value); + } + } + (PreEscaped(format!(r#" + <script type="text/javascript"> {logging_template} + var form = document.getElementById("payment_form"); + var formFields = form.querySelectorAll("input"); + window.setTimeout(function () {{ + if (form.method.toUpperCase() === "GET" && formFields.length === 0) {{ + window.location.href = form.action; + }} else {{ + form.submit(); + }} + }}, 300); + </script> + "#))) + } + } + }.into_string() + ) + {} + } + } + }, } }
2024-10-20T09:44:04Z
## Description Described in #6177 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Integrates Worldpay's 3DS flow ## How did you test it? Things to test 1. 3DS payments using automatic capture 2. No 3DS payment using manual capture (full amount captures) 3. Payments Sync <details> <summary>1. Create and capture</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9' \ --data-raw '{"authentication_type":"three_ds","capture_method":"automatic","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","profile_id":"pro_OodaMoJ1Y9nlnegU4soR","amount":100,"currency":"USD","confirm":true,"connector":["worldpay"],"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"US","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"}},"email":"john.doe@example.com","session_expiry":10000,"return_url":"https://example.com","off_session":true,"payment_method":"card","payment_method_type":"credit","payment_method_data":{"card":{"card_number":"4000000000001091","card_exp_month":"12","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"123"}},"browser_info":{"user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":24,"screen_height":723,"screen_width":1536,"time_zone":0,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"statement_descriptor_name":"John","statement_descriptor_suffix":"JD","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"}}' Response {"payment_id":"pay_OjJGWEhFHNpycXbZmDNS","merchant_id":"merchant_1728979001","status":"requires_customer_action","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_OjJGWEhFHNpycXbZmDNS_secret_vMQEnVxtwo0xKYXtDTqh","created":"2024-10-21T10:59:11.767Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@example.com","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"1091","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_OjJGWEhFHNpycXbZmDNS/merchant_1728979001/pay_OjJGWEhFHNpycXbZmDNS_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_sH6s3hf1uukqvYlAGkj5","created_at":1729508351,"expires":1729511951,"secret":"epk_dfac7bbac2014a18ae323ba08bfe7e9b"},"manual_retry_allowed":null,"connector_transaction_id":"eyJrIjoxLCJkIjoibVJjNnpNRE45cys3RmIxWjRRbWF2SWd4akc2VC9KdHZiVlgrTTRvTURQdzJJRGpBeDR3ekZaWWVqNDJzOTJkWiJ9","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"3fbccf2f-0ab5-494c-9909-1c8d2be40049","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:45:51.767Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-21T10:59:12.308Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} Open the link and continue https://github.com/user-attachments/assets/52239cd6-fa40-45e3-88a9-231115ab8b20 </details> <details> <summary>2. Create a payment using manual capture</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9' \ --data-raw '{"authentication_type":"three_ds","capture_method":"manual","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","profile_id":"pro_OodaMoJ1Y9nlnegU4soR","amount":100,"currency":"USD","confirm":true,"connector":["worldpay"],"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"US","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"}},"email":"john.doe@example.com","session_expiry":10000,"return_url":"https://example.com","off_session":true,"payment_method":"card","payment_method_type":"credit","payment_method_data":{"card":{"card_number":"4000000000001091","card_exp_month":"12","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"123"}},"browser_info":{"user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":24,"screen_height":723,"screen_width":1536,"time_zone":0,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"statement_descriptor_name":"John","statement_descriptor_suffix":"JD","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"}}' Response {"payment_id":"pay_ff5lUcN6X1lg5f2PBtyv","merchant_id":"merchant_1728979001","status":"requires_customer_action","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_ff5lUcN6X1lg5f2PBtyv_secret_6iktmiNQwi8DAsIRNn4i","created":"2024-10-21T11:03:31.227Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@example.com","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"1096","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"520000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_ff5lUcN6X1lg5f2PBtyv/merchant_1728979001/pay_ff5lUcN6X1lg5f2PBtyv_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_sH6s3hf1uukqvYlAGkj5","created_at":1729508611,"expires":1729512211,"secret":"epk_739c58c7f7384fac89c7099e1cdae436"},"manual_retry_allowed":null,"connector_transaction_id":"eyJrIjoxLCJkIjoiQTRKMWZFZXlONnFqdGhHTWlmWDdYY2RzUVlIUzI2dEdLcEFPak9GRzNaczJJRGpBeDR3ekZaWWVqNDJzOTJkWiJ9","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"5b1cdf1c-26ea-42b1-b6e0-a02453ebf21f","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:50:11.227Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-21T11:03:31.677Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} cURL (capture) curl --location --request POST 'http://localhost:8080/payments/pay_ff5lUcN6X1lg5f2PBtyv/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9' \ --data '{}' Response {"payment_id":"pay_ff5lUcN6X1lg5f2PBtyv","merchant_id":"merchant_1728979001","status":"processing","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_ff5lUcN6X1lg5f2PBtyv_secret_6iktmiNQwi8DAsIRNn4i","created":"2024-10-21T11:03:31.227Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@example.com","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"1096","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"520000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLZqKn+Z0amZtgDGJNxxTouoBznrTCkCd2i5TQsznCawECpZY8cZeCeMgt1ol:GABqQG6u+T:u3sfHv3ezSOJxioRTixsThPEhzFW4ZZ6mObj3CK0rnFndcM0swvZMqgQwSEj5tBsydfzM4XKX20O6Nme96ha9twqxTSQIfr1rtl9V3q7fw3w5O9UZT4vQi9BMyCcaHkWSD:RbCWCcmiQqa:C6PZmXicLsKiJilUv0dIUwRuaBJaSeFhCq3fDWQC7:n7drI2adm1BXX7w39afnJw==","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"f7cb203a-aa4d-4fbc-84e7-9f6c1a9273a5","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:50:11.227Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-21T11:04:47.760Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} </details> <details> <summary>3. Payments Sync</summary> cURL curl --location --request GET 'http://localhost:8080/payments/pay_ff5lUcN6X1lg5f2PBtyv?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9' Response {"payment_id":"pay_ff5lUcN6X1lg5f2PBtyv","merchant_id":"merchant_1728979001","status":"processing","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_ff5lUcN6X1lg5f2PBtyv_secret_6iktmiNQwi8DAsIRNn4i","created":"2024-10-21T11:03:31.227Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@example.com","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"1096","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"520000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLZqKn+Z0amZtgDGJNxxTouoBznrTCkCd2i5TQsznCawECpZY8cZeCeMgt1ol:GABqQG6u+T:u3sfHv3ezSOJxioRTixsThPEhzFW4ZZ6mObj3CK0rnFndcM0swvZMqgQwSEj5tBsydfzM4XKX20O6Nme96ha9twqxTSQIfr1rtl9V3q7fw3w5O9UZT4vQi9BMyCcaHkWSD:RbCWCcmiQqa:C6PZmXicLsKiJilUv0dIUwRuaBJaSeFhCq3fDWQC7:n7drI2adm1BXX7w39afnJw==","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"eaf9a1d5-031a-4b3b-b70b-ed9b7ec05406","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:50:11.227Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-21T11:06:18.222Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} </details>
58296ffae6ff6f2f2c8f7b23dd28e92b374b9be3
Things to test 1. 3DS payments using automatic capture 2. No 3DS payment using manual capture (full amount captures) 3. Payments Sync <details> <summary>1. Create and capture</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9' \ --data-raw '{"authentication_type":"three_ds","capture_method":"automatic","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","profile_id":"pro_OodaMoJ1Y9nlnegU4soR","amount":100,"currency":"USD","confirm":true,"connector":["worldpay"],"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"US","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"}},"email":"john.doe@example.com","session_expiry":10000,"return_url":"https://example.com","off_session":true,"payment_method":"card","payment_method_type":"credit","payment_method_data":{"card":{"card_number":"4000000000001091","card_exp_month":"12","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"123"}},"browser_info":{"user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":24,"screen_height":723,"screen_width":1536,"time_zone":0,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"statement_descriptor_name":"John","statement_descriptor_suffix":"JD","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"}}' Response {"payment_id":"pay_OjJGWEhFHNpycXbZmDNS","merchant_id":"merchant_1728979001","status":"requires_customer_action","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_OjJGWEhFHNpycXbZmDNS_secret_vMQEnVxtwo0xKYXtDTqh","created":"2024-10-21T10:59:11.767Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@example.com","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"1091","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_OjJGWEhFHNpycXbZmDNS/merchant_1728979001/pay_OjJGWEhFHNpycXbZmDNS_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_sH6s3hf1uukqvYlAGkj5","created_at":1729508351,"expires":1729511951,"secret":"epk_dfac7bbac2014a18ae323ba08bfe7e9b"},"manual_retry_allowed":null,"connector_transaction_id":"eyJrIjoxLCJkIjoibVJjNnpNRE45cys3RmIxWjRRbWF2SWd4akc2VC9KdHZiVlgrTTRvTURQdzJJRGpBeDR3ekZaWWVqNDJzOTJkWiJ9","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"3fbccf2f-0ab5-494c-9909-1c8d2be40049","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:45:51.767Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-21T10:59:12.308Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} Open the link and continue https://github.com/user-attachments/assets/52239cd6-fa40-45e3-88a9-231115ab8b20 </details> <details> <summary>2. Create a payment using manual capture</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9' \ --data-raw '{"authentication_type":"three_ds","capture_method":"manual","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","profile_id":"pro_OodaMoJ1Y9nlnegU4soR","amount":100,"currency":"USD","confirm":true,"connector":["worldpay"],"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"US","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"}},"email":"john.doe@example.com","session_expiry":10000,"return_url":"https://example.com","off_session":true,"payment_method":"card","payment_method_type":"credit","payment_method_data":{"card":{"card_number":"4000000000001091","card_exp_month":"12","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"123"}},"browser_info":{"user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":24,"screen_height":723,"screen_width":1536,"time_zone":0,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"statement_descriptor_name":"John","statement_descriptor_suffix":"JD","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"}}' Response {"payment_id":"pay_ff5lUcN6X1lg5f2PBtyv","merchant_id":"merchant_1728979001","status":"requires_customer_action","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_ff5lUcN6X1lg5f2PBtyv_secret_6iktmiNQwi8DAsIRNn4i","created":"2024-10-21T11:03:31.227Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@example.com","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"1096","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"520000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_ff5lUcN6X1lg5f2PBtyv/merchant_1728979001/pay_ff5lUcN6X1lg5f2PBtyv_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_sH6s3hf1uukqvYlAGkj5","created_at":1729508611,"expires":1729512211,"secret":"epk_739c58c7f7384fac89c7099e1cdae436"},"manual_retry_allowed":null,"connector_transaction_id":"eyJrIjoxLCJkIjoiQTRKMWZFZXlONnFqdGhHTWlmWDdYY2RzUVlIUzI2dEdLcEFPak9GRzNaczJJRGpBeDR3ekZaWWVqNDJzOTJkWiJ9","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"5b1cdf1c-26ea-42b1-b6e0-a02453ebf21f","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:50:11.227Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-21T11:03:31.677Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} cURL (capture) curl --location --request POST 'http://localhost:8080/payments/pay_ff5lUcN6X1lg5f2PBtyv/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9' \ --data '{}' Response {"payment_id":"pay_ff5lUcN6X1lg5f2PBtyv","merchant_id":"merchant_1728979001","status":"processing","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_ff5lUcN6X1lg5f2PBtyv_secret_6iktmiNQwi8DAsIRNn4i","created":"2024-10-21T11:03:31.227Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@example.com","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"1096","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"520000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLZqKn+Z0amZtgDGJNxxTouoBznrTCkCd2i5TQsznCawECpZY8cZeCeMgt1ol:GABqQG6u+T:u3sfHv3ezSOJxioRTixsThPEhzFW4ZZ6mObj3CK0rnFndcM0swvZMqgQwSEj5tBsydfzM4XKX20O6Nme96ha9twqxTSQIfr1rtl9V3q7fw3w5O9UZT4vQi9BMyCcaHkWSD:RbCWCcmiQqa:C6PZmXicLsKiJilUv0dIUwRuaBJaSeFhCq3fDWQC7:n7drI2adm1BXX7w39afnJw==","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"f7cb203a-aa4d-4fbc-84e7-9f6c1a9273a5","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:50:11.227Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-21T11:04:47.760Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} </details> <details> <summary>3. Payments Sync</summary> cURL curl --location --request GET 'http://localhost:8080/payments/pay_ff5lUcN6X1lg5f2PBtyv?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9' Response {"payment_id":"pay_ff5lUcN6X1lg5f2PBtyv","merchant_id":"merchant_1728979001","status":"processing","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_ff5lUcN6X1lg5f2PBtyv_secret_6iktmiNQwi8DAsIRNn4i","created":"2024-10-21T11:03:31.227Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@example.com","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"1096","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"520000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLZqKn+Z0amZtgDGJNxxTouoBznrTCkCd2i5TQsznCawECpZY8cZeCeMgt1ol:GABqQG6u+T:u3sfHv3ezSOJxioRTixsThPEhzFW4ZZ6mObj3CK0rnFndcM0swvZMqgQwSEj5tBsydfzM4XKX20O6Nme96ha9twqxTSQIfr1rtl9V3q7fw3w5O9UZT4vQi9BMyCcaHkWSD:RbCWCcmiQqa:C6PZmXicLsKiJilUv0dIUwRuaBJaSeFhCq3fDWQC7:n7drI2adm1BXX7w39afnJw==","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"eaf9a1d5-031a-4b3b-b70b-ed9b7ec05406","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:50:11.227Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-21T11:06:18.222Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} </details>
[ "crates/diesel_models/src/query/payment_attempt.rs", "crates/hyperswitch_domain_models/src/router_response_types.rs", "crates/router/src/connector/worldpay.rs", "crates/router/src/connector/worldpay/requests.rs", "crates/router/src/connector/worldpay/response.rs", "crates/router/src/connector/worldpay/transformers.rs", "crates/router/src/core/payments/flows.rs", "crates/router/src/services/api.rs" ]
juspay/hyperswitch
juspay__hyperswitch-5175
Bug: Adding Contributors Guide to the Readme of the repository Being an open source project, we look forward to contributors from across the world. For that we have outlined few changes which will make it easier for contributors to navigate through the project with more ease, and quickly develop a better understanding of the working of different components of Hyperswitch.
diff --git a/README.md b/README.md index e8dd2f31674..ccdd6e19b6d 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,6 @@ Here are the components of Hyperswitch that deliver the whole solution: Jump in and contribute to these repositories to help improve and expand Hyperswitch! <br> -<img src="./docs/imgs/hyperswitch-product.png" alt="Hyperswitch-Product" width="50%"/> <a href="#Quick Setup"> <h2 id="quick-setup">⚡️ Quick Setup</h2>
2024-10-18T11:42:24Z
## Description <!-- Describe your changes in detail --> Closes - #5175 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
451376e7993839f5c93624c12833af7d47aa4e34
[ "README.md" ]
juspay/hyperswitch
juspay__hyperswitch-6364
Bug: feat(config): update vector config # Current Behaviour - Sdk logs pushes `publishable_key` in the `merchant_id` field. - open search logs have some irrelevant fields. # Proposed Changes - transform sdk logs and update the correct corresponding `merchant_id` of the pre-existing `publishable_key` value - add some more except/ignore fields in open search sinks.
diff --git a/config/vector.yaml b/config/vector.yaml index 3f0709ae03c..4b801935ae5 100644 --- a/config/vector.yaml +++ b/config/vector.yaml @@ -1,5 +1,16 @@ acknowledgements: enabled: true +enrichment_tables: + sdk_map: + type: file + file: + path: /etc/vector/config/sdk_map.csv + encoding: + type: csv + schema: + publishable_key: string + merchant_id: string + api: enabled: true @@ -87,6 +98,21 @@ transforms: key_field: "{{ .payment_id }}{{ .merchant_id }}" threshold: 1000 window_secs: 60 + + amend_sdk_logs: + type: remap + inputs: + - sdk_transformed + source: | + .before_transform = now() + + merchant_id = .merchant_id + row = get_enrichment_table_record!("sdk_map", { "publishable_key" : merchant_id }, case_sensitive: true) + .merchant_id = row.merchant_id + + .after_transform = now() + + sinks: opensearch_events_1: @@ -110,6 +136,9 @@ sinks: - offset - partition - topic + - clickhouse_database + - last_synced + - sign_flag bulk: index: "vector-{{ .topic }}" @@ -134,6 +163,9 @@ sinks: - offset - partition - topic + - clickhouse_database + - last_synced + - sign_flag bulk: # Add a date suffixed index for better grouping index: "vector-{{ .topic }}-%Y-%m-%d" @@ -224,7 +256,7 @@ sinks: - "path" - "source_type" inputs: - - "sdk_transformed" + - "amend_sdk_logs" bootstrap_servers: kafka0:29092 topic: hyper-sdk-logs key_field: ".merchant_id"
2024-10-18T10:13:52Z
## Fixes #6364 ## Description <!-- Describe your changes in detail --> - adding a transform for `sdk` logs that fetches a value from an enrichment table `sdk_map` populated by file `sdk_map.csv` and updates the fields using this value. - adding some fields to ignore/except in `opensearch` logs sink **Important Notes** _Please ensure that the `sdk_map.csv` file is properly formatted and accessible at the specified path. The name of the file should also match the name of the table in config i.e `sdk_map`._ ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ### Prior Behaviour - sdk logs have a merchant_id field but it was being populated with publishable_key as value at source observed `merchant_id: "pk_dev*****"`. expected `merchant_id: "merchant_*****"`. - open search logs have certain fields like `last_synced`, `sign_flag` and `clickhouse_database` that needed to be ignored ### Intentions - Ensuring correctness of logs and reduce log size by storing only relevant fields. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### Running it locally to check logs added in console (sdk) logs & opensearch #### sdk_logs I created a dummy_transform event that inserted a `publishable_key` in merchant_id field and passed it to the actual transform function and then captured the output on a [console sink](https://vector.dev/docs/reference/configuration/sinks/console/console) - test-code <img width="1156" alt="Screenshot 2024-10-23 at 10 26 22 PM" src="https://github.com/user-attachments/assets/8f22c579-884f-4c65-8b09-aa657e87b261"> - sdk_map.csv (with dummy value 19999) <img width="828" alt="Screenshot 2024-10-23 at 10 27 26 PM" src="https://github.com/user-attachments/assets/8e5bf34a-b082-451f-94c4-638178bd3e63"> - console output <img width="1390" alt="Screenshot 2024-10-23 at 10 25 40 PM" src="https://github.com/user-attachments/assets/b126978d-da7a-43b5-bcb4-512bfdf00afb"> #### opensearch logs for this simply created a payment and compared the logs from kafka topics and opensearch entries kafka ui <img width="1726" alt="Screenshot 2024-10-23 at 10 44 45 PM" src="https://github.com/user-attachments/assets/6acfbb66-3d14-4156-9dc9-1d9d261331c7"> opensearch dashboard (no last_synced entry found) <img width="1708" alt="Screenshot 2024-10-23 at 10 45 43 PM" src="https://github.com/user-attachments/assets/8574306d-4e85-4f79-9c3d-538c0f7aa7ca">
35bf5a91d9a5b2d5e476c995e679b445242218e0
### Running it locally to check logs added in console (sdk) logs & opensearch #### sdk_logs I created a dummy_transform event that inserted a `publishable_key` in merchant_id field and passed it to the actual transform function and then captured the output on a [console sink](https://vector.dev/docs/reference/configuration/sinks/console/console) - test-code <img width="1156" alt="Screenshot 2024-10-23 at 10 26 22 PM" src="https://github.com/user-attachments/assets/8f22c579-884f-4c65-8b09-aa657e87b261"> - sdk_map.csv (with dummy value 19999) <img width="828" alt="Screenshot 2024-10-23 at 10 27 26 PM" src="https://github.com/user-attachments/assets/8e5bf34a-b082-451f-94c4-638178bd3e63"> - console output <img width="1390" alt="Screenshot 2024-10-23 at 10 25 40 PM" src="https://github.com/user-attachments/assets/b126978d-da7a-43b5-bcb4-512bfdf00afb"> #### opensearch logs for this simply created a payment and compared the logs from kafka topics and opensearch entries kafka ui <img width="1726" alt="Screenshot 2024-10-23 at 10 44 45 PM" src="https://github.com/user-attachments/assets/6acfbb66-3d14-4156-9dc9-1d9d261331c7"> opensearch dashboard (no last_synced entry found) <img width="1708" alt="Screenshot 2024-10-23 at 10 45 43 PM" src="https://github.com/user-attachments/assets/8574306d-4e85-4f79-9c3d-538c0f7aa7ca">
[ "config/vector.yaml" ]
juspay/hyperswitch
juspay__hyperswitch-6363
Bug: make `x_merchant_domain` as required value only for session call done on web The merchant domain url is only required in case of samsung pay payments on web. While processing payments on app the merchant domain is not required. Hence mandate the merchant domain only if the `x-client-platform` is `web`
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 1db9c98806b..654161d1c09 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -19148,7 +19148,6 @@ "type": "object", "required": [ "name", - "url", "country_code" ], "properties": { @@ -19158,7 +19157,8 @@ }, "url": { "type": "string", - "description": "Merchant domain that process payments" + "description": "Merchant domain that process payments, required for web payments", + "nullable": true }, "country_code": { "$ref": "#/components/schemas/CountryAlpha2" diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 71f383f014e..c28406cf630 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5500,8 +5500,8 @@ pub enum SamsungPayProtocolType { pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, - /// Merchant domain that process payments - pub url: String, + /// Merchant domain that process payments, required for web payments + pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 49b89fd5623..31027bc8c52 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -550,10 +550,15 @@ fn create_samsung_pay_session_token( message: "Failed to convert amount to string major unit for Samsung Pay".to_string(), })?; - let merchant_domain = header_payload - .x_merchant_domain - .get_required_value("samsung pay domain") - .attach_printable("Failed to get domain for samsung pay session call")?; + let merchant_domain = match header_payload.x_client_platform { + Some(common_enums::ClientPlatform::Web) => Some( + header_payload + .x_merchant_domain + .get_required_value("samsung pay domain") + .attach_printable("Failed to get domain for samsung pay session call")?, + ), + _ => None, + }; let samsung_pay_wallet_details = match samsung_pay_session_token_data.data { payment_types::SamsungPayCombinedMetadata::MerchantCredentials(
2024-10-18T08:22:24Z
## Description <!-- Describe your changes in detail --> The merchant domain url is only required in case of samsung pay payments on web. While processing payments on app the merchant domain is not required. Hence mandate the merchant domain only if the `x-client-platform` is `web` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a connector with samsung pay enabled -> Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_GhK0bBcXMIVjqoKmEip0XbSEvPXOuaEOLlMdBQWL4gdD51LsgHsjj2vzyuxMahw1' \ --data '{ "amount": 100000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1728548597" }' ``` ``` { "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "merchant_id": "merchant_1729239061", "status": "requires_payment_method", "amount": 100000, "net_amount": 100000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu", "created": "2024-10-18T09:06:02.530Z", "currency": "USD", "customer_id": "cu_1728548597", "customer": { "id": "cu_1728548597", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1728548597", "created_at": 1729242362, "expires": 1729245962, "secret": "epk_d521808e21a34868a01d050538f1f602" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_jh473NMl0nqGqosp7dqW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-18T09:21:02.530Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-18T09:06:02.581Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Session call, pass `x-client-platform` as `web` and `x-merchant-domain` as `sdk-test-app.netlify.app` ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'x-client-platform: web' \ --header 'x-merchant-domain: sdk-test-app.netlify.app' \ --header 'api-key: pk_dev_f2a5482b81f34fd884e8efbae5e2598c' \ --data '{ "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "wallets": [], "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu" }' ``` ``` { "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-rXRkcJK4eiTFnb29Meks", "merchant": { "name": "Hyperswitch", "url": "sdk-test-app.netlify.app", "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "1000.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` -> Session call, pass `x-client-platform` as `web` and do not pass `x-merchant-domain`. Response will not contain the samsung pay session token. ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'x-client-platform: web' \ --header 'api-key: pk_dev_f2a5482b81f34fd884e8efbae5e2598c' \ --data '{ "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "wallets": [], "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu" }' ``` ``` { "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` -> Session call, do not pass `x-client-platform` ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'api-key: pk_dev_f2a5482b81f34fd884e8efbae5e2598c' \ --data '{ "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "wallets": [], "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu" }' ``` ``` { "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-rXRkcJK4eiTFnb29Meks", "merchant": { "name": "Hyperswitch", "url": null, "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "1000.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` -> Session call, pass `x-client-platform` as `ios` ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'x-client-platform: ios' \ --header 'api-key: pk_dev_f2a5482b81f34fd884e8efbae5e2598c' \ --data '{ "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "wallets": [], "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu" }' ``` ``` { "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-rXRkcJK4eiTFnb29Meks", "merchant": { "name": "Hyperswitch", "url": null, "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "1000.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ```
451376e7993839f5c93624c12833af7d47aa4e34
-> Create a connector with samsung pay enabled -> Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_GhK0bBcXMIVjqoKmEip0XbSEvPXOuaEOLlMdBQWL4gdD51LsgHsjj2vzyuxMahw1' \ --data '{ "amount": 100000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1728548597" }' ``` ``` { "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "merchant_id": "merchant_1729239061", "status": "requires_payment_method", "amount": 100000, "net_amount": 100000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu", "created": "2024-10-18T09:06:02.530Z", "currency": "USD", "customer_id": "cu_1728548597", "customer": { "id": "cu_1728548597", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1728548597", "created_at": 1729242362, "expires": 1729245962, "secret": "epk_d521808e21a34868a01d050538f1f602" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_jh473NMl0nqGqosp7dqW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-18T09:21:02.530Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-18T09:06:02.581Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Session call, pass `x-client-platform` as `web` and `x-merchant-domain` as `sdk-test-app.netlify.app` ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'x-client-platform: web' \ --header 'x-merchant-domain: sdk-test-app.netlify.app' \ --header 'api-key: pk_dev_f2a5482b81f34fd884e8efbae5e2598c' \ --data '{ "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "wallets": [], "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu" }' ``` ``` { "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-rXRkcJK4eiTFnb29Meks", "merchant": { "name": "Hyperswitch", "url": "sdk-test-app.netlify.app", "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "1000.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` -> Session call, pass `x-client-platform` as `web` and do not pass `x-merchant-domain`. Response will not contain the samsung pay session token. ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'x-client-platform: web' \ --header 'api-key: pk_dev_f2a5482b81f34fd884e8efbae5e2598c' \ --data '{ "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "wallets": [], "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu" }' ``` ``` { "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` -> Session call, do not pass `x-client-platform` ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'api-key: pk_dev_f2a5482b81f34fd884e8efbae5e2598c' \ --data '{ "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "wallets": [], "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu" }' ``` ``` { "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-rXRkcJK4eiTFnb29Meks", "merchant": { "name": "Hyperswitch", "url": null, "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "1000.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` -> Session call, pass `x-client-platform` as `ios` ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'x-client-platform: ios' \ --header 'api-key: pk_dev_f2a5482b81f34fd884e8efbae5e2598c' \ --data '{ "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "wallets": [], "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu" }' ``` ``` { "payment_id": "pay_rXRkcJK4eiTFnb29Meks", "client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-rXRkcJK4eiTFnb29Meks", "merchant": { "name": "Hyperswitch", "url": null, "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "1000.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ```
[ "api-reference-v2/openapi_spec.json", "crates/api_models/src/payments.rs", "crates/router/src/core/payments/flows/session_flow.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2313
Bug: [FEATURE]: [PayU] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs index 7b3792c0e24..dc65d6e1d76 100644 --- a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs @@ -34,6 +34,7 @@ pub struct PayuPaymentsRequest { description: String, pay_methods: PayuPaymentMethod, continue_url: Option<String>, + ext_order_id: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -133,6 +134,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { .to_string(), ), merchant_pos_id: auth_type.merchant_pos_id, + ext_order_id: Some(item.connector_request_reference_id.clone()), total_amount: item.request.amount, currency_code: item.request.currency, description: item.description.clone().ok_or(
2024-10-18T03:14:35Z
## Description Add connector_request_reference_id support for PayU - Used `extOrderId` as the reference id based on the [PayU documentation](https://developers.payu.com/europe/api/#tag/Order/operation/create-an-order) reference: ![image](https://github.com/user-attachments/assets/f730028d-1fa4-4222-b2ad-7e2b4caeed9e) Resolves #2313 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
c3b0f7c1d6ad95034535048aa50ff6abe9ed6aa0
[ "crates/hyperswitch_connectors/src/connectors/payu/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6139
Bug: [REFACTOR]: [RISKIFIED] Add amount conversion framework to Riskified ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://support.riskified.com/hc/en-us/articles/360012160393-API-Integration-Guide) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [ ] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR? ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/router/src/connector/riskified.rs b/crates/router/src/connector/riskified.rs index 0f8ebb46134..7d9feec717a 100644 --- a/crates/router/src/connector/riskified.rs +++ b/crates/router/src/connector/riskified.rs @@ -1,8 +1,10 @@ pub mod transformers; -use std::fmt::Debug; #[cfg(feature = "frm")] use base64::Engine; +use common_utils::types::{ + AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector, +}; #[cfg(feature = "frm")] use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; #[cfg(feature = "frm")] @@ -14,6 +16,7 @@ use ring::hmac; #[cfg(feature = "frm")] use transformers as riskified; +use super::utils::convert_amount; #[cfg(feature = "frm")] use super::utils::{self as connector_utils, FrmTransactionRouterDataRequest}; use crate::{ @@ -35,10 +38,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Riskified; +#[derive(Clone)] +pub struct Riskified { + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} impl Riskified { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMajorUnitForConnector, + } + } + #[cfg(feature = "frm")] pub fn generate_authorization_signature( &self, @@ -173,7 +184,17 @@ impl req: &frm_types::FrmCheckoutRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let req_obj = riskified::RiskifiedPaymentsCheckoutRequest::try_from(req)?; + let amount = convert_amount( + self.amount_converter, + MinorUnit::new(req.request.amount), + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + )?; + let req_data = riskified::RiskifiedRouterData::from((amount, req)); + let req_obj = riskified::RiskifiedPaymentsCheckoutRequest::try_from(&req_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } @@ -293,7 +314,17 @@ impl Ok(RequestContent::Json(Box::new(req_obj))) } _ => { - let req_obj = riskified::TransactionSuccessRequest::try_from(req)?; + let amount = convert_amount( + self.amount_converter, + MinorUnit::new(req.request.amount), + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + )?; + let req_data = riskified::RiskifiedRouterData::from((amount, req)); + let req_obj = riskified::TransactionSuccessRequest::try_from(&req_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } } diff --git a/crates/router/src/connector/riskified/transformers/api.rs b/crates/router/src/connector/riskified/transformers/api.rs index d2d38855daf..bbeb045f692 100644 --- a/crates/router/src/connector/riskified/transformers/api.rs +++ b/crates/router/src/connector/riskified/transformers/api.rs @@ -1,5 +1,10 @@ use api_models::payments::AdditionalPaymentData; -use common_utils::{ext_traits::ValueExt, id_type, pii::Email}; +use common_utils::{ + ext_traits::ValueExt, + id_type, + pii::Email, + types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, +}; use error_stack::{self, ResultExt}; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -7,17 +12,37 @@ use time::PrimitiveDateTime; use crate::{ connector::utils::{ - AddressDetailsData, FraudCheckCheckoutRequest, FraudCheckTransactionRequest, RouterData, + convert_amount, AddressDetailsData, FraudCheckCheckoutRequest, + FraudCheckTransactionRequest, RouterData, }, core::{errors, fraud_check::types as core_types}, types::{ - self, api, api::Fulfillment, fraud_check as frm_types, storage::enums as storage_enums, + self, + api::{self, Fulfillment}, + fraud_check as frm_types, + storage::enums as storage_enums, ResponseId, ResponseRouterData, }, }; type Error = error_stack::Report<errors::ConnectorError>; +pub struct RiskifiedRouterData<T> { + pub amount: StringMajorUnit, + pub router_data: T, + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} + +impl<T> From<(StringMajorUnit, T)> for RiskifiedRouterData<T> { + fn from((amount, router_data): (StringMajorUnit, T)) -> Self { + Self { + amount, + router_data, + amount_converter: &StringMajorUnitForConnector, + } + } +} + #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct RiskifiedPaymentsCheckoutRequest { order: CheckoutRequest, @@ -35,7 +60,7 @@ pub struct CheckoutRequest { updated_at: PrimitiveDateTime, gateway: Option<String>, browser_ip: Option<std::net::IpAddr>, - total_price: i64, + total_price: StringMajorUnit, total_discounts: i64, cart_token: String, referring_site: String, @@ -60,13 +85,13 @@ pub struct PaymentDetails { #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct ShippingLines { - price: i64, + price: StringMajorUnit, title: Option<String>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct DiscountCodes { - amount: i64, + amount: StringMajorUnit, code: Option<String>, } @@ -110,7 +135,7 @@ pub struct OrderAddress { #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct LineItem { - price: i64, + price: StringMajorUnit, quantity: i32, title: String, product_type: Option<api_models::payments::ProductType>, @@ -132,9 +157,14 @@ pub struct RiskifiedMetadata { shipping_lines: Vec<ShippingLines>, } -impl TryFrom<&frm_types::FrmCheckoutRouterData> for RiskifiedPaymentsCheckoutRequest { +impl TryFrom<&RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>> + for RiskifiedPaymentsCheckoutRequest +{ type Error = Error; - fn try_from(payment_data: &frm_types::FrmCheckoutRouterData) -> Result<Self, Self::Error> { + fn try_from( + payment: &RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>, + ) -> Result<Self, Self::Error> { + let payment_data = payment.router_data.clone(); let metadata: RiskifiedMetadata = payment_data .frm_metadata .clone() @@ -148,6 +178,33 @@ impl TryFrom<&frm_types::FrmCheckoutRouterData> for RiskifiedPaymentsCheckoutReq let billing_address = payment_data.get_billing()?; let shipping_address = payment_data.get_shipping_address_with_phone_number()?; let address = payment_data.get_billing_address()?; + let line_items = payment_data + .request + .get_order_details()? + .iter() + .map(|order_detail| { + let price = convert_amount( + payment.amount_converter, + order_detail.amount, + payment_data.request.currency.ok_or_else(|| { + errors::ConnectorError::MissingRequiredField { + field_name: "currency", + } + })?, + )?; + + Ok(LineItem { + price, + quantity: i32::from(order_detail.quantity), + title: order_detail.product_name.clone(), + product_type: order_detail.product_type.clone(), + requires_shipping: order_detail.requires_shipping, + product_id: order_detail.product_id.clone(), + category: order_detail.category.clone(), + brand: order_detail.brand.clone(), + }) + }) + .collect::<Result<Vec<_>, Self::Error>>()?; Ok(Self { order: CheckoutRequest { @@ -156,23 +213,9 @@ impl TryFrom<&frm_types::FrmCheckoutRouterData> for RiskifiedPaymentsCheckoutReq created_at: common_utils::date_time::now(), updated_at: common_utils::date_time::now(), gateway: payment_data.request.gateway.clone(), - total_price: payment_data.request.amount, + total_price: payment.amount.clone(), cart_token: payment_data.attempt_id.clone(), - line_items: payment_data - .request - .get_order_details()? - .iter() - .map(|order_detail| LineItem { - price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future. - quantity: i32::from(order_detail.quantity), - title: order_detail.product_name.clone(), - product_type: order_detail.product_type.clone(), - requires_shipping: order_detail.requires_shipping, - product_id: order_detail.product_id.clone(), - category: order_detail.category.clone(), - brand: order_detail.brand.clone(), - }) - .collect::<Vec<_>>(), + line_items, source: Source::DesktopWeb, billing_address: OrderAddress::try_from(billing_address).ok(), shipping_address: OrderAddress::try_from(shipping_address).ok(), @@ -411,7 +454,7 @@ pub struct SuccessfulTransactionData { pub struct TransactionDecisionData { external_status: TransactionStatus, reason: Option<String>, - amount: i64, + amount: StringMajorUnit, currency: storage_enums::Currency, #[serde(with = "common_utils::custom_serde::iso8601")] decided_at: PrimitiveDateTime, @@ -429,16 +472,21 @@ pub enum TransactionStatus { Approved, } -impl TryFrom<&frm_types::FrmTransactionRouterData> for TransactionSuccessRequest { +impl TryFrom<&RiskifiedRouterData<&frm_types::FrmTransactionRouterData>> + for TransactionSuccessRequest +{ type Error = Error; - fn try_from(item: &frm_types::FrmTransactionRouterData) -> Result<Self, Self::Error> { + fn try_from( + item_data: &RiskifiedRouterData<&frm_types::FrmTransactionRouterData>, + ) -> Result<Self, Self::Error> { + let item = item_data.router_data.clone(); Ok(Self { order: SuccessfulTransactionData { id: item.attempt_id.clone(), decision: TransactionDecisionData { external_status: TransactionStatus::Approved, reason: None, - amount: item.request.amount, + amount: item_data.amount.clone(), currency: item.request.get_currency()?, decided_at: common_utils::date_time::now(), payment_details: [TransactionPaymentDetails { diff --git a/crates/router/src/types/api/fraud_check.rs b/crates/router/src/types/api/fraud_check.rs index 2d1a42092f4..213aef9cf03 100644 --- a/crates/router/src/types/api/fraud_check.rs +++ b/crates/router/src/types/api/fraud_check.rs @@ -51,7 +51,7 @@ impl FraudCheckConnectorData { Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd))) } enums::FrmConnectors::Riskified => { - Ok(ConnectorEnum::Old(Box::new(&connector::Riskified))) + Ok(ConnectorEnum::Old(Box::new(connector::Riskified::new()))) } } }
2024-10-17T18:02:20Z
## Description <!-- Describe your changes in detail --> This PR does amount conversion changes for Riskified Connector and it accepts the amount in MinorUnit ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes https://github.com/juspay/hyperswitch/issues/6139 ## Test Case 1. Create an FRM payment with Riskified ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_zDKkW8FG9RWqLNhMLVekbZbKOO1AYL8AEOQMKBQx0e0MbbmvKbGF32hdEnyA4JuS' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer2", "email": "guest@example.com", "name": "Bob Smith", "phone": "999999999", "phone_country_code": "+91", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "31 Sherwood Gardens", "line3": "31 Sherwood Gardens", "city": "London", "state": "Manchester", "zip": "E14 9wn", "country": "GB", "first_name": "Bob", "last_name": "Smith" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "frm_metadata": { "vendor_name": "srujan", "shipping_lines": [ { "price": 240, "title": "customer" } ] }, "order_details": [ { "product_name": "gillete creme", "quantity": 2, "amount": 600 }, { "product_name": "gillete razor", "quantity": 1, "amount": 300 } ] }' ``` Response ``` { "payment_id": "pay_p2PnkzcC76EiUfkMHoS3", "merchant_id": "merchant_1732534203", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "stripe", "client_secret": "pay_p2PnkzcC76EiUfkMHoS3_secret_aJ2PoxDPJ177jxjuLJtI", "created": "2024-11-25T12:18:24.319Z", "currency": "USD", "customer_id": "StripeCustomer2", "customer": { "id": "StripeCustomer2", "name": "Bob Smith", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+91" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": null, "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "London", "country": "GB", "line1": "1467", "line2": "31 Sherwood Gardens", "line3": "31 Sherwood Gardens", "zip": "E14 9wn", "state": "Manchester", "first_name": "Bob", "last_name": "Smith" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": [ { "brand": null, "amount": 600, "category": null, "quantity": 2, "product_id": null, "product_name": "gillete creme", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "requires_shipping": null }, { "brand": null, "amount": 300, "category": null, "quantity": 1, "product_id": null, "product_name": "gillete razor", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "requires_shipping": null } ], "email": "guest@example.com", "name": "Bob Smith", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer2", "created_at": 1732537104, "expires": 1732540704, "secret": "epk_af52a2410328468da0efcceab4721688" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3QP1FGD5R7gDAGff0hjO4CcX", "frm_message": { "frm_name": "riskified", "frm_transaction_id": "pay_p2PnkzcC76EiUfkMHoS3_1", "frm_transaction_type": "pre_frm", "frm_status": "legit", "frm_score": null, "frm_reason": "Reviewed and approved by Riskified", "frm_error": null }, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3QP1FGD5R7gDAGff0hjO4CcX", "payment_link": null, "profile_id": "pro_zRAcxSJqv3OTKIPGkuxI", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_TSlADmpiVd230wMhKj67", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-25T12:33:24.319Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-11-25T12:18:27.847Z", "charges": null, "frm_metadata": { "vendor_name": "srujan", "shipping_lines": [ { "price": 240, "title": "customer" } ] }, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ```
cd6265887adf7c17136e9fb608e97e6dd535e360
[ "crates/router/src/connector/riskified.rs", "crates/router/src/connector/riskified/transformers/api.rs", "crates/router/src/types/api/fraud_check.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6357
Bug: feat(opensearch): add additional filters and create sessionizer indexes for local Global search has two components: - Free flow search, wherein search takes place across all fields available to search upon - Search on a specific field based on the field filter Additional filters should be added for global search to search on a specific field. A list of values can be provided for every filter field which will be added to the query in order to extract responses from opensearch / elasticsearch. Existing filters (fields): - payment_method - currency - status - customer_email - search_tags New filters to be added (fields): - connector - payment_method_type - card_network - card_last_4 - payment_id
diff --git a/config/config.example.toml b/config/config.example.toml index c0358d91a26..8f04ba49831 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -728,6 +728,10 @@ payment_attempts = "hyperswitch-payment-attempt-events" payment_intents = "hyperswitch-payment-intent-events" refunds = "hyperswitch-refund-events" disputes = "hyperswitch-dispute-events" +sessionizer_payment_attempts = "sessionizer-payment-attempt-events" +sessionizer_payment_intents = "sessionizer-payment-intent-events" +sessionizer_refunds = "sessionizer-refund-events" +sessionizer_disputes = "sessionizer-dispute-events" [saved_payment_methods] sdk_eligible_payment_methods = "card" diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 5dce5be9c96..cfefe9a130f 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -252,6 +252,10 @@ payment_attempts = "hyperswitch-payment-attempt-events" payment_intents = "hyperswitch-payment-intent-events" refunds = "hyperswitch-refund-events" disputes = "hyperswitch-dispute-events" +sessionizer_payment_attempts = "sessionizer-payment-attempt-events" +sessionizer_payment_intents = "sessionizer-payment-intent-events" +sessionizer_refunds = "sessionizer-refund-events" +sessionizer_disputes = "sessionizer-dispute-events" # Configuration for the Key Manager Service [key_manager] diff --git a/config/development.toml b/config/development.toml index 0153c6ef102..29cd2dd048d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -732,6 +732,10 @@ payment_attempts = "hyperswitch-payment-attempt-events" payment_intents = "hyperswitch-payment-intent-events" refunds = "hyperswitch-refund-events" disputes = "hyperswitch-dispute-events" +sessionizer_payment_attempts = "sessionizer-payment-attempt-events" +sessionizer_payment_intents = "sessionizer-payment-intent-events" +sessionizer_refunds = "sessionizer-refund-events" +sessionizer_disputes = "sessionizer-dispute-events" [saved_payment_methods] sdk_eligible_payment_methods = "card" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 5ffe5df138f..006b017de0b 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -556,6 +556,10 @@ payment_attempts = "hyperswitch-payment-attempt-events" payment_intents = "hyperswitch-payment-intent-events" refunds = "hyperswitch-refund-events" disputes = "hyperswitch-dispute-events" +sessionizer_payment_attempts = "sessionizer-payment-attempt-events" +sessionizer_payment_intents = "sessionizer-payment-intent-events" +sessionizer_refunds = "sessionizer-refund-events" +sessionizer_disputes = "sessionizer-dispute-events" [saved_payment_methods] sdk_eligible_payment_methods = "card" diff --git a/config/vector.yaml b/config/vector.yaml index 54ff25cab5a..3f0709ae03c 100644 --- a/config/vector.yaml +++ b/config/vector.yaml @@ -18,6 +18,15 @@ sources: decoding: codec: json + sessionized_kafka_tx_events: + type: kafka + bootstrap_servers: kafka0:29092 + group_id: sessionizer + topics: + - ^sessionizer + decoding: + codec: json + app_logs: type: docker_logs include_labels: @@ -35,10 +44,19 @@ sources: encoding: json transforms: + events_create_ts: + inputs: + - kafka_tx_events + source: |- + .timestamp = from_unix_timestamp(.created_at, unit: "seconds") ?? now() + ."@timestamp" = from_unix_timestamp(.created_at, unit: "seconds") ?? now() + type: remap + plus_1_events: type: filter inputs: - - kafka_tx_events + - events_create_ts + - sessionized_events_create_ts condition: ".sign_flag == 1" hs_server_logs: @@ -54,13 +72,13 @@ transforms: source: |- .message = parse_json!(.message) - events: + sessionized_events_create_ts: type: remap inputs: - - plus_1_events + - sessionized_kafka_tx_events source: |- - .timestamp = from_unix_timestamp!(.created_at, unit: "seconds") - ."@timestamp" = from_unix_timestamp(.created_at, unit: "seconds") ?? now() + .timestamp = from_unix_timestamp(.created_at, unit: "milliseconds") ?? now() + ."@timestamp" = from_unix_timestamp(.created_at, unit: "milliseconds") ?? now() sdk_transformed: type: throttle @@ -74,7 +92,7 @@ sinks: opensearch_events_1: type: elasticsearch inputs: - - events + - plus_1_events endpoints: - "https://opensearch:9200" id_key: message_key @@ -98,7 +116,7 @@ sinks: opensearch_events_2: type: elasticsearch inputs: - - events + - plus_1_events endpoints: - "https://opensearch:9200" id_key: message_key @@ -120,6 +138,33 @@ sinks: # Add a date suffixed index for better grouping index: "vector-{{ .topic }}-%Y-%m-%d" + opensearch_events_3: + type: elasticsearch + inputs: + - plus_1_events + endpoints: + - "https://opensearch:9200" + id_key: message_key + api_version: v7 + tls: + verify_certificate: false + verify_hostname: false + auth: + strategy: basic + user: admin + password: 0penS3arc# + encoding: + except_fields: + - message_key + - offset + - partition + - topic + - clickhouse_database + - last_synced + - sign_flag + bulk: + index: "{{ .topic }}" + opensearch_logs: type: elasticsearch inputs: @@ -143,6 +188,7 @@ sinks: type: loki inputs: - kafka_tx_events + - sessionized_kafka_tx_events endpoint: http://loki:3100 labels: source: vector diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index 3be9688d8f7..a6e6c486ebe 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -42,6 +42,10 @@ pub struct OpenSearchIndexes { pub payment_intents: String, pub refunds: String, pub disputes: String, + pub sessionizer_payment_attempts: String, + pub sessionizer_payment_intents: String, + pub sessionizer_refunds: String, + pub sessionizer_disputes: String, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash)] @@ -81,6 +85,10 @@ impl Default for OpenSearchConfig { payment_intents: "hyperswitch-payment-intent-events".to_string(), refunds: "hyperswitch-refund-events".to_string(), disputes: "hyperswitch-dispute-events".to_string(), + sessionizer_payment_attempts: "sessionizer-payment-attempt-events".to_string(), + sessionizer_payment_intents: "sessionizer-payment-intent-events".to_string(), + sessionizer_refunds: "sessionizer-refund-events".to_string(), + sessionizer_disputes: "sessionizer-dispute-events".to_string(), }, } } @@ -219,6 +227,14 @@ impl OpenSearchClient { SearchIndex::PaymentIntents => self.indexes.payment_intents.clone(), SearchIndex::Refunds => self.indexes.refunds.clone(), SearchIndex::Disputes => self.indexes.disputes.clone(), + SearchIndex::SessionizerPaymentAttempts => { + self.indexes.sessionizer_payment_attempts.clone() + } + SearchIndex::SessionizerPaymentIntents => { + self.indexes.sessionizer_payment_intents.clone() + } + SearchIndex::SessionizerRefunds => self.indexes.sessionizer_refunds.clone(), + SearchIndex::SessionizerDisputes => self.indexes.sessionizer_disputes.clone(), } } @@ -324,6 +340,36 @@ impl OpenSearchIndexes { )) })?; + when( + self.sessionizer_payment_attempts.is_default_or_empty(), + || { + Err(ApplicationError::InvalidConfigurationValueError( + "Opensearch Sessionizer Payment Attempts index must not be empty".into(), + )) + }, + )?; + + when( + self.sessionizer_payment_intents.is_default_or_empty(), + || { + Err(ApplicationError::InvalidConfigurationValueError( + "Opensearch Sessionizer Payment Intents index must not be empty".into(), + )) + }, + )?; + + when(self.sessionizer_refunds.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Opensearch Sessionizer Refunds index must not be empty".into(), + )) + })?; + + when(self.sessionizer_disputes.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Opensearch Sessionizer Disputes index must not be empty".into(), + )) + })?; + Ok(()) } } diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs index c81ff2f416b..f53b07b1232 100644 --- a/crates/analytics/src/search.rs +++ b/crates/analytics/src/search.rs @@ -92,6 +92,44 @@ pub async fn msearch_results( .switch()?; } }; + if let Some(connector) = filters.connector { + if !connector.is_empty() { + query_builder + .add_filter_clause("connector.keyword".to_string(), connector.clone()) + .switch()?; + } + }; + if let Some(payment_method_type) = filters.payment_method_type { + if !payment_method_type.is_empty() { + query_builder + .add_filter_clause( + "payment_method_type.keyword".to_string(), + payment_method_type.clone(), + ) + .switch()?; + } + }; + if let Some(card_network) = filters.card_network { + if !card_network.is_empty() { + query_builder + .add_filter_clause("card_network.keyword".to_string(), card_network.clone()) + .switch()?; + } + }; + if let Some(card_last_4) = filters.card_last_4 { + if !card_last_4.is_empty() { + query_builder + .add_filter_clause("card_last_4.keyword".to_string(), card_last_4.clone()) + .switch()?; + } + }; + if let Some(payment_id) = filters.payment_id { + if !payment_id.is_empty() { + query_builder + .add_filter_clause("payment_id.keyword".to_string(), payment_id.clone()) + .switch()?; + } + }; }; if let Some(time_range) = req.time_range { @@ -217,6 +255,44 @@ pub async fn search_results( .switch()?; } }; + if let Some(connector) = filters.connector { + if !connector.is_empty() { + query_builder + .add_filter_clause("connector.keyword".to_string(), connector.clone()) + .switch()?; + } + }; + if let Some(payment_method_type) = filters.payment_method_type { + if !payment_method_type.is_empty() { + query_builder + .add_filter_clause( + "payment_method_type.keyword".to_string(), + payment_method_type.clone(), + ) + .switch()?; + } + }; + if let Some(card_network) = filters.card_network { + if !card_network.is_empty() { + query_builder + .add_filter_clause("card_network.keyword".to_string(), card_network.clone()) + .switch()?; + } + }; + if let Some(card_last_4) = filters.card_last_4 { + if !card_last_4.is_empty() { + query_builder + .add_filter_clause("card_last_4.keyword".to_string(), card_last_4.clone()) + .switch()?; + } + }; + if let Some(payment_id) = filters.payment_id { + if !payment_id.is_empty() { + query_builder + .add_filter_clause("payment_id.keyword".to_string(), payment_id.clone()) + .switch()?; + } + }; }; if let Some(time_range) = search_req.time_range { diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs index 24dd0effcbb..a33dd100c79 100644 --- a/crates/api_models/src/analytics/search.rs +++ b/crates/api_models/src/analytics/search.rs @@ -9,6 +9,11 @@ pub struct SearchFilters { pub status: Option<Vec<String>>, pub customer_email: Option<Vec<HashedString<common_utils::pii::EmailStrategy>>>, pub search_tags: Option<Vec<HashedString<WithType>>>, + pub connector: Option<Vec<String>>, + pub payment_method_type: Option<Vec<String>>, + pub card_network: Option<Vec<String>>, + pub card_last_4: Option<Vec<String>>, + pub payment_id: Option<Vec<String>>, } impl SearchFilters { pub fn is_all_none(&self) -> bool { @@ -17,6 +22,11 @@ impl SearchFilters { && self.status.is_none() && self.customer_email.is_none() && self.search_tags.is_none() + && self.connector.is_none() + && self.payment_method_type.is_none() + && self.card_network.is_none() + && self.card_last_4.is_none() + && self.payment_id.is_none() } } @@ -58,6 +68,10 @@ pub enum SearchIndex { PaymentIntents, Refunds, Disputes, + SessionizerPaymentAttempts, + SessionizerPaymentIntents, + SessionizerRefunds, + SessionizerDisputes, } #[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy)] diff --git a/crates/router/src/consts/opensearch.rs b/crates/router/src/consts/opensearch.rs index 277b0e946ba..c9eeec1b343 100644 --- a/crates/router/src/consts/opensearch.rs +++ b/crates/router/src/consts/opensearch.rs @@ -1,12 +1,16 @@ use api_models::analytics::search::SearchIndex; -pub const fn get_search_indexes() -> [SearchIndex; 4] { +pub const fn get_search_indexes() -> [SearchIndex; 8] { [ SearchIndex::PaymentAttempts, SearchIndex::PaymentIntents, SearchIndex::Refunds, SearchIndex::Disputes, + SearchIndex::SessionizerPaymentAttempts, + SearchIndex::SessionizerPaymentIntents, + SearchIndex::SessionizerRefunds, + SearchIndex::SessionizerDisputes, ] } -pub const SEARCH_INDEXES: [SearchIndex; 4] = get_search_indexes(); +pub const SEARCH_INDEXES: [SearchIndex; 8] = get_search_indexes();
2024-10-17T12:27:42Z
## Description <!-- Describe your changes in detail --> Global search has two components: - Free flow search, wherein search takes place across all fields available to search upon - Search on a specific field based on the field filter In this PR, additional filters have been added for global search to search on a specific field. A list of values can be provided for every filter field which will be added to the query in order to extract responses from opensearch / elasticsearch. Existing filters (fields): - payment_method - currency - status - customer_email - search_tags New filters added (fields): - connector - payment_method_type - card_network - card_last_4 - payment_id ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Enhance search experience on global search using filters ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> The following filters can be used to be searched upon: - connector - payment_method_type - card_network - card_last_4 - payment_id Hit the following curl for the `/search` API ```bash curl --location 'http://localhost:8080/analytics/v1/search' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTI0ODM1MCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.TQD6wYkiTXlTvPW3-mH8FzEP1d7hXw9SmWgjVMH7flk' \ --header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '{ "query": "merchant_1726046328", "filters": { "payment_method": [ "card" ] }, "timeRange": { "startTime": "2024-09-13T00:30:00Z", "endTime": "2024-10-18T21:45:00Z" } }' ```
962afbd084458e9afb11a0278a8210edd9226a3d
The following filters can be used to be searched upon: - connector - payment_method_type - card_network - card_last_4 - payment_id Hit the following curl for the `/search` API ```bash curl --location 'http://localhost:8080/analytics/v1/search' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTI0ODM1MCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.TQD6wYkiTXlTvPW3-mH8FzEP1d7hXw9SmWgjVMH7flk' \ --header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '{ "query": "merchant_1726046328", "filters": { "payment_method": [ "card" ] }, "timeRange": { "startTime": "2024-09-13T00:30:00Z", "endTime": "2024-10-18T21:45:00Z" } }' ```
[ "config/config.example.toml", "config/deployments/env_specific.toml", "config/development.toml", "config/docker_compose.toml", "config/vector.yaml", "crates/analytics/src/opensearch.rs", "crates/analytics/src/search.rs", "crates/api_models/src/analytics/search.rs", "crates/router/src/consts/opensearch.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6348
Bug: set the eligible connector in payment attempt for network transaction id based mit flow [Reference pr](https://github.com/juspay/hyperswitch/pull/6245) In the MIT flow when the recurring details is of type `"type": "network_transaction_id_and_card_details"` the eligible connector needs to be set in the payment attempt.
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 68f318958a2..a6ddc2e2180 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4193,6 +4193,10 @@ where } }; + // Set the eligible connector in the attempt + payment_data + .set_connector_in_payment_attempt(Some(eligible_connector_data.connector_name.to_string())); + // Set `NetworkMandateId` as the MandateId payment_data.set_mandate_id(payments_api::MandateIds { mandate_id: None,
2024-10-17T07:50:34Z
## Description <!-- Describe your changes in detail --> In the MIT flow when the recurring details is of type "type": "network_transaction_id_and_card_details" the eligible connector needs to be set in the payment attempt. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Create merchant connector account for cybersource -> Make a MIT payment with `"type": "network_transaction_id_and_card_details"` ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_OJYRaFClX8PIIwCNrPWUMttJWZrAXUNbBiyA1GvyYyaxRK5EsqODd2ON8KTOlTMa' \ --header 'Content-Type: application/json' \ --data-raw '{ "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "email": "guest@example.com", "payment_method": "card", "payment_method_type": "credit", "off_session": true, "recurring_details": { "type": "network_transaction_id_and_card_details", "data": { "card_number": "5454545454545454", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "name name", "network_transaction_id": "737" } }, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" } }' ``` ``` { "payment_id": "pay_ZEs9n2F6Yp0oy50G8VmN", "merchant_id": "merchant_1729157921", "status": "succeeded", "amount": 499, "net_amount": 499, "amount_capturable": 0, "amount_received": 499, "connector": "cybersource", "client_secret": "pay_ZEs9n2F6Yp0oy50G8VmN_secret_fC2BsOIUxNEDzAtimD0X", "created": "2024-10-17T09:39:04.760Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "5454", "card_type": "CREDIT", "card_network": null, "card_issuer": "BANKHANDLOWYWWARSZAWIE.S.A.", "card_issuing_country": "POLAND", "card_isin": "545454", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7291579463536087703954", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_ZEs9n2F6Yp0oy50G8VmN_1", "payment_link": null, "profile_id": "pro_F0y6R0BOaHFdIv6wsaT8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HMDXW38hX91dX1Z5z1xC", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-17T09:54:04.760Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-17T09:39:07.091Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ```
881f5fd0149cb5573eb31451fceb596092eab79a
Create merchant connector account for cybersource -> Make a MIT payment with `"type": "network_transaction_id_and_card_details"` ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_OJYRaFClX8PIIwCNrPWUMttJWZrAXUNbBiyA1GvyYyaxRK5EsqODd2ON8KTOlTMa' \ --header 'Content-Type: application/json' \ --data-raw '{ "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "email": "guest@example.com", "payment_method": "card", "payment_method_type": "credit", "off_session": true, "recurring_details": { "type": "network_transaction_id_and_card_details", "data": { "card_number": "5454545454545454", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "name name", "network_transaction_id": "737" } }, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" } }' ``` ``` { "payment_id": "pay_ZEs9n2F6Yp0oy50G8VmN", "merchant_id": "merchant_1729157921", "status": "succeeded", "amount": 499, "net_amount": 499, "amount_capturable": 0, "amount_received": 499, "connector": "cybersource", "client_secret": "pay_ZEs9n2F6Yp0oy50G8VmN_secret_fC2BsOIUxNEDzAtimD0X", "created": "2024-10-17T09:39:04.760Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "5454", "card_type": "CREDIT", "card_network": null, "card_issuer": "BANKHANDLOWYWWARSZAWIE.S.A.", "card_issuing_country": "POLAND", "card_isin": "545454", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7291579463536087703954", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_ZEs9n2F6Yp0oy50G8VmN_1", "payment_link": null, "profile_id": "pro_F0y6R0BOaHFdIv6wsaT8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HMDXW38hX91dX1Z5z1xC", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-17T09:54:04.760Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-17T09:39:07.091Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ```
[ "crates/router/src/core/payments.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6343
Bug: feat(analytics): add customer_id as filter for payment intents Add customer_id as a filter for payment intents
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index af46baed23e..3e8915c60a2 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -205,7 +205,8 @@ pub async fn get_metrics( | PaymentIntentMetrics::SessionizedPaymentsSuccessRate => metrics_builder .payments_success_rate .add_metrics_bucket(&value), - PaymentIntentMetrics::SessionizedPaymentProcessedAmount => metrics_builder + PaymentIntentMetrics::SessionizedPaymentProcessedAmount + | PaymentIntentMetrics::PaymentProcessedAmount => metrics_builder .payment_processed_amount .add_metrics_bucket(&value), PaymentIntentMetrics::SessionizedPaymentsDistribution => metrics_builder diff --git a/crates/analytics/src/payment_intents/filters.rs b/crates/analytics/src/payment_intents/filters.rs index e81b050214c..d03d6c2a15f 100644 --- a/crates/analytics/src/payment_intents/filters.rs +++ b/crates/analytics/src/payment_intents/filters.rs @@ -54,4 +54,5 @@ pub struct PaymentIntentFilterRow { pub status: Option<DBEnumWrapper<IntentStatus>>, pub currency: Option<DBEnumWrapper<Currency>>, pub profile_id: Option<String>, + pub customer_id: Option<String>, } diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs index e9d7f244306..9aa7d3e9771 100644 --- a/crates/analytics/src/payment_intents/metrics.rs +++ b/crates/analytics/src/payment_intents/metrics.rs @@ -17,6 +17,7 @@ use crate::{ }; mod payment_intent_count; +mod payment_processed_amount; mod payments_success_rate; mod sessionized_metrics; mod smart_retried_amount; @@ -24,6 +25,7 @@ mod successful_smart_retries; mod total_smart_retries; use payment_intent_count::PaymentIntentCount; +use payment_processed_amount::PaymentProcessedAmount; use payments_success_rate::PaymentsSuccessRate; use smart_retried_amount::SmartRetriedAmount; use successful_smart_retries::SuccessfulSmartRetries; @@ -107,6 +109,11 @@ where .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } + Self::PaymentProcessedAmount => { + PaymentProcessedAmount + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } Self::SessionizedSuccessfulSmartRetries => { sessionized_metrics::SuccessfulSmartRetries .load_metrics(dimensions, auth, filters, granularity, time_range, pool) diff --git a/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs new file mode 100644 index 00000000000..51b574f4ad3 --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs @@ -0,0 +1,161 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct PaymentProcessedAmount; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for PaymentProcessedAmount +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + auth: &AuthInfo, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntent); + + let mut dimensions = dimensions.to_vec(); + + dimensions.push(PaymentIntentDimensions::PaymentIntentStatus); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + + query_builder + .add_select_column("attempt_count == 1 as first_attempt") + .switch()?; + + query_builder.add_select_column("currency").switch()?; + + query_builder + .add_select_column(Aggregate::Sum { + field: "amount", + alias: Some("total"), + }) + .switch()?; + + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + query_builder + .add_group_by_clause("attempt_count") + .attach_printable("Error grouping by attempt_count") + .switch()?; + + query_builder + .add_group_by_clause("currency") + .attach_printable("Error grouping by currency") + .switch()?; + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .add_filter_clause( + PaymentIntentDimensions::PaymentIntentStatus, + storage_enums::IntentStatus::Succeeded, + ) + .switch()?; + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + None, + i.currency.as_ref().map(|i| i.0), + i.profile_id.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/types.rs b/crates/analytics/src/payment_intents/types.rs index 03f2a196c20..bb5141297c5 100644 --- a/crates/analytics/src/payment_intents/types.rs +++ b/crates/analytics/src/payment_intents/types.rs @@ -30,6 +30,11 @@ where .add_filter_in_range_clause(PaymentIntentDimensions::ProfileId, &self.profile_id) .attach_printable("Error adding profile id filter")?; } + if !self.customer_id.is_empty() { + builder + .add_filter_in_range_clause("customer_id", &self.customer_id) + .attach_printable("Error adding customer id filter")?; + } Ok(()) } } diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index 7ce338f7db3..d746594e36e 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -451,6 +451,12 @@ impl<T: AnalyticsDataSource> ToSql<T> for &common_utils::id_type::PaymentId { } } +impl<T: AnalyticsDataSource> ToSql<T> for common_utils::id_type::CustomerId { + fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { + Ok(self.get_string_repr().to_owned()) + } +} + /// Implement `ToSql` on arrays of types that impl `ToString`. macro_rules! impl_to_sql_for_to_string { ($($type:ty),+) => { diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 89eb2ee0bde..7c90e37c55f 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -652,10 +652,15 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFi ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let customer_id: Option<String> = row.try_get("customer_id").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; Ok(Self { status, currency, profile_id, + customer_id, }) } } diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs index d018437ae8c..60662f2e90a 100644 --- a/crates/api_models/src/analytics/payment_intents.rs +++ b/crates/api_models/src/analytics/payment_intents.rs @@ -16,6 +16,8 @@ pub struct PaymentIntentFilters { pub currency: Vec<Currency>, #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, + #[serde(default)] + pub customer_id: Vec<id_type::CustomerId>, } #[derive( @@ -62,6 +64,7 @@ pub enum PaymentIntentMetrics { SmartRetriedAmount, PaymentIntentCount, PaymentsSuccessRate, + PaymentProcessedAmount, SessionizedSuccessfulSmartRetries, SessionizedTotalSmartRetries, SessionizedSmartRetriedAmount,
2024-10-17T06:31:48Z
## Description <!-- Describe your changes in detail --> - Added `customer_id` as a filter for payment intents - Added `payment_processed_amount` metric for `payment_intents` table ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Filter out payments for a particular customer through the `customer_id` ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Hit the curl: Metric data would be obtained based on the customer_id filter applied. ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTI0ODM1MCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.TQD6wYkiTXlTvPW3-mH8FzEP1d7hXw9SmWgjVMH7flk' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-09-11T00:00:00Z", "endTime": "2024-10-26T09:22:30Z" }, "filters": { "customer_id": ["StripeCustomer"] }, "mode": "ORDER", "source": "BATCH", "metrics": [ "payment_processed_amount" ] } ]' ```
829a20cc933267551e49565d06eb08e03e5f13bb
Hit the curl: Metric data would be obtained based on the customer_id filter applied. ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTI0ODM1MCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.TQD6wYkiTXlTvPW3-mH8FzEP1d7hXw9SmWgjVMH7flk' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-09-11T00:00:00Z", "endTime": "2024-10-26T09:22:30Z" }, "filters": { "customer_id": ["StripeCustomer"] }, "mode": "ORDER", "source": "BATCH", "metrics": [ "payment_processed_amount" ] } ]' ```
[ "crates/analytics/src/payment_intents/core.rs", "crates/analytics/src/payment_intents/filters.rs", "crates/analytics/src/payment_intents/metrics.rs", "crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs", "crates/analytics/src/payment_intents/types.rs", "crates/analytics/src/query.rs", "crates/analytics/src/sqlx.rs", "crates/api_models/src/analytics/payment_intents.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6135
Bug: [REFACTOR]: [OPAYO] Add amount conversion framework to Opayo ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://docs.recurly.com/docs/opayo) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [ ] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR? ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/router/src/connector/opayo.rs b/crates/router/src/connector/opayo.rs index cd1ef67f662..3e7edba2128 100644 --- a/crates/router/src/connector/opayo.rs +++ b/crates/router/src/connector/opayo.rs @@ -1,8 +1,9 @@ mod transformers; -use std::fmt::Debug; - -use common_utils::request::RequestContent; +use common_utils::{ + request::RequestContent, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, +}; use diesel_models::enums; use error_stack::{report, ResultExt}; use masking::ExposeInterface; @@ -10,7 +11,7 @@ use transformers as opayo; use crate::{ configs::settings, - connector::utils as connector_utils, + connector::{utils as connector_utils, utils::convert_amount}, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, @@ -27,8 +28,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Opayo; +#[derive(Clone)] +pub struct Opayo { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} + +impl Opayo { + pub fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} impl api::Payment for Opayo {} impl api::PaymentSession for Opayo {} @@ -197,7 +208,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = opayo::OpayoPaymentsRequest::try_from(req)?; + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + let connector_router_data = opayo::OpayoRouterData::from((amount, req)); + let connector_req = opayo::OpayoPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -433,7 +450,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = opayo::OpayoRefundRequest::try_from(req)?; + let refund_amount = convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + let connector_router_data = opayo::OpayoRouterData::from((refund_amount, req)); + let connector_req = opayo::OpayoRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index 16a76301ede..44069f3650b 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -1,3 +1,4 @@ +use common_utils::types::MinorUnit; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -6,10 +7,24 @@ use crate::{ core::errors, types::{self, api, domain, storage::enums}, }; +#[derive(Debug, Serialize)] +pub struct OpayoRouterData<T> { + pub amount: MinorUnit, + pub router_data: T, +} + +impl<T> From<(MinorUnit, T)> for OpayoRouterData<T> { + fn from((amount, router_data): (MinorUnit, T)) -> Self { + Self { + amount, + router_data, + } + } +} #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct OpayoPaymentsRequest { - amount: i64, + amount: MinorUnit, card: OpayoCard, } @@ -23,9 +38,12 @@ pub struct OpayoCard { complete: bool, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { +impl TryFrom<&OpayoRouterData<&types::PaymentsAuthorizeRouterData>> for OpayoPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + fn try_from( + item_data: &OpayoRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let item = item_data.router_data.clone(); match item.request.payment_method_data.clone() { domain::PaymentMethodData::Card(req_card) => { let card = OpayoCard { @@ -39,7 +57,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { complete: item.request.is_auto_capture()?, }; Ok(Self { - amount: item.request.amount, + amount: item_data.amount, card, }) } @@ -143,14 +161,14 @@ impl<F, T> // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct OpayoRefundRequest { - pub amount: i64, + pub amount: MinorUnit, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for OpayoRefundRequest { +impl<F> TryFrom<&OpayoRouterData<&types::RefundsRouterData<F>>> for OpayoRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &OpayoRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { - amount: item.request.refund_amount, + amount: item.amount, }) } } diff --git a/crates/router/tests/connectors/opayo.rs b/crates/router/tests/connectors/opayo.rs index 6bca86fa813..585a6f4486b 100644 --- a/crates/router/tests/connectors/opayo.rs +++ b/crates/router/tests/connectors/opayo.rs @@ -15,7 +15,7 @@ impl utils::Connector for OpayoTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Opayo; utils::construct_connector_data_old( - Box::new(&Opayo), + Box::new(Opayo::new()), // Remove `dummy_connector` feature gate from module in `main.rs` when updating this to use actual connector variant types::Connector::DummyConnector1, types::api::GetToken::Connector,
2024-10-16T22:13:47Z
## Description <!-- Describe your changes in detail --> This PR adds amount conversion framework to Opayo. Opayo accepts amount in MinorUnit ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Amount conversion for Opayo Fixes #6135 <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). -->
881f5fd0149cb5573eb31451fceb596092eab79a
[ "crates/router/src/connector/opayo.rs", "crates/router/src/connector/opayo/transformers.rs", "crates/router/tests/connectors/opayo.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6117
Bug: [FEATURE] Generate Random Disputes for sample data ### Feature Description The issue is sub part of issue: #5991 (Please refer to this First) The current implementation of the generate_sample_data_for_user function generates sample data for payments and refunds. However, there is no functionality to generate sample disputes. This issue is about extending the generate_sample_data_for_user function to generate random disputes based on the sample payments created. Current Behavior - The /sample_data API generates sample payments and refunds. - No disputes are generated as part of the sample data generation process. Expected Behavior - The generate_sample_data_for_user function should also generate random disputes along with payments and refunds. - The number of disputes generated should be based on the number of payments created: 2 disputes if the number of payments is between 50 and 100. 1 dispute if the number of payments is less than 50. ### Possible Implementation Modify generate_sample_data_for_user Function: Update the function in `utils::user::sample_data::generate_sample_data` to create sample disputes based on the number of generated payments. The Data should be random and fields should be related to sample payments/refunds for which we are creating dispute. Call the Db function inside `generate_sample_data_for_user` to Batch insert sample disputes Call the Db function inside `delete_sample_data_for_user` to Delete sample disputes Test To generate Sample Data: ``` curl --location 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` To Delete Sample Data: ``` curl --location --request DELETE 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rs index 453b3edf00f..d098d1f76d9 100644 --- a/crates/router/src/core/user/sample_data.rs +++ b/crates/router/src/core/user/sample_data.rs @@ -1,6 +1,6 @@ use api_models::user::sample_data::SampleDataRequest; use common_utils::errors::ReportSwitchExt; -use diesel_models::RefundNew; +use diesel_models::{DisputeNew, RefundNew}; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentIntent; @@ -39,19 +39,23 @@ pub async fn generate_sample_data_for_user( .change_context(SampleDataError::InternalServerError) .attach_printable("Not able to fetch merchant key store")?; // If not able to fetch merchant key store for any reason, this should be an internal server error - let (payment_intents, payment_attempts, refunds): ( + let (payment_intents, payment_attempts, refunds, disputes): ( Vec<PaymentIntent>, Vec<diesel_models::user::sample_data::PaymentAttemptBatchNew>, Vec<RefundNew>, + Vec<DisputeNew>, ) = sample_data.into_iter().fold( - (Vec::new(), Vec::new(), Vec::new()), - |(mut pi, mut pa, mut rf), (payment_intent, payment_attempt, refund)| { + (Vec::new(), Vec::new(), Vec::new(), Vec::new()), + |(mut pi, mut pa, mut rf, mut dp), (payment_intent, payment_attempt, refund, dispute)| { pi.push(payment_intent); pa.push(payment_attempt); if let Some(refund) = refund { rf.push(refund); } - (pi, pa, rf) + if let Some(dispute) = dispute { + dp.push(dispute); + } + (pi, pa, rf, dp) }, ); @@ -70,6 +74,11 @@ pub async fn generate_sample_data_for_user( .insert_refunds_batch_for_sample_data(refunds) .await .switch()?; + state + .store + .insert_disputes_batch_for_sample_data(disputes) + .await + .switch()?; Ok(ApplicationResponse::StatusOk) } @@ -109,6 +118,11 @@ pub async fn delete_sample_data_for_user( .delete_refunds_for_sample_data(&merchant_id_del) .await .switch()?; + state + .store + .delete_disputes_for_sample_data(&merchant_id_del) + .await + .switch()?; Ok(ApplicationResponse::StatusOk) } diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index ea2556a5151..4f859d8e56a 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -8,7 +8,7 @@ use common_utils::{ }; #[cfg(feature = "v1")] use diesel_models::user::sample_data::PaymentAttemptBatchNew; -use diesel_models::RefundNew; +use diesel_models::{enums as storage_enums, DisputeNew, RefundNew}; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentIntent; use rand::{prelude::SliceRandom, thread_rng, Rng}; @@ -27,7 +27,14 @@ pub async fn generate_sample_data( req: SampleDataRequest, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, -) -> SampleDataResult<Vec<(PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>)>> { +) -> SampleDataResult< + Vec<( + PaymentIntent, + PaymentAttemptBatchNew, + Option<RefundNew>, + Option<DisputeNew>, + )>, +> { let sample_data_size: usize = req.record.unwrap_or(100); let key_manager_state = &state.into(); if !(10..=100).contains(&sample_data_size) { @@ -120,13 +127,23 @@ pub async fn generate_sample_data( let mut refunds_count = 0; + // 2 disputes if generated data size is between 50 and 100, 1 dispute if it is less than 50. + let number_of_disputes: usize = if sample_data_size >= 50 { 2 } else { 1 }; + + let mut disputes_count = 0; + let mut random_array: Vec<usize> = (1..=sample_data_size).collect(); // Shuffle the array let mut rng = thread_rng(); random_array.shuffle(&mut rng); - let mut res: Vec<(PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>)> = Vec::new(); + let mut res: Vec<( + PaymentIntent, + PaymentAttemptBatchNew, + Option<RefundNew>, + Option<DisputeNew>, + )> = Vec::new(); let start_time = req .start_time .unwrap_or(common_utils::date_time::now() - time::Duration::days(7)) @@ -353,7 +370,7 @@ pub async fn generate_sample_data( internal_reference_id: common_utils::generate_id_with_default_len("test"), external_reference_id: None, payment_id: payment_id.clone(), - attempt_id, + attempt_id: attempt_id.clone(), merchant_id: merchant_id.clone(), connector_transaction_id, connector_refund_id: None, @@ -387,7 +404,43 @@ pub async fn generate_sample_data( None }; - res.push((payment_intent, payment_attempt, refund)); + let dispute = + if disputes_count < number_of_disputes && !is_failed_payment && refund.is_none() { + disputes_count += 1; + Some(DisputeNew { + dispute_id: common_utils::generate_id_with_default_len("test"), + amount: (amount * 100).to_string(), + currency: payment_intent + .currency + .unwrap_or(common_enums::Currency::USD) + .to_string(), + dispute_stage: storage_enums::DisputeStage::Dispute, + dispute_status: storage_enums::DisputeStatus::DisputeOpened, + payment_id: payment_id.clone(), + attempt_id: attempt_id.clone(), + merchant_id: merchant_id.clone(), + connector_status: "Sample connector status".into(), + connector_dispute_id: common_utils::generate_id_with_default_len("test"), + connector_reason: Some("Sample Dispute".into()), + connector_reason_code: Some("123".into()), + challenge_required_by: None, + connector_created_at: None, + connector_updated_at: None, + connector: payment_attempt + .connector + .clone() + .unwrap_or(DummyConnector4.to_string()), + evidence: None, + profile_id: payment_intent.profile_id.clone(), + merchant_connector_id: payment_attempt.merchant_connector_id.clone(), + dispute_amount: amount * 100, + organization_id: org_id.clone(), + }) + } else { + None + }; + + res.push((payment_intent, payment_attempt, refund, dispute)); } Ok(res) }
2024-10-16T19:47:45Z
## Description <!-- Describe your changes in detail --> I added dispute generation to function `generate_sample_data` in `utils/user/sample_data.rs`. The number of disputes generated is based on the number of payments created: 2 disputes if the number of payments is between 50 and 100. 1 dispute if the number of payments is less than 50. Other changes I made is just to accommodate the dispute generation code changes. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #6117 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested manually. Initial state for both Case1 and Case2: Before sending POST request to `sample_data`, there are 18 non-generated `payment_attempt` records, and 0 `dispute` record. <img width="1384" alt="image" src="https://github.com/user-attachments/assets/a97abf7e-34d4-4bc2-b5e6-fd7ff2908c94"> <img width="1146" alt="image" src="https://github.com/user-attachments/assets/31dddc64-7063-41e3-80d0-c57d378debcf"> #### Case 1: 2 disputes if the number of payments is between 50 and 100. We send a POST request without payload to `sample_data`, by default, 100 `payment_attempt` records will be generated, along with 2 `dispute`. Now there are 118 generated `pyament_attempt` records, and 2 `dispute` records with `test_` prefixed `dispute_id`. <img width="1107" alt="image" src="https://github.com/user-attachments/assets/df612a03-dc3d-4af2-9588-a5b4381f7c09"> <img width="1384" alt="image" src="https://github.com/user-attachments/assets/16d5f449-4f92-417f-991e-8ddb4e9f2548"> #### Case 2: 1 dispute if the number of payments is less than 50. We send a POST request with payload `{ "record": 30 }` to `sample_data`, 30 `payment_attempt` records will be generated, along with 1 `dispute`. Now there are 48 generated `pyament_attempt` records, and 1 `dispute` records with `test_` prefixed `dispute_id`. <img width="1364" alt="image" src="https://github.com/user-attachments/assets/5e9f1712-3be2-4b88-acac-08ac866e64df"> <img width="1385" alt="image" src="https://github.com/user-attachments/assets/a2efec0a-cbec-4154-8d86-98aa5aecb3de"> #### Case Delete: When there exists data generated by `sample_api`, sending a `DELETE` request to `sample_api` deletes all the generated sample data (back to initial state in this example). <img width="1076" alt="image" src="https://github.com/user-attachments/assets/42414fe0-11d0-40ae-987d-7d0c8fd19d4b"> <img width="1057" alt="image" src="https://github.com/user-attachments/assets/4fe4cbba-21de-4b69-82f6-5049e61f69a6">
c3b0f7c1d6ad95034535048aa50ff6abe9ed6aa0
Tested manually. Initial state for both Case1 and Case2: Before sending POST request to `sample_data`, there are 18 non-generated `payment_attempt` records, and 0 `dispute` record. <img width="1384" alt="image" src="https://github.com/user-attachments/assets/a97abf7e-34d4-4bc2-b5e6-fd7ff2908c94"> <img width="1146" alt="image" src="https://github.com/user-attachments/assets/31dddc64-7063-41e3-80d0-c57d378debcf"> #### Case 1: 2 disputes if the number of payments is between 50 and 100. We send a POST request without payload to `sample_data`, by default, 100 `payment_attempt` records will be generated, along with 2 `dispute`. Now there are 118 generated `pyament_attempt` records, and 2 `dispute` records with `test_` prefixed `dispute_id`. <img width="1107" alt="image" src="https://github.com/user-attachments/assets/df612a03-dc3d-4af2-9588-a5b4381f7c09"> <img width="1384" alt="image" src="https://github.com/user-attachments/assets/16d5f449-4f92-417f-991e-8ddb4e9f2548"> #### Case 2: 1 dispute if the number of payments is less than 50. We send a POST request with payload `{ "record": 30 }` to `sample_data`, 30 `payment_attempt` records will be generated, along with 1 `dispute`. Now there are 48 generated `pyament_attempt` records, and 1 `dispute` records with `test_` prefixed `dispute_id`. <img width="1364" alt="image" src="https://github.com/user-attachments/assets/5e9f1712-3be2-4b88-acac-08ac866e64df"> <img width="1385" alt="image" src="https://github.com/user-attachments/assets/a2efec0a-cbec-4154-8d86-98aa5aecb3de"> #### Case Delete: When there exists data generated by `sample_api`, sending a `DELETE` request to `sample_api` deletes all the generated sample data (back to initial state in this example). <img width="1076" alt="image" src="https://github.com/user-attachments/assets/42414fe0-11d0-40ae-987d-7d0c8fd19d4b"> <img width="1057" alt="image" src="https://github.com/user-attachments/assets/4fe4cbba-21de-4b69-82f6-5049e61f69a6">
[ "crates/router/src/core/user/sample_data.rs", "crates/router/src/utils/user/sample_data.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6271
Bug: [BUG] Do not use backticks in shell files ### Bug Description These scripts: - [`INSTALL_dependencies.sh`](https://github.com/juspay/hyperswitch/tree/535f2f12f825be384a17fba8628d8517027bb6c6/INSTALL_dependencies.sh), - [`hyperswitch_aws_setup.sh`](https://github.com/juspay/hyperswitch/tree/535f2f12f825be384a17fba8628d8517027bb6c6/aws/hyperswitch_aws_setup.sh), - [`hyperswitch_cleanup_setup.sh`](https://github.com/juspay/hyperswitch/tree/535f2f12f825be384a17fba8628d8517027bb6c6/aws/hyperswitch_cleanup_setup.sh), - [`add_connector.sh`](https://github.com/juspay/hyperswitch/tree/535f2f12f825be384a17fba8628d8517027bb6c6/scripts/add_connector.sh), use the _deprecated_ backticks notation (cf. [SC2006](https://www.shellcheck.net/wiki/SC2006)). ### Expected Behavior These scripts should follow the recommended guidelines. ### Actual Behavior Use legacy notation, which might cause some maintenance issues. ### Steps To Reproduce Not relevant. ### Context For The Bug _No response_ ### Environment Not relevant. ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/INSTALL_dependencies.sh b/INSTALL_dependencies.sh index 3ec36ccc66e..e1d666b97a3 100755 --- a/INSTALL_dependencies.sh +++ b/INSTALL_dependencies.sh @@ -37,7 +37,7 @@ set -o nounset # utilities # convert semver to comparable integer -if [[ `id -u` -ne 0 ]]; then +if [[ "$(id -u)" -ne 0 ]]; then print_info "requires sudo" SUDO=sudo else @@ -45,10 +45,10 @@ else fi ver () { - printf "%03d%03d%03d%03d" `echo "$1" | tr '.' ' '`; + printf "%03d%03d%03d%03d" "$(echo "$1" | tr '.' ' ')"; } -PROGNAME=`basename $0` +PROGNAME="$(basename $0)" print_info () { echo -e "$PROGNAME: $*" } @@ -125,10 +125,10 @@ if command -v cargo > /dev/null; then need_cmd rustc - RUST_VERSION=`rustc -V | cut -d " " -f 2` + RUST_VERSION="$(rustc -V | cut -d " " -f 2)" - _HAVE_VERSION=`ver ${RUST_VERSION}` - _NEED_VERSION=`ver ${RUST_MSRV}` + _HAVE_VERSION="$(ver ${RUST_VERSION})" + _NEED_VERSION="$(ver ${RUST_MSRV})" print_info "Found rust version \"${RUST_VERSION}\". MSRV is \"${RUST_MSRV}\"" @@ -166,7 +166,7 @@ install_dep () { $INSTALL_CMD $* } -if [[ ! -x "`command -v psql`" ]] || [[ ! -x "`command -v redis-server`" ]] ; then +if [[ ! -x "$(command -v psql)" ]] || [[ ! -x "$(command -v redis-server)" ]] ; then print_info "Missing dependencies. Trying to install" # java has an apt which seems to mess up when we look for apt diff --git a/aws/hyperswitch_aws_setup.sh b/aws/hyperswitch_aws_setup.sh index dd71b698e93..e3af286a58d 100644 --- a/aws/hyperswitch_aws_setup.sh +++ b/aws/hyperswitch_aws_setup.sh @@ -38,12 +38,11 @@ echo "Creating Security Group for Application..." export EC2_SG="application-sg" -echo `(aws ec2 create-security-group \ +echo "$(aws ec2 create-security-group \ --region $REGION \ --group-name $EC2_SG \ --description "Security Group for Hyperswitch EC2 instance" \ ---tag-specifications "ResourceType=security-group,Tags=[{Key=ManagedBy,Value=hyperswitch}]" \ -)` +--tag-specifications "ResourceType=security-group,Tags=[{Key=ManagedBy,Value=hyperswitch}]")" export APP_SG_ID=$(aws ec2 describe-security-groups --group-names $EC2_SG --region $REGION --output text --query 'SecurityGroups[0].GroupId') @@ -51,24 +50,23 @@ echo "Security Group for Application CREATED.\n" echo "Creating Security Group ingress for port 80..." -echo `aws ec2 authorize-security-group-ingress \ +echo "$(aws ec2 authorize-security-group-ingress \ --group-id $APP_SG_ID \ --protocol tcp \ --port 80 \ --cidr 0.0.0.0/0 \ ---region $REGION` +--region $REGION)" echo "Security Group ingress for port 80 CREATED.\n" - echo "Creating Security Group ingress for port 22..." -echo `aws ec2 authorize-security-group-ingress \ +echo "$(aws ec2 authorize-security-group-ingress \ --group-id $APP_SG_ID \ --protocol tcp \ --port 22 \ --cidr 0.0.0.0/0 \ ---region $REGION` +--region $REGION)" echo "Security Group ingress for port 22 CREATED.\n" @@ -78,11 +76,11 @@ echo "Security Group ingress for port 22 CREATED.\n" echo "Creating Security Group for Elasticache..." export REDIS_GROUP_NAME=redis-sg -echo `aws ec2 create-security-group \ +echo "$(aws ec2 create-security-group \ --group-name $REDIS_GROUP_NAME \ --description "SG attached to elasticache" \ --tag-specifications "ResourceType=security-group,Tags=[{Key=ManagedBy,Value=hyperswitch}]" \ ---region $REGION` +--region $REGION)" echo "Security Group for Elasticache CREATED.\n" @@ -91,12 +89,12 @@ echo "Creating Inbound rules for Redis..." export REDIS_SG_ID=$(aws ec2 describe-security-groups --group-names $REDIS_GROUP_NAME --region $REGION --output text --query 'SecurityGroups[0].GroupId') # CREATE INBOUND RULES -echo `aws ec2 authorize-security-group-ingress \ +echo "$(aws ec2 authorize-security-group-ingress \ --group-id $REDIS_SG_ID \ --protocol tcp \ --port 6379 \ --source-group $EC2_SG \ ---region $REGION` +--region $REGION)" echo "Inbound rules for Redis CREATED.\n" @@ -105,11 +103,11 @@ echo "Inbound rules for Redis CREATED.\n" echo "Creating Security Group for RDS..." export RDS_GROUP_NAME=rds-sg -echo `aws ec2 create-security-group \ +echo "$(aws ec2 create-security-group \ --group-name $RDS_GROUP_NAME \ --description "SG attached to RDS" \ --tag-specifications "ResourceType=security-group,Tags=[{Key=ManagedBy,Value=hyperswitch}]" \ ---region $REGION` +--region $REGION)" echo "Security Group for RDS CREATED.\n" @@ -118,21 +116,21 @@ echo "Creating Inbound rules for RDS..." export RDS_SG_ID=$(aws ec2 describe-security-groups --group-names $RDS_GROUP_NAME --region $REGION --output text --query 'SecurityGroups[0].GroupId') # CREATE INBOUND RULES -echo `aws ec2 authorize-security-group-ingress \ +echo "$(aws ec2 authorize-security-group-ingress \ --group-id $RDS_SG_ID \ --protocol tcp \ --port 5432 \ --source-group $EC2_SG \ ---region $REGION` +--region $REGION)" echo "Inbound rules for RDS CREATED.\n" -echo `aws ec2 authorize-security-group-ingress \ +echo "$(aws ec2 authorize-security-group-ingress \ --group-id $RDS_SG_ID \ --protocol tcp \ --port 5432 \ --cidr 0.0.0.0/0 \ - --region $REGION` + --region $REGION)" echo "Inbound rules for RDS (from any IP) CREATED.\n" @@ -140,7 +138,7 @@ echo "Creating Elasticache with Redis engine..." export CACHE_CLUSTER_ID=hyperswitch-cluster -echo `aws elasticache create-cache-cluster \ +echo "$(aws elasticache create-cache-cluster \ --cache-cluster-id $CACHE_CLUSTER_ID \ --cache-node-type cache.t3.medium \ --engine redis \ @@ -148,14 +146,14 @@ echo `aws elasticache create-cache-cluster \ --security-group-ids $REDIS_SG_ID \ --engine-version 7.0 \ --tags "Key=ManagedBy,Value=hyperswitch" \ ---region $REGION` +--region $REGION)" echo "Elasticache with Redis engine CREATED.\n" echo "Creating RDS with PSQL..." export DB_INSTANCE_ID=hyperswitch-db -echo `aws rds create-db-instance \ +echo "$(aws rds create-db-instance \ --db-instance-identifier $DB_INSTANCE_ID\ --db-instance-class db.t3.micro \ --engine postgres \ @@ -166,7 +164,7 @@ echo `aws rds create-db-instance \ --region $REGION \ --db-name hyperswitch_db \ --tags "Key=ManagedBy,Value=hyperswitch" \ - --vpc-security-group-ids $RDS_SG_ID` + --vpc-security-group-ids $RDS_SG_ID)" echo "RDS with PSQL CREATED.\n" @@ -308,17 +306,17 @@ echo "EC2 instance launched.\n" echo "Add Tags to EC2 instance..." -echo `aws ec2 create-tags \ +echo "$(aws ec2 create-tags \ --resources $HYPERSWITCH_INSTANCE_ID \ --tags "Key=Name,Value=hyperswitch-router" \ ---region $REGION` +--region $REGION)" echo "Tag added to EC2 instance.\n" -echo `aws ec2 create-tags \ +echo "$(aws ec2 create-tags \ --resources $HYPERSWITCH_INSTANCE_ID \ --tags "Key=ManagedBy,Value=hyperswitch" \ ---region $REGION` +--region $REGION)" echo "ManagedBy tag added to EC2 instance.\n" diff --git a/aws/hyperswitch_cleanup_setup.sh b/aws/hyperswitch_cleanup_setup.sh index 383f23d5bd0..df75623746c 100644 --- a/aws/hyperswitch_cleanup_setup.sh +++ b/aws/hyperswitch_cleanup_setup.sh @@ -45,7 +45,7 @@ for cluster_arn in $ALL_ELASTIC_CACHE; do if [[ $? -eq 0 ]]; then echo -n "Delete $cluster_id (Y/n)? " if yes_or_no; then - echo `aws elasticache delete-cache-cluster --region $REGION --cache-cluster-id $cluster_id` + echo "$(aws elasticache delete-cache-cluster --region $REGION --cache-cluster-id $cluster_id)" fi fi done @@ -59,7 +59,7 @@ echo -n "Deleting ( $ALL_KEY_PAIRS ) key pairs? (Y/n)?" if yes_or_no; then for KEY_ID in $ALL_KEY_PAIRS; do - echo `aws ec2 delete-key-pair --key-pair-id $KEY_ID --region $REGION` + echo "$(aws ec2 delete-key-pair --key-pair-id $KEY_ID --region $REGION)" done fi @@ -78,7 +78,7 @@ echo -n "Terminating ( $ALL_INSTANCES ) instances? (Y/n)?" if yes_or_no; then for INSTANCE_ID in $ALL_INSTANCES; do - echo `aws ec2 terminate-instances --instance-ids $INSTANCE_ID --region $REGION` + echo "$(aws ec2 terminate-instances --instance-ids $INSTANCE_ID --region $REGION)" done fi @@ -105,15 +105,15 @@ for resource_id in $ALL_DB_RESOURCES; do echo -n "Create a snapshot before deleting ( $DB_INSTANCE_ID ) the database (Y/n)? " if yes_or_no; then - echo `aws rds delete-db-instance \ + echo "$(aws rds delete-db-instance \ --db-instance-identifier $DB_INSTANCE_ID \ --region $REGION \ - --final-db-snapshot-identifier hyperswitch-db-snapshot-`date +%s`` + --final-db-snapshot-identifier hyperswitch-db-snapshot-$(date +%s))" else - echo `aws rds delete-db-instance \ + echo "$(aws rds delete-db-instance \ --region $REGION \ --db-instance-identifier $DB_INSTANCE_ID \ - --skip-final-snapshot` + --skip-final-snapshot)" fi fi fi diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 2e12d829050..f90a8cbd3f5 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -8,7 +8,7 @@ function find_prev_connector() { # Add new connector to existing list and sort it connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets nexixpay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS - res=`echo ${sorted[@]}` + res="$(echo ${sorted[@]})" sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp for i in "${!sorted[@]}"; do if [ "${sorted[$i]}" = "$1" ] && [ $i != "0" ]; then
2024-10-16T08:15:36Z
## Description <!-- Describe your changes in detail --> Use $(...) notation instead of legacy `...` in the shell files. Removes the use of deprecated backticks notation (cf. [SC2006](https://www.shellcheck.net/wiki/SC2006)). ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes https://github.com/juspay/hyperswitch/issues/6271
899ec23565f99daaad821c1ec1482b4c0cc408c5
[ "INSTALL_dependencies.sh", "aws/hyperswitch_aws_setup.sh", "aws/hyperswitch_cleanup_setup.sh", "scripts/add_connector.sh" ]
juspay/hyperswitch
juspay__hyperswitch-5942
Bug: [REFACTOR]: [CYBERSOURCE] Add amount conversion framework to Cybersource ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://developer.cybersource.com/docs/cybs/en-us/api-fields/reference/all/so/api-fields/original-transaction-amount.html) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :package: Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 2a271acb62b..433a3139d52 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -603,7 +603,6 @@ impl StringMajorUnit { pub fn zero() -> Self { Self("0".to_string()) } - /// Get string amount from struct to be removed in future pub fn get_amount_as_string(&self) -> String { self.0.clone() diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 806cf67b2da..06f448e075a 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -1,9 +1,10 @@ pub mod transformers; -use std::fmt::Debug; - use base64::Engine; -use common_utils::request::RequestContent; +use common_utils::{ + request::RequestContent, + types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector}, +}; use diesel_models::enums; use error_stack::{report, Report, ResultExt}; use masking::{ExposeInterface, PeekInterface}; @@ -12,7 +13,7 @@ use time::OffsetDateTime; use transformers as cybersource; use url::Url; -use super::utils::{PaymentsAuthorizeRequestData, RouterData}; +use super::utils::{convert_amount, PaymentsAuthorizeRequestData, RouterData}; use crate::{ configs::settings, connector::{ @@ -36,9 +37,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Cybersource; +#[derive(Clone)] +pub struct Cybersource { + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} +impl Cybersource { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMajorUnitForConnector, + } + } +} impl Cybersource { pub fn generate_digest(&self, payload: &[u8]) -> String { let payload_digest = digest::digest(&digest::SHA256, payload); @@ -617,20 +627,20 @@ impl req: &types::PaymentsPreProcessingRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let minor_amount = req.request - .currency + .minor_amount .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "currency", - })?, + field_name: "minor_amount", + })?; + let currency = req.request - .amount + .currency .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "amount", - })?, - req, - ))?; + field_name: "currency", + })?; + let amount = convert_amount(self.amount_converter, minor_amount, currency)?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); let connector_req = cybersource::CybersourcePreProcessingRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -718,12 +728,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, req.request.currency, - req.request.amount_to_capture, - req, - ))?; + )?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); let connector_req = cybersource::CybersourcePaymentsCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -922,12 +932,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); if req.is_three_ds() && req.request.is_card() && (req.request.connector_mandate_id().is_none() @@ -1068,12 +1078,12 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp req: &types::PayoutsRouterData<api::PoFulfill>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.destination_currency, - req.request.amount, - req, - ))?; + )?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); let connector_req = cybersource::CybersourcePayoutFulfillRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -1193,12 +1203,12 @@ impl req: &types::PaymentsCompleteAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); let connector_req = cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -1317,20 +1327,21 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR req: &types::PaymentsCancelRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let minor_amount = req.request - .currency + .minor_amount .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "Currency", - })?, + field_name: "Amount", + })?; + let currency = req.request - .amount + .currency .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "Amount", - })?, - req, - ))?; + field_name: "Currency", + })?; + let amount = convert_amount(self.amount_converter, minor_amount, currency)?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); + let connector_req = cybersource::CybersourceVoidRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -1443,12 +1454,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundExecuteRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let refund_amount = convert_amount( + self.amount_converter, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; + )?; + let connector_router_data = cybersource::CybersourceRouterData::from((refund_amount, req)); let connector_req = cybersource::CybersourceRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -1609,12 +1620,14 @@ impl req: &types::PaymentsIncrementalAuthorizationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let minor_additional_amount = MinorUnit::new(req.request.additional_amount); + let additional_amount = convert_amount( + self.amount_converter, + minor_additional_amount, req.request.currency, - req.request.additional_amount, - req, - ))?; + )?; + let connector_router_data = + cybersource::CybersourceRouterData::from((additional_amount, req)); let connector_request = cybersource::CybersourcePaymentsIncrementalAuthorizationRequest::try_from( &connector_router_data, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 2ea36e3e35e..2174eb3bc50 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -9,7 +9,7 @@ use common_enums::FutureUsage; use common_utils::{ ext_traits::{OptionExt, ValueExt}, pii, - types::SemanticVersion, + types::{SemanticVersion, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -41,21 +41,16 @@ use crate::{ #[derive(Debug, Serialize)] pub struct CybersourceRouterData<T> { - pub amount: String, + pub amount: StringMajorUnit, pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for CybersourceRouterData<T> { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), - ) -> Result<Self, Self::Error> { - // This conversion function is used at different places in the file, if updating this, keep a check for those - let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; - Ok(Self { +impl<T> From<(StringMajorUnit, T)> for CybersourceRouterData<T> { + fn from((amount, router_data): (StringMajorUnit, T)) -> Self { + Self { amount, - router_data: item, - }) + router_data, + } } } @@ -93,7 +88,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { let order_information = OrderInformationWithBill { amount_details: Amount { - total_amount: "0".to_string(), + total_amount: StringMajorUnit::zero(), currency: item.request.currency, }, bill_to: Some(bill_to), @@ -526,14 +521,14 @@ pub struct OrderInformation { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Amount { - total_amount: String, + total_amount: StringMajorUnit, currency: api_models::enums::Currency, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdditionalAmount { - additional_amount: String, + additional_amount: StringMajorUnit, currency: String, } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index f5fa2d9a37e..975b219a26c 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -367,7 +367,7 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Cryptopay::new()))) } enums::Connector::Cybersource => { - Ok(ConnectorEnum::Old(Box::new(&connector::Cybersource))) + Ok(ConnectorEnum::Old(Box::new(connector::Cybersource::new()))) } enums::Connector::Datatrans => { Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new()))) diff --git a/crates/router/tests/connectors/cybersource.rs b/crates/router/tests/connectors/cybersource.rs index 0116b52f4ed..1accece7fa6 100644 --- a/crates/router/tests/connectors/cybersource.rs +++ b/crates/router/tests/connectors/cybersource.rs @@ -14,7 +14,7 @@ impl utils::Connector for Cybersource { fn get_data(&self) -> api::ConnectorData { use router::connector::Cybersource; utils::construct_connector_data_old( - Box::new(&Cybersource), + Box::new(Cybersource::new()), types::Connector::Cybersource, api::GetToken::Connector, None,
2024-10-16T07:06:40Z
## Description <!-- Describe your changes in detail --> added StringMajorUnit for amount conversion ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> fixes #5942 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested through postman: - Create a MCA for cybersource: - Create a Payment with Cybersource: ``` { "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "test_rec7", "email": "guest@example.com", "request_external_three_ds_authentication": true, "customer_acceptance": { "acceptance_type": "online" }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "Test Holder", "card_cvc": "737" } }, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "authentication_type": "no_three_ds" } ``` - The payment should be succeeded ``` { "payment_id": "pay_LGt7Tbil8tLko2OpVHqJ", "merchant_id": "merchant_1730121122", "status": "succeeded", "amount": 499, "net_amount": 499, "shipping_cost": null, "amount_capturable": 0, "amount_received": 499, "connector": "cybersource", "client_secret": "pay_LGt7Tbil8tLko2OpVHqJ_secret_dycae051HVaAJYXSCdCH", "created": "2024-10-28T13:12:22.609Z", "currency": "USD", "customer_id": "test_rec7", "customer": { "id": "test_rec7", "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": "Visa", "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" } }, "authentication_data": null }, "billing": null }, "payment_token": "token_LyziBYSQnkubuQbE91YF", "shipping": null, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "order_details": null, "email": "guest@example.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "test_rec7", "created_at": 1730121142, "expires": 1730124742, "secret": "epk_bb3a50134caa4214ad2ea7b534184d26" }, "manual_retry_allowed": false, "connector_transaction_id": "7301211437366791304951", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_LGt7Tbil8tLko2OpVHqJ_1", "payment_link": null, "profile_id": "pro_2pDEf41cwojHtrM9xItk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_AFVVYXejTDoWa4IgaPnw", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-28T13:27:22.609Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-28T13:12:24.692Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` - Check cybersource dashboard with respective connector_transaction_id to get the transaction data - the amount in dashboard should match with the amount passed in request. ![image](https://github.com/user-attachments/assets/c9644519-1638-4a09-a6b0-3c56c1adabd0)
55fe82fdcd78df9608842190f1423088740d1087
Tested through postman: - Create a MCA for cybersource: - Create a Payment with Cybersource: ``` { "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "test_rec7", "email": "guest@example.com", "request_external_three_ds_authentication": true, "customer_acceptance": { "acceptance_type": "online" }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "Test Holder", "card_cvc": "737" } }, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "authentication_type": "no_three_ds" } ``` - The payment should be succeeded ``` { "payment_id": "pay_LGt7Tbil8tLko2OpVHqJ", "merchant_id": "merchant_1730121122", "status": "succeeded", "amount": 499, "net_amount": 499, "shipping_cost": null, "amount_capturable": 0, "amount_received": 499, "connector": "cybersource", "client_secret": "pay_LGt7Tbil8tLko2OpVHqJ_secret_dycae051HVaAJYXSCdCH", "created": "2024-10-28T13:12:22.609Z", "currency": "USD", "customer_id": "test_rec7", "customer": { "id": "test_rec7", "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": "Visa", "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" } }, "authentication_data": null }, "billing": null }, "payment_token": "token_LyziBYSQnkubuQbE91YF", "shipping": null, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "order_details": null, "email": "guest@example.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "test_rec7", "created_at": 1730121142, "expires": 1730124742, "secret": "epk_bb3a50134caa4214ad2ea7b534184d26" }, "manual_retry_allowed": false, "connector_transaction_id": "7301211437366791304951", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_LGt7Tbil8tLko2OpVHqJ_1", "payment_link": null, "profile_id": "pro_2pDEf41cwojHtrM9xItk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_AFVVYXejTDoWa4IgaPnw", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-28T13:27:22.609Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-28T13:12:24.692Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` - Check cybersource dashboard with respective connector_transaction_id to get the transaction data - the amount in dashboard should match with the amount passed in request. ![image](https://github.com/user-attachments/assets/c9644519-1638-4a09-a6b0-3c56c1adabd0)
[ "crates/common_utils/src/types.rs", "crates/router/src/connector/cybersource.rs", "crates/router/src/connector/cybersource/transformers.rs", "crates/router/src/types/api.rs", "crates/router/tests/connectors/cybersource.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6338
Bug: Integration of dynamic connector selection in core flows ## Description This will integrate the dynamic_connector_selection in core flows, enabling the success_based connector selection for payments (with the profiles, enabled with dynamic_connector_selection feature).
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index fc65ab037c2..47d75b2e835 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -522,22 +522,51 @@ pub struct DynamicAlgorithmWithTimestamp<T> { #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicRoutingAlgorithmRef { - pub success_based_algorithm: - Option<DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>>, + pub success_based_algorithm: Option<SuccessBasedAlgorithm>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct SuccessBasedAlgorithm { + pub algorithm_id_with_timestamp: + DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, + #[serde(default)] + pub enabled_feature: SuccessBasedRoutingFeatures, +} + +impl SuccessBasedAlgorithm { + pub fn update_enabled_features(&mut self, feature_to_enable: SuccessBasedRoutingFeatures) { + self.enabled_feature = feature_to_enable + } } impl DynamicRoutingAlgorithmRef { - pub fn update_algorithm_id(&mut self, new_id: common_utils::id_type::RoutingId) { - self.success_based_algorithm = Some(DynamicAlgorithmWithTimestamp { - algorithm_id: Some(new_id), - timestamp: common_utils::date_time::now_unix_timestamp(), + pub fn update_algorithm_id( + &mut self, + new_id: common_utils::id_type::RoutingId, + enabled_feature: SuccessBasedRoutingFeatures, + ) { + self.success_based_algorithm = Some(SuccessBasedAlgorithm { + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp { + algorithm_id: Some(new_id), + timestamp: common_utils::date_time::now_unix_timestamp(), + }, + enabled_feature, }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleSuccessBasedRoutingQuery { - pub status: bool, + pub enable: SuccessBasedRoutingFeatures, +} + +#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum SuccessBasedRoutingFeatures { + Metrics, + DynamicConnectorSelection, + #[default] + None, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] @@ -551,7 +580,7 @@ pub struct SuccessBasedRoutingUpdateConfigQuery { #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ToggleSuccessBasedRoutingWrapper { pub profile_id: common_utils::id_type::ProfileId, - pub status: bool, + pub feature_to_enable: SuccessBasedRoutingFeatures, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index a76726eb8ac..b459cee7ad4 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -159,7 +159,6 @@ Never share your secret api keys. Keep them guarded and secure. routes::routing::routing_retrieve_default_config_for_profiles, routes::routing::routing_update_default_config_for_profile, routes::routing::toggle_success_based_routing, - routes::routing::success_based_routing_update_configs, // Routes for blocklist routes::blocklist::remove_entry_from_blocklist, @@ -559,6 +558,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::routing::RoutingDictionaryRecord, api_models::routing::RoutingKind, api_models::routing::RoutableConnectorChoice, + api_models::routing::SuccessBasedRoutingFeatures, api_models::routing::LinkedRoutingConfigRetrieveResponse, api_models::routing::RoutingRetrieveResponse, api_models::routing::ProfileDefaultRoutingConfig, @@ -570,11 +570,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::routing::ConnectorVolumeSplit, api_models::routing::ConnectorSelection, api_models::routing::ToggleSuccessBasedRoutingQuery, - api_models::routing::SuccessBasedRoutingConfig, - api_models::routing::SuccessBasedRoutingConfigParams, - api_models::routing::SuccessBasedRoutingConfigBody, - api_models::routing::CurrentBlockThreshold, - api_models::routing::SuccessBasedRoutingUpdateConfigQuery, api_models::routing::ToggleSuccessBasedRoutingPath, api_models::routing::ast::RoutableChoiceKind, api_models::enums::RoutableConnectors, diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs index 009708d860d..0bb79a2bbe4 100644 --- a/crates/openapi/src/routes/routing.rs +++ b/crates/openapi/src/routes/routing.rs @@ -266,7 +266,7 @@ pub async fn routing_update_default_config_for_profile() {} params( ("account_id" = String, Path, description = "Merchant id"), ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"), - ("status" = bool, Query, description = "Boolean value for mentioning the expected state of dynamic routing"), + ("enable" = SuccessBasedRoutingFeatures, Query, description = "Feature to enable for success based routing"), ), responses( (status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord), @@ -281,30 +281,3 @@ pub async fn routing_update_default_config_for_profile() {} security(("api_key" = []), ("jwt_key" = [])) )] pub async fn toggle_success_based_routing() {} - -#[cfg(feature = "v1")] -/// Routing - Update config for success based dynamic routing -/// -/// Update config for success based dynamic routing -#[utoipa::path( - patch, - path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/success_based/config/:algorithm_id", - request_body = SuccessBasedRoutingConfig, - params( - ("account_id" = String, Path, description = "Merchant id"), - ("profile_id" = String, Path, description = "The unique identifier for a profile"), - ("algorithm_id" = String, Path, description = "The unique identifier for routing algorithm"), - ), - responses( - (status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord), - (status = 400, description = "Request body is malformed"), - (status = 500, description = "Internal server error"), - (status = 404, description = "Resource missing"), - (status = 422, description = "Unprocessable request"), - (status = 403, description = "Forbidden"), - ), - tag = "Routing", - operation_id = "Update configs for success based dynamic routing algorithm", - security(("admin_api_key" = [])) -)] -pub async fn success_based_routing_update_configs() {} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index c56bfaca913..18af1b064cd 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -318,6 +318,20 @@ pub enum RoutingError { VolumeSplitFailed, #[error("Unable to parse metadata")] MetadataParsingError, + #[error("Unable to retrieve success based routing config")] + SuccessBasedRoutingConfigError, + #[error("Unable to calculate success based routing config from dynamic routing service")] + SuccessRateCalculationError, + #[error("Success rate client from dynamic routing gRPC service not initialized")] + SuccessRateClientInitializationError, + #[error("Unable to convert from '{from}' to '{to}'")] + GenericConversionError { from: String, to: String }, + #[error("Invalid success based connector label received from dynamic routing service: '{0}'")] + InvalidSuccessBasedConnectorLabel(String), + #[error("unable to find '{field}'")] + GenericNotFoundError { field: String }, + #[error("Unable to deserialize from '{from}' to '{to}'")] + DeserializationError { from: String, to: String }, } #[derive(Debug, Clone, thiserror::Error)] diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 9f904116171..568fcb20902 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4591,6 +4591,19 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; + // dynamic success based connector selection + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] + let connectors = { + if business_profile.dynamic_routing_algorithm.is_some() { + routing::perform_success_based_routing(state, connectors.clone(), business_profile) + .await + .map_err(|e| logger::error!(success_rate_routing_error=?e)) + .unwrap_or(connectors) + } else { + connectors + } + }; + let connector_data = connectors .into_iter() .map(|conn| { diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 6a5299db8c4..8a6fad6a60a 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1713,8 +1713,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( #[cfg(all(feature = "v1", feature = "dynamic_routing"))] { - if let Some(dynamic_routing_algorithm) = business_profile.dynamic_routing_algorithm.clone() - { + if business_profile.dynamic_routing_algorithm.is_some() { let state = state.clone(); let business_profile = business_profile.clone(); let payment_attempt = payment_attempt.clone(); @@ -1725,7 +1724,6 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( &payment_attempt, routable_connectors, &business_profile, - dynamic_routing_algorithm, ) .await .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e)) diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 04080a42730..dbb08e770a1 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -7,6 +7,8 @@ use std::{ sync::Arc, }; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use api_models::routing as api_routing; use api_models::{ admin as admin_api, enums::{self as api_enums, CountryAlpha2}, @@ -21,6 +23,10 @@ use euclid::{ enums as euclid_enums, frontend::{ast, dir as euclid_dir}, }; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use external_services::grpc_client::dynamic_routing::{ + success_rate::CalSuccessRateResponse, SuccessBasedDynamicRouting, +}; use kgraph_utils::{ mca as mca_graph, transformers::{IntoContext, IntoDirValue}, @@ -1202,3 +1208,114 @@ pub fn make_dsl_input_for_surcharge( }; Ok(backend_input) } + +/// success based dynamic routing +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub async fn perform_success_based_routing( + state: &SessionState, + routable_connectors: Vec<api_routing::RoutableConnectorChoice>, + business_profile: &domain::Profile, +) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { + let success_based_dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = + business_profile + .dynamic_routing_algorithm + .clone() + .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) + .transpose() + .change_context(errors::RoutingError::DeserializationError { + from: "JSON".to_string(), + to: "DynamicRoutingAlgorithmRef".to_string(), + }) + .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")? + .unwrap_or_default(); + + let success_based_algo_ref = success_based_dynamic_routing_algo_ref + .success_based_algorithm + .ok_or(errors::RoutingError::GenericNotFoundError { field: "success_based_algorithm".to_string() }) + .attach_printable( + "success_based_algorithm not found in dynamic_routing_algorithm from business_profile table", + )?; + + if success_based_algo_ref.enabled_feature + == api_routing::SuccessBasedRoutingFeatures::DynamicConnectorSelection + { + logger::debug!( + "performing success_based_routing for profile {}", + business_profile.get_id().get_string_repr() + ); + let client = state + .grpc_client + .dynamic_routing + .success_rate_client + .as_ref() + .ok_or(errors::RoutingError::SuccessRateClientInitializationError) + .attach_printable("success_rate gRPC client not found")?; + + let success_based_routing_configs = routing::helpers::fetch_success_based_routing_configs( + state, + business_profile, + success_based_algo_ref + .algorithm_id_with_timestamp + .algorithm_id + .ok_or(errors::RoutingError::GenericNotFoundError { + field: "success_based_routing_algorithm_id".to_string(), + }) + .attach_printable( + "success_based_routing_algorithm_id not found in business_profile", + )?, + ) + .await + .change_context(errors::RoutingError::SuccessBasedRoutingConfigError) + .attach_printable("unable to fetch success_rate based dynamic routing configs")?; + + let tenant_business_profile_id = routing::helpers::generate_tenant_business_profile_id( + &state.tenant.redis_key_prefix, + business_profile.get_id().get_string_repr(), + ); + + let success_based_connectors: CalSuccessRateResponse = client + .calculate_success_rate( + tenant_business_profile_id, + success_based_routing_configs, + routable_connectors, + ) + .await + .change_context(errors::RoutingError::SuccessRateCalculationError) + .attach_printable( + "unable to calculate/fetch success rate from dynamic routing service", + )?; + + let mut connectors = Vec::with_capacity(success_based_connectors.labels_with_score.len()); + for label_with_score in success_based_connectors.labels_with_score { + let (connector, merchant_connector_id) = label_with_score.label + .split_once(':') + .ok_or(errors::RoutingError::InvalidSuccessBasedConnectorLabel(label_with_score.label.to_string())) + .attach_printable( + "unable to split connector_name and mca_id from the label obtained by the dynamic routing service", + )?; + connectors.push(api_routing::RoutableConnectorChoice { + choice_kind: api_routing::RoutableChoiceKind::FullStruct, + connector: common_enums::RoutableConnectors::from_str(connector) + .change_context(errors::RoutingError::GenericConversionError { + from: "String".to_string(), + to: "RoutableConnectors".to_string(), + }) + .attach_printable("unable to convert String to RoutableConnectors")?, + merchant_connector_id: Some( + common_utils::id_type::MerchantConnectorAccountId::wrap( + merchant_connector_id.to_string(), + ) + .change_context(errors::RoutingError::GenericConversionError { + from: "String".to_string(), + to: "MerchantConnectorAccountId".to_string(), + }) + .attach_printable("unable to convert MerchantConnectorAccountId from string")?, + ), + }); + } + logger::debug!(success_based_routing_connectors=?connectors); + Ok(connectors) + } else { + Ok(routable_connectors) + } +} diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index b7b1c13ea80..35c4b8d9621 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -434,9 +434,13 @@ pub async fn link_routing_config( utils::when( matches!( dynamic_routing_ref.success_based_algorithm, - Some(routing_types::DynamicAlgorithmWithTimestamp { - algorithm_id: Some(ref id), - timestamp: _ + Some(routing::SuccessBasedAlgorithm { + algorithm_id_with_timestamp: + routing_types::DynamicAlgorithmWithTimestamp { + algorithm_id: Some(ref id), + timestamp: _ + }, + enabled_feature: _ }) if id == &algorithm_id ), || { @@ -446,7 +450,17 @@ pub async fn link_routing_config( }, )?; - dynamic_routing_ref.update_algorithm_id(algorithm_id); + dynamic_routing_ref.update_algorithm_id( + algorithm_id, + dynamic_routing_ref + .success_based_algorithm + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "missing success_based_algorithm in dynamic_algorithm_ref from business_profile table", + )? + .enabled_feature, + ); helpers::update_business_profile_active_dynamic_algorithm_ref( db, key_manager_state, @@ -1162,7 +1176,7 @@ pub async fn toggle_success_based_routing( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, - status: bool, + feature_to_enable: routing::SuccessBasedRoutingFeatures, profile_id: common_utils::id_type::ProfileId, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add( @@ -1198,115 +1212,158 @@ pub async fn toggle_success_based_routing( )? .unwrap_or_default(); - if status { - let default_success_based_routing_config = routing::SuccessBasedRoutingConfig::default(); - let algorithm_id = common_utils::generate_routing_id_of_default_length(); - let timestamp = common_utils::date_time::now(); - let algo = RoutingAlgorithm { - algorithm_id: algorithm_id.clone(), - profile_id: business_profile.get_id().to_owned(), - merchant_id: merchant_account.get_id().to_owned(), - name: "Dynamic routing algorithm".to_string(), - description: None, - kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic, - algorithm_data: serde_json::json!(default_success_based_routing_config), - created_at: timestamp, - modified_at: timestamp, - algorithm_for: common_enums::TransactionType::Payment, - }; - - let record = db - .insert_routing_algorithm(algo) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to insert record in routing algorithm table")?; - - success_based_dynamic_routing_algo_ref.update_algorithm_id(algorithm_id); - helpers::update_business_profile_active_dynamic_algorithm_ref( - db, - key_manager_state, - &key_store, - business_profile, - success_based_dynamic_routing_algo_ref, - ) - .await?; - - let new_record = record.foreign_into(); - - metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add( - &metrics::CONTEXT, - 1, - &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]), - ); - Ok(service_api::ApplicationResponse::Json(new_record)) - } else { - let timestamp = common_utils::date_time::now_unix_timestamp(); - match success_based_dynamic_routing_algo_ref.success_based_algorithm { - Some(algorithm_ref) => { - if let Some(algorithm_id) = algorithm_ref.algorithm_id { - let dynamic_routing_algorithm = routing_types::DynamicRoutingAlgorithmRef { - success_based_algorithm: Some( - routing_types::DynamicAlgorithmWithTimestamp { - algorithm_id: None, - timestamp, - }, - ), - }; - - // redact cache for success based routing configs - let cache_key = format!( - "{}_{}", - business_profile.get_id().get_string_repr(), - algorithm_id.get_string_repr() - ); - let cache_entries_to_redact = - vec![cache::CacheKind::SuccessBasedDynamicRoutingCache( - cache_key.into(), - )]; - let _ = cache::publish_into_redact_channel( - state.store.get_cache_store().as_ref(), - cache_entries_to_redact, - ) - .await - .map_err(|e| { - logger::error!( - "unable to publish into the redact channel for evicting the success based routing config cache {e:?}" + match feature_to_enable { + routing::SuccessBasedRoutingFeatures::Metrics + | routing::SuccessBasedRoutingFeatures::DynamicConnectorSelection => { + if let Some(ref mut algo_with_timestamp) = + success_based_dynamic_routing_algo_ref.success_based_algorithm + { + match algo_with_timestamp + .algorithm_id_with_timestamp + .algorithm_id + .clone() + { + Some(algorithm_id) => { + // algorithm is already present in profile + if algo_with_timestamp.enabled_feature == feature_to_enable { + // algorithm already has the required feature + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Success rate based routing is already enabled" + .to_string(), + })? + } else { + // enable the requested feature for the algorithm + algo_with_timestamp.update_enabled_features(feature_to_enable); + let record = db + .find_routing_algorithm_by_profile_id_algorithm_id( + business_profile.get_id(), + &algorithm_id, + ) + .await + .to_not_found_response( + errors::ApiErrorResponse::ResourceIdNotFound, + )?; + let response = record.foreign_into(); + helpers::update_business_profile_active_dynamic_algorithm_ref( + db, + key_manager_state, + &key_store, + business_profile, + success_based_dynamic_routing_algo_ref, + ) + .await?; + + metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add( + &metrics::CONTEXT, + 1, + &add_attributes([( + "profile_id", + profile_id.get_string_repr().to_owned(), + )]), + ); + Ok(service_api::ApplicationResponse::Json(response)) + } + } + None => { + // algorithm isn't present in profile + helpers::default_success_based_routing_setup( + &state, + key_store, + business_profile, + feature_to_enable, + merchant_account.get_id().to_owned(), + success_based_dynamic_routing_algo_ref, ) - }); + .await + } + } + } else { + // algorithm isn't present in profile + helpers::default_success_based_routing_setup( + &state, + key_store, + business_profile, + feature_to_enable, + merchant_account.get_id().to_owned(), + success_based_dynamic_routing_algo_ref, + ) + .await + } + } + routing::SuccessBasedRoutingFeatures::None => { + // disable success based routing for the requested profile + let timestamp = common_utils::date_time::now_unix_timestamp(); + match success_based_dynamic_routing_algo_ref.success_based_algorithm { + Some(algorithm_ref) => { + if let Some(algorithm_id) = + algorithm_ref.algorithm_id_with_timestamp.algorithm_id + { + let dynamic_routing_algorithm = routing_types::DynamicRoutingAlgorithmRef { + success_based_algorithm: Some(routing::SuccessBasedAlgorithm { + algorithm_id_with_timestamp: + routing_types::DynamicAlgorithmWithTimestamp { + algorithm_id: None, + timestamp, + }, + enabled_feature: routing::SuccessBasedRoutingFeatures::None, + }), + }; - let record = db - .find_routing_algorithm_by_profile_id_algorithm_id( - business_profile.get_id(), - &algorithm_id, + // redact cache for success based routing configs + let cache_key = format!( + "{}_{}", + business_profile.get_id().get_string_repr(), + algorithm_id.get_string_repr() + ); + let cache_entries_to_redact = + vec![cache::CacheKind::SuccessBasedDynamicRoutingCache( + cache_key.into(), + )]; + let _ = cache::publish_into_redact_channel( + state.store.get_cache_store().as_ref(), + cache_entries_to_redact, ) .await - .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; - let response = record.foreign_into(); - helpers::update_business_profile_active_dynamic_algorithm_ref( - db, - key_manager_state, - &key_store, - business_profile, - dynamic_routing_algorithm, - ) - .await?; - - metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add( - &metrics::CONTEXT, - 1, - &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]), - ); - - Ok(service_api::ApplicationResponse::Json(response)) - } else { - Err(errors::ApiErrorResponse::PreconditionFailed { - message: "Algorithm is already inactive".to_string(), - })? + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to publish into the redact channel for evicting the success based routing config cache")?; + + let record = db + .find_routing_algorithm_by_profile_id_algorithm_id( + business_profile.get_id(), + &algorithm_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; + let response = record.foreign_into(); + helpers::update_business_profile_active_dynamic_algorithm_ref( + db, + key_manager_state, + &key_store, + business_profile, + dynamic_routing_algorithm, + ) + .await?; + + metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add( + &metrics::CONTEXT, + 1, + &add_attributes([( + "profile_id", + profile_id.get_string_repr().to_owned(), + )]), + ); + + Ok(service_api::ApplicationResponse::Json(response)) + } else { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Algorithm is already inactive".to_string(), + })? + } } + None => Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Success rate based routing is already disabled".to_string(), + })?, } - None => Err(errors::ApiErrorResponse::PreconditionFailed { - message: "Algorithm is already inactive".to_string(), - })?, } } } diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 22966208dd4..6b584583174 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -12,10 +12,16 @@ use api_models::routing as routing_types; use common_utils::ext_traits::ValueExt; use common_utils::{ext_traits::Encode, id_type, types::keymanager::KeyManagerState}; use diesel_models::configs; +#[cfg(feature = "v1")] +use diesel_models::routing_algorithm; use error_stack::ResultExt; -#[cfg(feature = "dynamic_routing")] +#[cfg(all(feature = "dynamic_routing", feature = "v1"))] use external_services::grpc_client::dynamic_routing::SuccessBasedDynamicRouting; +#[cfg(feature = "v1")] +use hyperswitch_domain_models::api::ApplicationResponse; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] +use router_env::logger; +#[cfg(any(feature = "dynamic_routing", feature = "v1"))] use router_env::{instrument, metrics::add_attributes, tracing}; use rustc_hash::FxHashSet; use storage_impl::redis::cache; @@ -29,8 +35,10 @@ use crate::{ types::{domain, storage}, utils::StringExt, }; -#[cfg(all(feature = "dynamic_routing", feature = "v1"))] -use crate::{core::metrics as core_metrics, routes::metrics}; +#[cfg(feature = "v1")] +use crate::{core::metrics as core_metrics, routes::metrics, types::transformers::ForeignInto}; +pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = + "Success rate based dynamic routing algorithm"; /// Provides us with all the configured configs of the Merchant in the ascending time configured /// manner and chooses the first of them @@ -594,28 +602,8 @@ pub async fn refresh_success_based_routing_cache( pub async fn fetch_success_based_routing_configs( state: &SessionState, business_profile: &domain::Profile, - dynamic_routing_algorithm: serde_json::Value, + success_based_routing_id: id_type::RoutingId, ) -> RouterResult<routing_types::SuccessBasedRoutingConfig> { - let dynamic_routing_algorithm_ref = dynamic_routing_algorithm - .parse_value::<routing_types::DynamicRoutingAlgorithmRef>("DynamicRoutingAlgorithmRef") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to parse dynamic_routing_algorithm_ref")?; - - let success_based_routing_id = dynamic_routing_algorithm_ref - .success_based_algorithm - .ok_or(errors::ApiErrorResponse::GenericNotFoundError { - message: "success_based_algorithm not found in dynamic_routing_algorithm_ref" - .to_string(), - })? - .algorithm_id - // error can be possible when the feature is toggled off. - .ok_or(errors::ApiErrorResponse::GenericNotFoundError { - message: format!( - "unable to find algorithm_id in success based algorithm config as the feature is disabled for profile_id: {}", - business_profile.get_id().get_string_repr() - ), - })?; - let key = format!( "{}_{}", business_profile.get_id().get_string_repr(), @@ -657,156 +645,185 @@ pub async fn push_metrics_for_success_based_routing( payment_attempt: &storage::PaymentAttempt, routable_connectors: Vec<routing_types::RoutableConnectorChoice>, business_profile: &domain::Profile, - dynamic_routing_algorithm: serde_json::Value, ) -> RouterResult<()> { - let client = state - .grpc_client - .dynamic_routing - .success_rate_client - .as_ref() - .ok_or(errors::ApiErrorResponse::GenericNotFoundError { - message: "success_rate gRPC client not found".to_string(), - })?; - - let payment_connector = &payment_attempt.connector.clone().ok_or( - errors::ApiErrorResponse::GenericNotFoundError { - message: "unable to derive payment connector from payment attempt".to_string(), - }, - )?; - - let success_based_routing_configs = - fetch_success_based_routing_configs(state, business_profile, dynamic_routing_algorithm) - .await + let success_based_dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = + business_profile + .dynamic_routing_algorithm + .clone() + .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) + .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to retrieve success_rate based dynamic routing configs")?; + .attach_printable("Failed to deserialize DynamicRoutingAlgorithmRef from JSON")? + .unwrap_or_default(); - let tenant_business_profile_id = format!( - "{}:{}", - state.tenant.redis_key_prefix, - business_profile.get_id().get_string_repr() - ); + let success_based_algo_ref = success_based_dynamic_routing_algo_ref + .success_based_algorithm + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("success_based_algorithm not found in dynamic_routing_algorithm from business_profile table")?; + + if success_based_algo_ref.enabled_feature != routing_types::SuccessBasedRoutingFeatures::None { + let client = state + .grpc_client + .dynamic_routing + .success_rate_client + .as_ref() + .ok_or(errors::ApiErrorResponse::GenericNotFoundError { + message: "success_rate gRPC client not found".to_string(), + })?; + + let payment_connector = &payment_attempt.connector.clone().ok_or( + errors::ApiErrorResponse::GenericNotFoundError { + message: "unable to derive payment connector from payment attempt".to_string(), + }, + )?; - let success_based_connectors = client - .calculate_success_rate( - tenant_business_profile_id.clone(), - success_based_routing_configs.clone(), - routable_connectors.clone(), + let success_based_routing_configs = fetch_success_based_routing_configs( + state, + business_profile, + success_based_algo_ref + .algorithm_id_with_timestamp + .algorithm_id + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "success_based_routing_algorithm_id not found in business_profile", + )?, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to calculate/fetch success rate from dynamic routing service")?; - - let payment_status_attribute = - get_desired_payment_status_for_success_routing_metrics(&payment_attempt.status); - - let first_success_based_connector_label = &success_based_connectors - .labels_with_score - .first() - .ok_or(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "unable to fetch the first connector from list of connectors obtained from dynamic routing service", - )? - .label - .to_string(); - - let (first_success_based_connector, merchant_connector_id) = first_success_based_connector_label - .split_once(':') - .ok_or(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "unable to split connector_name and mca_id from the first connector obtained from dynamic routing service", - )?; - - let outcome = get_success_based_metrics_outcome_for_payment( - &payment_status_attribute, - payment_connector.to_string(), - first_success_based_connector.to_string(), - ); - - core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add( - &metrics::CONTEXT, - 1, - &add_attributes([ - ("tenant", state.tenant.name.clone()), - ( - "merchant_id", - payment_attempt.merchant_id.get_string_repr().to_string(), - ), - ( - "profile_id", - payment_attempt.profile_id.get_string_repr().to_string(), - ), - ("merchant_connector_id", merchant_connector_id.to_string()), - ( - "payment_id", - payment_attempt.payment_id.get_string_repr().to_string(), - ), - ( - "success_based_routing_connector", - first_success_based_connector.to_string(), - ), - ("payment_connector", payment_connector.to_string()), - ( - "currency", - payment_attempt - .currency - .map_or_else(|| "None".to_string(), |currency| currency.to_string()), - ), - ( - "payment_method", - payment_attempt.payment_method.map_or_else( - || "None".to_string(), - |payment_method| payment_method.to_string(), + .attach_printable("unable to retrieve success_rate based dynamic routing configs")?; + + let tenant_business_profile_id = generate_tenant_business_profile_id( + &state.tenant.redis_key_prefix, + business_profile.get_id().get_string_repr(), + ); + + let success_based_connectors = client + .calculate_success_rate( + tenant_business_profile_id.clone(), + success_based_routing_configs.clone(), + routable_connectors.clone(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to calculate/fetch success rate from dynamic routing service", + )?; + + let payment_status_attribute = + get_desired_payment_status_for_success_routing_metrics(&payment_attempt.status); + + let first_success_based_connector_label = &success_based_connectors + .labels_with_score + .first() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to fetch the first connector from list of connectors obtained from dynamic routing service", + )? + .label + .to_string(); + + let (first_success_based_connector, merchant_connector_id) = first_success_based_connector_label + .split_once(':') + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to split connector_name and mca_id from the first connector obtained from dynamic routing service", + )?; + + let outcome = get_success_based_metrics_outcome_for_payment( + &payment_status_attribute, + payment_connector.to_string(), + first_success_based_connector.to_string(), + ); + + core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add( + &metrics::CONTEXT, + 1, + &add_attributes([ + ("tenant", state.tenant.name.clone()), + ( + "merchant_id", + payment_attempt.merchant_id.get_string_repr().to_string(), ), - ), - ( - "payment_method_type", - payment_attempt.payment_method_type.map_or_else( - || "None".to_string(), - |payment_method_type| payment_method_type.to_string(), + ( + "profile_id", + payment_attempt.profile_id.get_string_repr().to_string(), ), - ), - ( - "capture_method", - payment_attempt.capture_method.map_or_else( - || "None".to_string(), - |capture_method| capture_method.to_string(), + ("merchant_connector_id", merchant_connector_id.to_string()), + ( + "payment_id", + payment_attempt.payment_id.get_string_repr().to_string(), ), - ), - ( - "authentication_type", - payment_attempt.authentication_type.map_or_else( - || "None".to_string(), - |authentication_type| authentication_type.to_string(), + ( + "success_based_routing_connector", + first_success_based_connector.to_string(), ), - ), - ("payment_status", payment_attempt.status.to_string()), - ("conclusive_classification", outcome.to_string()), - ]), - ); - - client - .update_success_rate( - tenant_business_profile_id, - success_based_routing_configs, - vec![routing_types::RoutableConnectorChoiceWithStatus::new( - routing_types::RoutableConnectorChoice { - choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, - connector: common_enums::RoutableConnectors::from_str( - payment_connector.as_str(), - ) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to infer routable_connector from connector")?, - merchant_connector_id: payment_attempt.merchant_connector_id.clone(), - }, - payment_status_attribute == common_enums::AttemptStatus::Charged, - )], - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "unable to update success based routing window in dynamic routing service", - )?; - Ok(()) + ("payment_connector", payment_connector.to_string()), + ( + "currency", + payment_attempt + .currency + .map_or_else(|| "None".to_string(), |currency| currency.to_string()), + ), + ( + "payment_method", + payment_attempt.payment_method.map_or_else( + || "None".to_string(), + |payment_method| payment_method.to_string(), + ), + ), + ( + "payment_method_type", + payment_attempt.payment_method_type.map_or_else( + || "None".to_string(), + |payment_method_type| payment_method_type.to_string(), + ), + ), + ( + "capture_method", + payment_attempt.capture_method.map_or_else( + || "None".to_string(), + |capture_method| capture_method.to_string(), + ), + ), + ( + "authentication_type", + payment_attempt.authentication_type.map_or_else( + || "None".to_string(), + |authentication_type| authentication_type.to_string(), + ), + ), + ("payment_status", payment_attempt.status.to_string()), + ("conclusive_classification", outcome.to_string()), + ]), + ); + logger::debug!("successfully pushed success_based_routing metrics"); + + client + .update_success_rate( + tenant_business_profile_id, + success_based_routing_configs, + vec![routing_types::RoutableConnectorChoiceWithStatus::new( + routing_types::RoutableConnectorChoice { + choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, + connector: common_enums::RoutableConnectors::from_str( + payment_connector.as_str(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to infer routable_connector from connector")?, + merchant_connector_id: payment_attempt.merchant_connector_id.clone(), + }, + payment_status_attribute == common_enums::AttemptStatus::Charged, + )], + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to update success based routing window in dynamic routing service", + )?; + Ok(()) + } else { + Ok(()) + } } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] @@ -875,3 +892,67 @@ fn get_success_based_metrics_outcome_for_payment( _ => common_enums::SuccessBasedRoutingConclusiveState::NonDeterministic, } } + +/// generates cache key with tenant's redis key prefix and profile_id +pub fn generate_tenant_business_profile_id( + redis_key_prefix: &str, + business_profile_id: &str, +) -> String { + format!("{}:{}", redis_key_prefix, business_profile_id) +} + +/// default config setup for success_based_routing +#[cfg(feature = "v1")] +#[instrument(skip_all)] +pub async fn default_success_based_routing_setup( + state: &SessionState, + key_store: domain::MerchantKeyStore, + business_profile: domain::Profile, + feature_to_enable: routing_types::SuccessBasedRoutingFeatures, + merchant_id: id_type::MerchantId, + mut success_based_dynamic_routing_algo: routing_types::DynamicRoutingAlgorithmRef, +) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> { + let db = state.store.as_ref(); + let key_manager_state = &state.into(); + let profile_id = business_profile.get_id().to_owned(); + let default_success_based_routing_config = routing_types::SuccessBasedRoutingConfig::default(); + let algorithm_id = common_utils::generate_routing_id_of_default_length(); + let timestamp = common_utils::date_time::now(); + let algo = routing_algorithm::RoutingAlgorithm { + algorithm_id: algorithm_id.clone(), + profile_id: profile_id.clone(), + merchant_id, + name: SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(), + description: None, + kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic, + algorithm_data: serde_json::json!(default_success_based_routing_config), + created_at: timestamp, + modified_at: timestamp, + algorithm_for: common_enums::TransactionType::Payment, + }; + + let record = db + .insert_routing_algorithm(algo) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to insert record in routing algorithm table")?; + + success_based_dynamic_routing_algo.update_algorithm_id(algorithm_id, feature_to_enable); + update_business_profile_active_dynamic_algorithm_ref( + db, + key_manager_state, + &key_store, + business_profile, + success_based_dynamic_routing_algo, + ) + .await?; + + let new_record = record.foreign_into(); + + core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add( + &metrics::CONTEXT, + 1, + &add_attributes([("profile_id", profile_id.get_string_repr().to_string())]), + ); + Ok(ApplicationResponse::Json(new_record)) +} diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index 4c8d89fa87d..cc4a9510ab6 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -989,7 +989,7 @@ pub async fn toggle_success_based_routing( ) -> impl Responder { let flow = Flow::ToggleDynamicRouting; let wrapper = routing_types::ToggleSuccessBasedRoutingWrapper { - status: query.into_inner().status, + feature_to_enable: query.into_inner().enable, profile_id: path.into_inner().profile_id, }; Box::pin(oss_api::server_wrap( @@ -1005,7 +1005,7 @@ pub async fn toggle_success_based_routing( state, auth.merchant_account, auth.key_store, - wrapper.status, + wrapper.feature_to_enable, wrapper.profile_id, ) },
2024-10-16T04:25:05Z
## Description <!-- Describe your changes in detail --> This will add dynamic_routing in core flows. After which once the toggle route is hit with `feature = dynamic_connector_selection`, routable connectors will be evaluated on basis of success_based routing. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Will enable success_based routing ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### The testing flows are as follows: 1. Toggle the route with feature(`metrics`, `dynamic_conenctor_selection`, `none`) as `dynamic_connector_selection`. ``` curl --location --request POST 'http://localhost:8080/account/merchant_id/business_profile/profile_id/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \ --header 'api-key: api_key' ``` 2. Check the business_profile table for the enabled dynamic routing feature. 3. Moreover if the dynamic_connector_selection is enabled for business_profile, success_based_routing will be performed, which can be checked by having a log filter with `success_based_routing connectors`. 4. If metrics feature is enabled, there will be no logs from the 3rd step instead there will be a log something like `successfully pushed success_based_routing metrics`, NOTE: this log will also be present in step 3rd. 5. if None is selected no logs regarding `success_based_routing` will be there.
39d89f23b6ae85c4f91a52bb0d970277b43237d8
### The testing flows are as follows: 1. Toggle the route with feature(`metrics`, `dynamic_conenctor_selection`, `none`) as `dynamic_connector_selection`. ``` curl --location --request POST 'http://localhost:8080/account/merchant_id/business_profile/profile_id/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \ --header 'api-key: api_key' ``` 2. Check the business_profile table for the enabled dynamic routing feature. 3. Moreover if the dynamic_connector_selection is enabled for business_profile, success_based_routing will be performed, which can be checked by having a log filter with `success_based_routing connectors`. 4. If metrics feature is enabled, there will be no logs from the 3rd step instead there will be a log something like `successfully pushed success_based_routing metrics`, NOTE: this log will also be present in step 3rd. 5. if None is selected no logs regarding `success_based_routing` will be there.
[ "crates/api_models/src/routing.rs", "crates/openapi/src/openapi.rs", "crates/openapi/src/routes/routing.rs", "crates/router/src/core/errors.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/operations/payment_response.rs", "crates/router/src/core/payments/routing.rs", "crates/router/src/core/routing.rs", "crates/router/src/core/routing/helpers.rs", "crates/router/src/routes/routing.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6330
Bug: fix(list): improve querying time for payments list Quick Fix. Currently payment list is giving intermittent 5xx. After analyzing logs we got to knwo that it is happening for the count query That query need to be called always and we can skip this in most of the cases. Also add the logs around count. This can be a temporary help, till will move to more durable solution.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 674a19f3ef8..039c99ef348 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4449,6 +4449,17 @@ pub struct PaymentListFilterConstraints { /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, } + +impl PaymentListFilterConstraints { + pub fn has_no_attempt_filters(&self) -> bool { + self.connector.is_none() + && self.payment_method.is_none() + && self.payment_method_type.is_none() + && self.authentication_type.is_none() + && self.merchant_connector_id.is_none() + } +} + #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index 67af7a3bef5..85c69824892 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -369,7 +369,6 @@ impl PaymentAttempt { payment_method: Option<Vec<enums::PaymentMethod>>, payment_method_type: Option<Vec<enums::PaymentMethodType>>, authentication_type: Option<Vec<enums::AuthenticationType>>, - profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, ) -> StorageResult<i64> { let mut filter = <Self as HasTable>::table() @@ -394,17 +393,23 @@ impl PaymentAttempt { if let Some(merchant_connector_id) = merchant_connector_id { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id)) } - if let Some(profile_id_list) = profile_id_list { - filter = filter.filter(dsl::profile_id.eq_any(profile_id_list)) - } + router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); - db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( + // TODO: Remove these logs after debugging the issue for delay in count query + let start_time = std::time::Instant::now(); + router_env::logger::debug!("Executing count query start_time: {:?}", start_time); + let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_result_async::<i64>(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(DatabaseError::Others) - .attach_printable("Error filtering count of payments") + .attach_printable("Error filtering count of payments"); + + let duration = start_time.elapsed(); + router_env::logger::debug!("Completed count query in {:?}", duration); + + result } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 5aba0616143..ea65cfff8b4 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -158,7 +158,6 @@ pub trait PaymentAttemptInterface { payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>, authentication_type: Option<Vec<storage_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, - profile_id_list: Option<Vec<id_type::ProfileId>>, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<i64, errors::StorageError>; } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 68f318958a2..651a79a0c14 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3737,54 +3737,69 @@ pub async fn apply_filters_on_payments( merchant_key_store: domain::MerchantKeyStore, constraints: api::PaymentListFilterConstraints, ) -> RouterResponse<api::PaymentListResponseV2> { - let limit = &constraints.limit; - helpers::validate_payment_list_request_for_joins(*limit)?; - let db: &dyn StorageInterface = state.store.as_ref(); - let pi_fetch_constraints = (constraints.clone(), profile_id_list.clone()).try_into()?; - let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db - .get_filtered_payment_intents_attempt( - &(&state).into(), - merchant.get_id(), - &pi_fetch_constraints, - &merchant_key_store, - merchant.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - let data: Vec<api::PaymentsResponse> = - list.into_iter().map(ForeignFrom::foreign_from).collect(); - - let active_attempt_ids = db - .get_filtered_active_attempt_ids_for_total_count( - merchant.get_id(), - &pi_fetch_constraints, - merchant.storage_scheme, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; + common_utils::metrics::utils::record_operation_time( + async { + let limit = &constraints.limit; + helpers::validate_payment_list_request_for_joins(*limit)?; + let db: &dyn StorageInterface = state.store.as_ref(); + let pi_fetch_constraints = (constraints.clone(), profile_id_list.clone()).try_into()?; + let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db + .get_filtered_payment_intents_attempt( + &(&state).into(), + merchant.get_id(), + &pi_fetch_constraints, + &merchant_key_store, + merchant.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + let data: Vec<api::PaymentsResponse> = + list.into_iter().map(ForeignFrom::foreign_from).collect(); + + let active_attempt_ids = db + .get_filtered_active_attempt_ids_for_total_count( + merchant.get_id(), + &pi_fetch_constraints, + merchant.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; - let total_count = db - .get_total_count_of_filtered_payment_attempts( - merchant.get_id(), - &active_attempt_ids, - constraints.connector, - constraints.payment_method, - constraints.payment_method_type, - constraints.authentication_type, - constraints.merchant_connector_id, - pi_fetch_constraints.get_profile_id_list(), - merchant.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; + let total_count = if constraints.has_no_attempt_filters() { + i64::try_from(active_attempt_ids.len()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while converting from usize to i64") + } else { + db.get_total_count_of_filtered_payment_attempts( + merchant.get_id(), + &active_attempt_ids, + constraints.connector, + constraints.payment_method, + constraints.payment_method_type, + constraints.authentication_type, + constraints.merchant_connector_id, + merchant.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + }?; - Ok(services::ApplicationResponse::Json( - api::PaymentListResponseV2 { - count: data.len(), - total_count, - data, + Ok(services::ApplicationResponse::Json( + api::PaymentListResponseV2 { + count: data.len(), + total_count, + data, + }, + )) }, - )) + &metrics::PAYMENT_LIST_LATENCY, + &metrics::CONTEXT, + &[router_env::opentelemetry::KeyValue::new( + "merchant_id", + merchant.get_id().clone(), + )], + ) + .await } #[cfg(all(feature = "olap", feature = "v1"))] diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 9f237c226b6..e8fbd7cb483 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1601,7 +1601,6 @@ impl PaymentAttemptInterface for KafkaStore { payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, - profile_id_list: Option<Vec<id_type::ProfileId>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::DataStorageError> { self.diesel_store @@ -1613,7 +1612,6 @@ impl PaymentAttemptInterface for KafkaStore { payment_method_type, authentication_type, merchant_connector_id, - profile_id_list, storage_scheme, ) .await diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index f3f1cd7cda0..1b55c838c45 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -21,6 +21,8 @@ counter_metric!(PAYMENT_OPS_COUNT, GLOBAL_METER); counter_metric!(PAYMENT_COUNT, GLOBAL_METER); counter_metric!(SUCCESSFUL_PAYMENT, GLOBAL_METER); +//TODO: This can be removed, added for payment list debugging +histogram_metric!(PAYMENT_LIST_LATENCY, GLOBAL_METER); counter_metric!(REFUND_COUNT, GLOBAL_METER); counter_metric!(SUCCESSFUL_REFUND, GLOBAL_METER); diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 7410c5ee363..77ba1da0fcd 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1035,7 +1035,7 @@ pub async fn profile_payments_list_by_filter( |state, auth: auth::AuthenticationData, req, _| { payments::apply_filters_on_payments( state, - auth.merchant_account, + auth.merchant_account.clone(), auth.profile_id.map(|profile_id| vec![profile_id]), auth.key_store, req, diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 13c75e005c4..59fb1155480 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -52,7 +52,6 @@ impl PaymentAttemptInterface for MockDb { _payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, _authentication_type: Option<Vec<common_enums::AuthenticationType>>, _merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, - _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<i64, StorageError> { Err(StorageError::MockDbError)? diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 9053b7561ad..20b46a8460d 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -402,7 +402,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, - profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = self @@ -425,7 +424,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { payment_method, payment_method_type, authentication_type, - profile_id_list, merchant_connector_id, ) .await @@ -1280,7 +1278,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, - profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.router_store @@ -1292,7 +1289,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { payment_method_type, authentication_type, merchant_connector_id, - profile_id_list, storage_scheme, ) .await
2024-10-15T21:20:33Z
## Description - Skip count query if no filters are applied for attempts, in this we don't need to filter attempts as count of active attempt ids will be the total count. - Profile id filter is already getting applied in intents, so removing it from last active attempts. - Add logging around count query. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#6330](https://github.com/juspay/hyperswitch/issues/6330) ## How did you test it? For Tests Lists working is same, same request and response: ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-api-key: dev_VWtyXkyK1Ath1vBNRMM4dqm18J0PVW8SiML4IsKtuzpsR5ojI0FCDBIY0ZRggpFf' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` Response will be something like ``` { "count": 0, "total_count": 0, "data": [] } ``` Log is getting printed sucessfully `Completed count query in 292.71075m ` Results. After hitting some 100 concurrent request for a very large dataset, we can clearly see without count query api is taking less time, and there is significant diff. WIth count query <img width="464" alt="Screenshot 2024-10-16 at 3 59 08 AM" src="https://github.com/user-attachments/assets/7e689588-672d-4148-978d-262ef71e6f94"> Without count query <img width="433" alt="Screenshot 2024-10-16 at 3 59 21 AM" src="https://github.com/user-attachments/assets/fb261141-b857-4a81-b4c0-3abe6fdd6a58">
7e90031c68c7b93db996ee03e11c56b56a87402b
For Tests Lists working is same, same request and response: ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-api-key: dev_VWtyXkyK1Ath1vBNRMM4dqm18J0PVW8SiML4IsKtuzpsR5ojI0FCDBIY0ZRggpFf' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` Response will be something like ``` { "count": 0, "total_count": 0, "data": [] } ``` Log is getting printed sucessfully `Completed count query in 292.71075m ` Results. After hitting some 100 concurrent request for a very large dataset, we can clearly see without count query api is taking less time, and there is significant diff. WIth count query <img width="464" alt="Screenshot 2024-10-16 at 3 59 08 AM" src="https://github.com/user-attachments/assets/7e689588-672d-4148-978d-262ef71e6f94"> Without count query <img width="433" alt="Screenshot 2024-10-16 at 3 59 21 AM" src="https://github.com/user-attachments/assets/fb261141-b857-4a81-b4c0-3abe6fdd6a58">
[ "crates/api_models/src/payments.rs", "crates/diesel_models/src/query/payment_attempt.rs", "crates/hyperswitch_domain_models/src/payments/payment_attempt.rs", "crates/router/src/core/payments.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/routes/metrics.rs", "crates/router/src/routes/payments.rs", "crates/storage_impl/src/mock_db/payment_attempt.rs", "crates/storage_impl/src/payments/payment_attempt.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6340
Bug: Fix(mandates): handle the connector_mandate creation once and only if the payment is charged Earlier we used to store the connector mandate id irrespective of the payments status being charged or not for 3DS flows, now we would handle the connector_mandate_id updation in payment_method once and only if the payment has a status as charged.
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 8306deeb258..e36a6d74994 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -3356,3 +3356,16 @@ pub enum SurchargeCalculationOverride { /// Calculate surcharge Calculate, } + +/// Connector Mandate Status +#[derive( + Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, +)] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum ConnectorMandateStatus { + /// Indicates that the connector mandate is active and can be used for payments. + Active, + /// Indicates that the connector mandate is not active and hence cannot be used for payments. + Inactive, +} diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 277061c78aa..ae98b8a0481 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -12,6 +12,16 @@ use crate::schema::payment_attempt; #[cfg(feature = "v2")] use crate::schema_v2::payment_attempt; +common_utils::impl_to_sql_from_sql_json!(ConnectorMandateReferenceId); +#[derive( + Clone, Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq, diesel::AsExpression, +)] +#[diesel(sql_type = diesel::sql_types::Jsonb)] +pub struct ConnectorMandateReferenceId { + pub connector_mandate_id: Option<String>, + pub payment_method_id: Option<String>, + pub mandate_metadata: Option<serde_json::Value>, +} #[cfg(feature = "v2")] #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable, @@ -76,6 +86,7 @@ pub struct PaymentAttempt { pub id: String, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, + pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, } #[cfg(feature = "v1")] @@ -153,6 +164,7 @@ pub struct PaymentAttempt { pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub connector_transaction_data: Option<String>, + pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, } #[cfg(feature = "v1")] @@ -256,6 +268,7 @@ pub struct PaymentAttemptNew { pub card_network: Option<String>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, + pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, } #[cfg(feature = "v1")] @@ -328,6 +341,7 @@ pub struct PaymentAttemptNew { pub card_network: Option<String>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, + pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, } #[cfg(feature = "v1")] @@ -442,6 +456,7 @@ pub enum PaymentAttemptUpdate { unified_message: Option<Option<String>>, payment_method_data: Option<serde_json::Value>, charge_id: Option<String>, + connector_mandate_detail: Option<ConnectorMandateReferenceId>, }, UnresolvedResponseUpdate { status: storage_enums::AttemptStatus, @@ -757,6 +772,7 @@ pub struct PaymentAttemptUpdateInternal { customer_acceptance: Option<pii::SecretSerdeValue>, card_network: Option<String>, connector_payment_data: Option<String>, + connector_mandate_detail: Option<ConnectorMandateReferenceId>, } #[cfg(feature = "v1")] @@ -813,6 +829,7 @@ pub struct PaymentAttemptUpdateInternal { pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub connector_transaction_data: Option<String>, + pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, } #[cfg(feature = "v2")] @@ -1002,6 +1019,7 @@ impl PaymentAttemptUpdate { shipping_cost, order_tax_amount, connector_transaction_data, + connector_mandate_detail, } = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source); PaymentAttempt { amount: amount.unwrap_or(source.amount), @@ -1059,6 +1077,7 @@ impl PaymentAttemptUpdate { order_tax_amount: order_tax_amount.or(source.order_tax_amount), connector_transaction_data: connector_transaction_data .or(source.connector_transaction_data), + connector_mandate_detail: connector_mandate_detail.or(source.connector_mandate_detail), ..source } } @@ -2054,6 +2073,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::AuthenticationTypeUpdate { authentication_type, @@ -2109,6 +2129,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::ConfirmUpdate { amount, @@ -2194,6 +2215,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost, order_tax_amount, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::VoidUpdate { status, @@ -2250,6 +2272,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::RejectUpdate { status, @@ -2307,6 +2330,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::BlocklistUpdate { status, @@ -2364,6 +2388,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::PaymentMethodDetailsUpdate { payment_method_id, @@ -2419,6 +2444,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::ResponseUpdate { status, @@ -2441,6 +2467,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { unified_message, payment_method_data, charge_id, + connector_mandate_detail, } => { let (connector_transaction_id, connector_transaction_data) = connector_transaction_id @@ -2498,6 +2525,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_mandate_detail, } } PaymentAttemptUpdate::ErrorUpdate { @@ -2570,6 +2598,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_mandate_detail: None, } } PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self { @@ -2623,6 +2652,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::UpdateTrackers { payment_token, @@ -2684,6 +2714,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::UnresolvedResponseUpdate { status, @@ -2752,6 +2783,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_mandate_detail: None, } } PaymentAttemptUpdate::PreprocessingUpdate { @@ -2819,6 +2851,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_mandate_detail: None, } } PaymentAttemptUpdate::CaptureUpdate { @@ -2876,6 +2909,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::AmountToCaptureUpdate { status, @@ -2932,6 +2966,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::ConnectorResponse { authentication_data, @@ -2997,6 +3032,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_mandate_detail: None, } } PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { @@ -3053,6 +3089,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::AuthenticationUpdate { status, @@ -3111,6 +3148,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, PaymentAttemptUpdate::ManualUpdate { status, @@ -3178,6 +3216,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_mandate_detail: None, } } PaymentAttemptUpdate::PostSessionTokensUpdate { @@ -3234,6 +3273,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, connector_transaction_data: None, + connector_mandate_detail: None, }, } } @@ -3319,7 +3359,6 @@ mod tests { "user_agent": "amet irure esse" } }, - "mandate_type": { "single_use": { "amount": 6540, "currency": "USD" diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 5cd2abd3599..8d2dfc47b62 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -850,6 +850,7 @@ diesel::table! { order_tax_amount -> Nullable<Int8>, #[max_length = 512] connector_transaction_data -> Nullable<Varchar>, + connector_mandate_detail -> Nullable<Jsonb>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index d662603981b..45a4ce03e55 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -821,6 +821,7 @@ diesel::table! { id -> Varchar, shipping_cost -> Nullable<Int8>, order_tax_amount -> Nullable<Int8>, + connector_mandate_detail -> Nullable<Jsonb>, } } diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index db30d02bd7c..88617afb392 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -12,7 +12,7 @@ use crate::schema::payment_attempt; use crate::schema_v2::payment_attempt; use crate::{ enums::{MandateDataType, MandateDetails}, - PaymentAttemptNew, + ConnectorMandateReferenceId, PaymentAttemptNew, }; #[cfg(feature = "v2")] @@ -204,6 +204,7 @@ pub struct PaymentAttemptBatchNew { pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub connector_transaction_data: Option<String>, + pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, } #[cfg(feature = "v1")] @@ -282,6 +283,7 @@ impl PaymentAttemptBatchNew { organization_id: self.organization_id, shipping_cost: self.shipping_cost, order_tax_amount: self.order_tax_amount, + connector_mandate_detail: self.connector_mandate_detail, } } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 691037c2824..8ecac77e54e 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -10,7 +10,8 @@ use common_utils::{ }, }; use diesel_models::{ - PaymentAttempt as DieselPaymentAttempt, PaymentAttemptNew as DieselPaymentAttemptNew, + ConnectorMandateReferenceId, PaymentAttempt as DieselPaymentAttempt, + PaymentAttemptNew as DieselPaymentAttemptNew, PaymentAttemptUpdate as DieselPaymentAttemptUpdate, }; use error_stack::ResultExt; @@ -222,6 +223,7 @@ pub struct PaymentAttempt { pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub id: String, + pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, } impl PaymentAttempt { @@ -331,6 +333,7 @@ pub struct PaymentAttempt { pub customer_acceptance: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, + pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default)] @@ -624,6 +627,7 @@ pub struct PaymentAttemptNew { pub customer_acceptance: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, + pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, } #[cfg(feature = "v1")] @@ -732,6 +736,7 @@ pub enum PaymentAttemptUpdate { unified_message: Option<Option<String>>, payment_method_data: Option<serde_json::Value>, charge_id: Option<String>, + connector_mandate_detail: Option<ConnectorMandateReferenceId>, }, UnresolvedResponseUpdate { status: storage_enums::AttemptStatus, @@ -992,6 +997,7 @@ impl PaymentAttemptUpdate { unified_message, payment_method_data, charge_id, + connector_mandate_detail, } => DieselPaymentAttemptUpdate::ResponseUpdate { status, connector, @@ -1013,6 +1019,7 @@ impl PaymentAttemptUpdate { unified_message, payment_method_data, charge_id, + connector_mandate_detail, }, Self::UnresolvedResponseUpdate { status, @@ -1281,6 +1288,7 @@ impl behaviour::Conversion for PaymentAttempt { connector_transaction_data, order_tax_amount: self.net_amount.get_order_tax_amount(), shipping_cost: self.net_amount.get_shipping_cost(), + connector_mandate_detail: self.connector_mandate_detail, }) } @@ -1361,6 +1369,7 @@ impl behaviour::Conversion for PaymentAttempt { customer_acceptance: storage_model.customer_acceptance, profile_id: storage_model.profile_id, organization_id: storage_model.organization_id, + connector_mandate_detail: storage_model.connector_mandate_detail, }) } .await @@ -1442,6 +1451,7 @@ impl behaviour::Conversion for PaymentAttempt { card_network, order_tax_amount: self.net_amount.get_order_tax_amount(), shipping_cost: self.net_amount.get_shipping_cost(), + connector_mandate_detail: self.connector_mandate_detail, }) } } @@ -1517,6 +1527,7 @@ impl behaviour::Conversion for PaymentAttempt { shipping_cost, order_tax_amount, connector, + connector_mandate_detail, } = self; let (connector_payment_id, connector_payment_data) = connector_payment_id @@ -1580,6 +1591,7 @@ impl behaviour::Conversion for PaymentAttempt { external_reference_id, connector, connector_payment_data, + connector_mandate_detail, }) } @@ -1651,6 +1663,7 @@ impl behaviour::Conversion for PaymentAttempt { authentication_applied: storage_model.authentication_applied, external_reference_id: storage_model.external_reference_id, connector: storage_model.connector, + connector_mandate_detail: storage_model.connector_mandate_detail, }) } .await @@ -1718,6 +1731,7 @@ impl behaviour::Conversion for PaymentAttempt { order_tax_amount: self.order_tax_amount, shipping_cost: self.shipping_cost, amount_to_capture: self.amount_to_capture, + connector_mandate_detail: self.connector_mandate_detail, }) } } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 7c97516192e..27d73d0df46 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4071,6 +4071,7 @@ impl AttemptType { customer_acceptance: old_payment_attempt.customer_acceptance, organization_id: old_payment_attempt.organization_id, profile_id: old_payment_attempt.profile_id, + connector_mandate_detail: None, } } diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 9ec2438ddb3..ca32be35e55 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -614,7 +614,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa } else { (None, payment_method_info) }; - // The operation merges mandate data from both request and payment_attempt let setup_mandate = mandate_data.map(|mut sm| { sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type); diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 779b2d29c06..fc1f71c2085 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1206,8 +1206,10 @@ impl PaymentCreate { .map(Secret::new), organization_id: organization_id.clone(), profile_id, + connector_mandate_detail: None, }, additional_pm_data, + )) } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 6ead0523020..3bb6647b527 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1,11 +1,12 @@ use std::collections::HashMap; +use api_models::payments::{ConnectorMandateReferenceId, MandateReferenceId}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::RoutableConnectorChoice; use async_trait::async_trait; use common_enums::{AuthorizationStatus, SessionUpdateStatus}; use common_utils::{ - ext_traits::{AsyncExt, Encode}, + ext_traits::{AsyncExt, Encode, ValueExt}, types::{keymanager::KeyManagerState, ConnectorTransactionId, MinorUnit}, }; use error_stack::{report, ResultExt}; @@ -184,14 +185,11 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor let save_payment_call_future = Box::pin(tokenization::save_payment_method( state, connector_name.clone(), - merchant_connector_id.clone(), save_payment_data, customer_id.clone(), merchant_account, resp.request.payment_method_type, key_store, - Some(resp.request.amount), - Some(resp.request.currency), billing_name.clone(), payment_method_billing_address, business_profile, @@ -208,7 +206,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor resp.request.setup_future_usage, Some(enums::FutureUsage::OffSession) ); - + let storage_scheme = merchant_account.storage_scheme; if is_legacy_mandate { // Mandate is created on the application side and at the connector. let tokenization::SavePaymentMethodDataResponse { @@ -233,15 +231,46 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor // The mandate is created on connector's end. let tokenization::SavePaymentMethodDataResponse { payment_method_id, - mandate_reference_id, + connector_mandate_reference_id, .. } = save_payment_call_future.await?; - + payment_data.payment_method_info = if let Some(payment_method_id) = &payment_method_id { + match state + .store + .find_payment_method( + &(state.into()), + key_store, + payment_method_id, + storage_scheme, + ) + .await + { + Ok(payment_method) => Some(payment_method), + Err(error) => { + if error.current_context().is_db_not_found() { + logger::info!("Payment Method not found in db {:?}", error); + None + } else { + Err(error) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error retrieving payment method from db") + .map_err(|err| logger::error!(payment_method_retrieve=?err)) + .ok() + } + } + } + } else { + None + }; payment_data.payment_attempt.payment_method_id = payment_method_id; - + payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id + .clone() + .map(ForeignFrom::foreign_from); payment_data.set_mandate_id(api_models::payments::MandateIds { mandate_id: None, - mandate_reference_id, + mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| { + MandateReferenceId::ConnectorMandateId(connector_mandate_id) + }), }); Ok(()) } else if should_avoid_saving { @@ -256,16 +285,10 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor let key_store = key_store.clone(); let state = state.clone(); let customer_id = payment_data.payment_intent.customer_id.clone(); - - let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone(); let payment_attempt = payment_data.payment_attempt.clone(); let business_profile = business_profile.clone(); - - let amount = resp.request.amount; - let currency = resp.request.currency; let payment_method_type = resp.request.payment_method_type; - let storage_scheme = merchant_account.clone().storage_scheme; let payment_method_billing_address = payment_method_billing_address.cloned(); logger::info!("Call to save_payment_method in locker"); @@ -276,14 +299,11 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor let result = Box::pin(tokenization::save_payment_method( &state, connector_name, - merchant_connector_id, save_payment_data, customer_id, &merchant_account, payment_method_type, &key_store, - Some(amount), - Some(currency), billing_name, payment_method_billing_address.as_ref(), &business_profile, @@ -554,6 +574,33 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for where F: 'b + Clone + Send + Sync, { + let (connector_mandate_id, mandate_metadata) = resp + .response + .clone() + .ok() + .and_then(|resp| { + if let types::PaymentsResponseData::TransactionResponse { + mandate_reference, .. + } = resp + { + mandate_reference.map(|mandate_ref| { + ( + mandate_ref.connector_mandate_id.clone(), + mandate_ref.mandate_metadata.clone(), + ) + }) + } else { + None + } + }) + .unwrap_or((None, None)); + + update_connector_mandate_details_for_the_flow( + connector_mandate_id, + mandate_metadata, + payment_data, + )?; + update_payment_method_status_and_ntid( state, key_store, @@ -1038,19 +1085,16 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone(); let tokenization::SavePaymentMethodDataResponse { payment_method_id, - mandate_reference_id, + connector_mandate_reference_id, .. } = Box::pin(tokenization::save_payment_method( state, connector_name, - merchant_connector_id.clone(), save_payment_data, customer_id.clone(), merchant_account, resp.request.payment_method_type, key_store, - resp.request.amount, - Some(resp.request.currency), billing_name, None, business_profile, @@ -1069,9 +1113,14 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa .await?; payment_data.payment_attempt.payment_method_id = payment_method_id; payment_data.payment_attempt.mandate_id = mandate_id; + payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id + .clone() + .map(ForeignFrom::foreign_from); payment_data.set_mandate_id(api_models::payments::MandateIds { mandate_id: None, - mandate_reference_id, + mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| { + MandateReferenceId::ConnectorMandateId(connector_mandate_id) + }), }); Ok(()) } @@ -1127,6 +1176,32 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData where F: 'b + Clone + Send + Sync, { + let (connector_mandate_id, mandate_metadata) = resp + .response + .clone() + .ok() + .and_then(|resp| { + if let types::PaymentsResponseData::TransactionResponse { + mandate_reference, .. + } = resp + { + mandate_reference.map(|mandate_ref| { + ( + mandate_ref.connector_mandate_id.clone(), + mandate_ref.mandate_metadata.clone(), + ) + }) + } else { + None + } + }) + .unwrap_or((None, None)); + update_connector_mandate_details_for_the_flow( + connector_mandate_id, + mandate_metadata, + payment_data, + )?; + update_payment_method_status_and_ntid( state, key_store, @@ -1487,6 +1562,78 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( .payment_intent .fingerprint_id .clone_from(&payment_data.payment_attempt.fingerprint_id); + + if let Some(payment_method) = + payment_data.payment_method_info.clone() + { + // Parse value to check for mandates' existence + let mandate_details = payment_method + .connector_mandate_details + .clone() + .map(|val| { + val.parse_value::<storage::PaymentsMandateReference>( + "PaymentsMandateReference", + ) + }) + .transpose() + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) + .attach_printable( + "Failed to deserialize to Payment Mandate Reference ", + )?; + + if let Some(mca_id) = + payment_data.payment_attempt.merchant_connector_id.clone() + { + // check if the mandate has not already been set to active + if !mandate_details + .as_ref() + .map(|payment_mandate_reference| { + + payment_mandate_reference.0.get(&mca_id) + .map(|payment_mandate_reference_record| payment_mandate_reference_record.connector_mandate_status == Some(common_enums::ConnectorMandateStatus::Active)) + .unwrap_or(false) + }) + .unwrap_or(false) + { + let (connector_mandate_id, mandate_metadata) = payment_data.payment_attempt.connector_mandate_detail.clone() + .map(|cmr| (cmr.connector_mandate_id, cmr.mandate_metadata)) + .unwrap_or((None, None)); + + // Update the connector mandate details with the payment attempt connector mandate id + let connector_mandate_details = + tokenization::update_connector_mandate_details( + mandate_details, + payment_data.payment_attempt.payment_method_type, + Some( + payment_data + .payment_attempt + .net_amount + .get_total_amount() + .get_amount_as_i64(), + ), + payment_data.payment_attempt.currency, + payment_data.payment_attempt.merchant_connector_id.clone(), + connector_mandate_id, + mandate_metadata, + )?; + // Update the payment method table with the active mandate record + payment_methods::cards::update_payment_method_connector_mandate_details( + state, + key_store, + &*state.store, + payment_method, + connector_mandate_details, + storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update payment method in db")?; + } + } + } + metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]); } @@ -1561,6 +1708,10 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( encoded_data, payment_method_data: additional_payment_method_data, charge_id, + connector_mandate_detail: payment_data + .payment_attempt + .connector_mandate_detail + .clone(), }), ), }; @@ -1760,59 +1911,6 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( .in_current_span(), ); - // When connector requires redirection for mandate creation it can update the connector mandate_id in payment_methods during Psync and CompleteAuthorize - - let flow_name = core_utils::get_flow_name::<F>()?; - if flow_name == "PSync" || flow_name == "CompleteAuthorize" { - let (connector_mandate_id, mandate_metadata) = match router_data.response.clone() { - Ok(resp) => match resp { - types::PaymentsResponseData::TransactionResponse { - ref mandate_reference, - .. - } => { - if let Some(mandate_ref) = mandate_reference { - ( - mandate_ref.connector_mandate_id.clone(), - mandate_ref.mandate_metadata.clone(), - ) - } else { - (None, None) - } - } - _ => (None, None), - }, - Err(_) => (None, None), - }; - if let Some(payment_method) = payment_data.payment_method_info.clone() { - let connector_mandate_details = - tokenization::update_connector_mandate_details_in_payment_method( - payment_method.clone(), - payment_method.payment_method_type, - Some( - payment_data - .payment_attempt - .net_amount - .get_total_amount() - .get_amount_as_i64(), - ), - payment_data.payment_attempt.currency, - payment_data.payment_attempt.merchant_connector_id.clone(), - connector_mandate_id, - mandate_metadata, - )?; - payment_methods::cards::update_payment_method_connector_mandate_details( - state, - key_store, - &*state.store, - payment_method.clone(), - connector_mandate_details, - storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to update payment method in db")? - } - } // When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize let m_db = state.clone().store; let m_router_data_merchant_id = router_data.merchant_id.clone(); @@ -2032,6 +2130,35 @@ async fn update_payment_method_status_and_ntid<F: Clone>( Ok(()) } +fn update_connector_mandate_details_for_the_flow<F: Clone>( + connector_mandate_id: Option<String>, + mandate_metadata: Option<serde_json::Value>, + payment_data: &mut PaymentData<F>, +) -> RouterResult<()> { + let connector_mandate_reference_id = if connector_mandate_id.is_some() { + Some(ConnectorMandateReferenceId { + connector_mandate_id: connector_mandate_id.clone(), + payment_method_id: None, + update_history: None, + mandate_metadata: mandate_metadata.clone(), + }) + } else { + None + }; + + payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id + .clone() + .map(ForeignFrom::foreign_from); + + payment_data.set_mandate_id(api_models::payments::MandateIds { + mandate_id: None, + mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| { + MandateReferenceId::ConnectorMandateId(connector_mandate_id) + }), + }); + Ok(()) +} + fn response_to_capture_update( multiple_capture_data: &MultipleCaptureData, response_list: HashMap<String, CaptureSyncResponse>, diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 374c5680685..e4b6d0e287c 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -456,6 +456,7 @@ where unified_message: None, payment_method_data: additional_payment_method_data, charge_id, + connector_mandate_detail: None, }; #[cfg(feature = "v1")] @@ -642,6 +643,7 @@ pub fn make_new_payment_attempt( fingerprint_id: Default::default(), charge_id: Default::default(), customer_acceptance: Default::default(), + connector_mandate_detail: Default::default(), } } diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 213a9211c06..b4e5ade5698 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -5,8 +5,8 @@ use std::collections::HashMap; not(feature = "payment_methods_v2") ))] use api_models::payment_methods::PaymentMethodsData; -use api_models::payments::{ConnectorMandateReferenceId, MandateReferenceId}; -use common_enums::PaymentMethod; +use api_models::payments::ConnectorMandateReferenceId; +use common_enums::{ConnectorMandateStatus, PaymentMethod}; use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, Encode, ValueExt}, @@ -61,7 +61,7 @@ impl<F, Req: Clone> From<&types::RouterData<F, Req, types::PaymentsResponseData> pub struct SavePaymentMethodDataResponse { pub payment_method_id: Option<String>, pub payment_method_status: Option<common_enums::PaymentMethodStatus>, - pub mandate_reference_id: Option<MandateReferenceId>, + pub connector_mandate_reference_id: Option<ConnectorMandateReferenceId>, } #[cfg(all( any(feature = "v1", feature = "v2"), @@ -72,14 +72,11 @@ pub struct SavePaymentMethodDataResponse { pub async fn save_payment_method<FData>( state: &SessionState, connector_name: String, - merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, save_payment_method_data: SavePaymentMethodData<FData>, customer_id: Option<id_type::CustomerId>, merchant_account: &domain::MerchantAccount, payment_method_type: Option<storage_enums::PaymentMethodType>, key_store: &domain::MerchantKeyStore, - amount: Option<i64>, - currency: Option<storage_enums::Currency>, billing_name: Option<Secret<String>>, payment_method_billing_address: Option<&api::Address>, business_profile: &domain::Profile, @@ -174,32 +171,6 @@ where } _ => (None, None), }; - let check_for_mit_mandates = save_payment_method_data - .request - .get_setup_mandate_details() - .is_none() - && save_payment_method_data - .request - .get_setup_future_usage() - .map(|future_usage| future_usage == storage_enums::FutureUsage::OffSession) - .unwrap_or(false); - // insert in PaymentMethods if its a off-session mit payment - let connector_mandate_details = if check_for_mit_mandates { - add_connector_mandate_details_in_payment_method( - payment_method_type, - amount, - currency, - merchant_connector_id.clone(), - connector_mandate_id.clone(), - mandate_metadata.clone(), - ) - } else { - None - } - .map(|connector_mandate_data| connector_mandate_data.encode_to_value()) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to serialize customer acceptance to value")?; let pm_id = if customer_acceptance.is_some() { let payment_method_create_request = @@ -384,24 +355,6 @@ where .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; - if check_for_mit_mandates { - let connector_mandate_details = - update_connector_mandate_details_in_payment_method( - pm.clone(), - payment_method_type, - amount, - currency, - merchant_connector_id.clone(), - connector_mandate_id.clone(), - mandate_metadata.clone(), - )?; - - payment_methods::cards::update_payment_method_connector_mandate_details(state, - key_store,db, pm, connector_mandate_details, merchant_account.storage_scheme).await.change_context( - errors::ApiErrorResponse::InternalServerError, - ) - .attach_printable("Failed to update payment method in db")?; - } } Err(err) => { if err.current_context().is_db_not_found() { @@ -418,7 +371,7 @@ where customer_acceptance, pm_data_encrypted.map(Into::into), key_store, - connector_mandate_details, + None, pm_status, network_transaction_id, merchant_account.storage_scheme, @@ -489,28 +442,7 @@ where resp.payment_method_id = payment_method_id; let existing_pm = match payment_method { - Ok(pm) => { - // update if its a off-session mit payment - if check_for_mit_mandates { - let connector_mandate_details = - update_connector_mandate_details_in_payment_method( - pm.clone(), - payment_method_type, - amount, - currency, - merchant_connector_id.clone(), - connector_mandate_id.clone(), - mandate_metadata.clone(), - )?; - - payment_methods::cards::update_payment_method_connector_mandate_details( state, - key_store,db, pm.clone(), connector_mandate_details, merchant_account.storage_scheme).await.change_context( - errors::ApiErrorResponse::InternalServerError, - ) - .attach_printable("Failed to update payment method in db")?; - } - Ok(pm) - } + Ok(pm) => Ok(pm), Err(err) => { if err.current_context().is_db_not_found() { payment_methods::cards::create_payment_method( @@ -524,7 +456,7 @@ where customer_acceptance, pm_data_encrypted.map(Into::into), key_store, - connector_mandate_details, + None, pm_status, network_transaction_id, merchant_account.storage_scheme, @@ -733,7 +665,7 @@ where customer_acceptance, pm_data_encrypted.map(Into::into), key_store, - connector_mandate_details, + None, pm_status, network_transaction_id, merchant_account.storage_scheme, @@ -755,35 +687,28 @@ where } else { None }; - let cmid_config = db - .find_config_by_key_unwrap_or( - format!("{}_should_show_connector_mandate_id_in_payments_response", merchant_account.get_id().get_string_repr().to_owned()).as_str(), - Some("false".to_string()), - ) - .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", connector_mandate_details_population=?err)).ok(); - - let mandate_reference_id = match cmid_config { - Some(config) if config.config == "true" => Some( - MandateReferenceId::ConnectorMandateId(ConnectorMandateReferenceId { - connector_mandate_id: connector_mandate_id.clone(), - payment_method_id: pm_id.clone(), - update_history: None, - mandate_metadata: mandate_metadata.clone(), - }), - ), - _ => None, + // check if there needs to be a config if yes then remove it to a different place + let connector_mandate_reference_id = if connector_mandate_id.is_some() { + Some(ConnectorMandateReferenceId { + connector_mandate_id: connector_mandate_id.clone(), + payment_method_id: None, + update_history: None, + mandate_metadata: mandate_metadata.clone(), + }) + } else { + None }; Ok(SavePaymentMethodDataResponse { payment_method_id: pm_id, payment_method_status: pm_status, - mandate_reference_id, + connector_mandate_reference_id, }) } Err(_) => Ok(SavePaymentMethodDataResponse { payment_method_id: None, payment_method_status: None, - mandate_reference_id: None, + connector_mandate_reference_id: None, }), } } @@ -795,14 +720,11 @@ where pub async fn save_payment_method<FData>( _state: &SessionState, _connector_name: String, - _merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, _save_payment_method_data: SavePaymentMethodData<FData>, _customer_id: Option<id_type::CustomerId>, _merchant_account: &domain::MerchantAccount, _payment_method_type: Option<storage_enums::PaymentMethodType>, _key_store: &domain::MerchantKeyStore, - _amount: Option<i64>, - _currency: Option<storage_enums::Currency>, _billing_name: Option<Secret<String>>, _payment_method_billing_address: Option<&api::Address>, _business_profile: &domain::Profile, @@ -1226,6 +1148,7 @@ pub fn add_connector_mandate_details_in_payment_method( original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, mandate_metadata, + connector_mandate_status: Some(ConnectorMandateStatus::Active), }, ); Some(storage::PaymentsMandateReference(mandate_details)) @@ -1234,8 +1157,8 @@ pub fn add_connector_mandate_details_in_payment_method( } } -pub fn update_connector_mandate_details_in_payment_method( - payment_method: domain::PaymentMethod, +pub fn update_connector_mandate_details( + mandate_details: Option<storage::PaymentsMandateReference>, payment_method_type: Option<storage_enums::PaymentMethodType>, authorized_amount: Option<i64>, authorized_currency: Option<storage_enums::Currency>, @@ -1243,17 +1166,8 @@ pub fn update_connector_mandate_details_in_payment_method( connector_mandate_id: Option<String>, mandate_metadata: Option<serde_json::Value>, ) -> RouterResult<Option<serde_json::Value>> { - let mandate_reference = match payment_method.connector_mandate_details { - Some(_) => { - let mandate_details = payment_method - .connector_mandate_details - .map(|val| { - val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference") - }) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; - + let mandate_reference = match mandate_details { + Some(mut payment_mandate_reference) => { if let Some((mca_id, connector_mandate_id)) = merchant_connector_id.clone().zip(connector_mandate_id) { @@ -1263,20 +1177,21 @@ pub fn update_connector_mandate_details_in_payment_method( original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, mandate_metadata: mandate_metadata.clone(), + connector_mandate_status: Some(ConnectorMandateStatus::Active), }; - mandate_details.map(|mut payment_mandate_reference| { - payment_mandate_reference - .entry(mca_id) - .and_modify(|pm| *pm = updated_record) - .or_insert(storage::PaymentsMandateReferenceRecord { - connector_mandate_id, - payment_method_type, - original_payment_authorized_amount: authorized_amount, - original_payment_authorized_currency: authorized_currency, - mandate_metadata: mandate_metadata.clone(), - }); - payment_mandate_reference - }) + + payment_mandate_reference + .entry(mca_id) + .and_modify(|pm| *pm = updated_record) + .or_insert(storage::PaymentsMandateReferenceRecord { + connector_mandate_id, + payment_method_type, + original_payment_authorized_amount: authorized_amount, + original_payment_authorized_currency: authorized_currency, + mandate_metadata: mandate_metadata.clone(), + connector_mandate_status: Some(ConnectorMandateStatus::Active), + }); + Some(payment_mandate_reference) } else { None } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 36586fdb155..0d9d684cae8 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1,8 +1,8 @@ use std::{fmt::Debug, marker::PhantomData, str::FromStr}; use api_models::payments::{ - Address, CustomerDetails, CustomerDetailsResponse, FrmMessage, PaymentChargeRequest, - PaymentChargeResponse, RequestSurchargeDetails, + Address, ConnectorMandateReferenceId, CustomerDetails, CustomerDetailsResponse, FrmMessage, + PaymentChargeRequest, PaymentChargeResponse, RequestSurchargeDetails, }; use common_enums::{Currency, RequestIncrementalAuthorization}; use common_utils::{ @@ -11,7 +11,10 @@ use common_utils::{ pii::Email, types::{self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnitForConnector}, }; -use diesel_models::ephemeral_key; +use diesel_models::{ + ephemeral_key, + payment_attempt::ConnectorMandateReferenceId as DieselConnectorMandateReferenceId, +}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types}; use masking::{ExposeInterface, Maskable, PeekInterface, Secret}; @@ -2849,3 +2852,23 @@ impl ForeignFrom<diesel_models::TransactionDetailsUiConfiguration> } } } + +impl ForeignFrom<DieselConnectorMandateReferenceId> for ConnectorMandateReferenceId { + fn foreign_from(value: DieselConnectorMandateReferenceId) -> Self { + Self { + connector_mandate_id: value.connector_mandate_id, + payment_method_id: value.payment_method_id, + update_history: None, + mandate_metadata: value.mandate_metadata, + } + } +} +impl ForeignFrom<ConnectorMandateReferenceId> for DieselConnectorMandateReferenceId { + fn foreign_from(value: ConnectorMandateReferenceId) -> Self { + Self { + connector_mandate_id: value.connector_mandate_id, + payment_method_id: value.payment_method_id, + mandate_metadata: value.mandate_metadata, + } + } +} diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 3942c395665..19670fc8ccb 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -259,13 +259,13 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( let merchant_connector_account = match merchant_connector_account { Some(merchant_connector_account) => merchant_connector_account, None => { - helper_utils::get_mca_from_object_reference_id( + Box::pin(helper_utils::get_mca_from_object_reference_id( &state, object_ref_id.clone(), &merchant_account, &connector_name, &key_store, - ) + )) .await? } }; diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index 40335d5f2ab..502e03b7293 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -216,6 +216,7 @@ mod tests { customer_acceptance: Default::default(), profile_id: common_utils::generate_profile_id_of_default_length(), organization_id: Default::default(), + connector_mandate_detail: Default::default(), }; let store = state @@ -299,6 +300,7 @@ mod tests { customer_acceptance: Default::default(), profile_id: common_utils::generate_profile_id_of_default_length(), organization_id: Default::default(), + connector_mandate_detail: Default::default(), }; let store = state .stores @@ -395,6 +397,7 @@ mod tests { customer_acceptance: Default::default(), profile_id: common_utils::generate_profile_id_of_default_length(), organization_id: Default::default(), + connector_mandate_detail: Default::default(), }; let store = state .stores diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index bb1b801edb6..20d0ee74b01 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -125,6 +125,7 @@ pub struct PaymentsMandateReferenceRecord { pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::Currency>, pub mandate_metadata: Option<serde_json::Value>, + pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 122989a82cf..7faafb14ec1 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -339,6 +339,7 @@ pub async fn generate_sample_data( shipping_cost: None, order_tax_amount: None, connector_transaction_data, + connector_mandate_detail: None, }; let refund = if refunds_count < number_of_refunds && !is_failed_payment { diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 59fb1155480..121397cdfb9 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -180,6 +180,7 @@ impl PaymentAttemptInterface for MockDb { customer_acceptance: payment_attempt.customer_acceptance, organization_id: payment_attempt.organization_id, profile_id: payment_attempt.profile_id, + connector_mandate_detail: payment_attempt.connector_mandate_detail, }; payment_attempts.push(payment_attempt.clone()); Ok(payment_attempt) diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 024ab9fd814..5087e28b854 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -531,6 +531,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { customer_acceptance: payment_attempt.customer_acceptance.clone(), organization_id: payment_attempt.organization_id.clone(), profile_id: payment_attempt.profile_id.clone(), + connector_mandate_detail: payment_attempt.connector_mandate_detail.clone(), }; let field = format!("pa_{}", created_attempt.attempt_id); @@ -1453,6 +1454,7 @@ impl DataModelExt for PaymentAttempt { connector_transaction_data, shipping_cost: self.net_amount.get_shipping_cost(), order_tax_amount: self.net_amount.get_order_tax_amount(), + connector_mandate_detail: self.connector_mandate_detail, } } @@ -1528,6 +1530,7 @@ impl DataModelExt for PaymentAttempt { customer_acceptance: storage_model.customer_acceptance, organization_id: storage_model.organization_id, profile_id: storage_model.profile_id, + connector_mandate_detail: storage_model.connector_mandate_detail, } } } @@ -1610,6 +1613,7 @@ impl DataModelExt for PaymentAttemptNew { profile_id: self.profile_id, shipping_cost: self.net_amount.get_shipping_cost(), order_tax_amount: self.net_amount.get_order_tax_amount(), + connector_mandate_detail: self.connector_mandate_detail, } } @@ -1681,6 +1685,7 @@ impl DataModelExt for PaymentAttemptNew { customer_acceptance: storage_model.customer_acceptance, organization_id: storage_model.organization_id, profile_id: storage_model.profile_id, + connector_mandate_detail: storage_model.connector_mandate_detail, } } } diff --git a/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/down.sql b/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/down.sql new file mode 100644 index 00000000000..f4e6f2e2e26 --- /dev/null +++ b/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE + payment_attempt DROP COLUMN connector_mandate_detail; \ No newline at end of file diff --git a/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/up.sql b/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/up.sql new file mode 100644 index 00000000000..bb592f623d4 --- /dev/null +++ b/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/up.sql @@ -0,0 +1,5 @@ +-- Your SQL goes here +ALTER TABLE + payment_attempt +ADD + COLUMN connector_mandate_detail JSONB DEFAULT NULL; \ No newline at end of file
2024-10-15T17:41:53Z
## Description Earlier we used to store the connector mandate id irrespective of the payments status being charged or not for 3DS flows, now we would handle the connector_mandate_id updation in payment_method once and only if the payment has a status as charged. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? - Configure a MA and a MCA - Make a 3ds mandate failed payment, it would be populated in the payment_attempt, but not in the payment_method table ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: dev_5SpseUd7WAhIwgQeMpoCKwEeaPjmduquAv3Qu4VxdRkSBkilsq5arTZa6nXoPokw' \ --data-raw '{ "amount": 8500, "currency": "USD", "confirm": false, "customer_id": "CustomerX777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` ``` Confirm curl --location 'http://localhost:8080/payments/pay_v7bENZR0bgPe0g6ThobF/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: pk_dev_07feea3d36ed4f8da3cd844b07b8e3e9' \ --data '{ "confirm": true, "client_secret":"pay_v7bENZR0bgPe0g6ThobF_secret_d792ajlpJ4z6XlS9esjK", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4000008400001629", "card_exp_month": "06", "card_exp_year": "2030", "card_holder_name": "John T", "card_cvc": "737" } } }' ``` ``` Response { "payment_id": "pay_v7bENZR0bgPe0g6ThobF", "merchant_id": "merchant_1729155606", "status": "requires_customer_action", "amount": 8500, "net_amount": 8500, "amount_capturable": 8500, "amount_received": 0, "connector": "stripe", "client_secret": "pay_v7bENZR0bgPe0g6ThobF_secret_d792ajlpJ4z6XlS9esjK", "created": "2024-10-17T09:01:29.364Z", "currency": "USD", "customer_id": "CustomerX777", "customer": { "id": "CustomerX777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1629", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "06", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_v7bENZR0bgPe0g6ThobF/merchant_1729155606/pay_v7bENZR0bgPe0g6ThobF_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "pi_3QApaRD5R7gDAGff0khxOUA8", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pi_3QApaRD5R7gDAGff0khxOUA8", "payment_link": null, "profile_id": "pro_OYE7Iv9nauJb3HXYFB1u", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_LKJi6vdC2IEQwbEaVJQP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-17T09:16:29.364Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_PxUXcAinbE62hBE1mAg2", "payment_method_status": "inactive", "updated": "2024-10-17T09:01:39.749Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "pm_1QApaRD5R7gDAGffKM5cG6sU" } ``` ``` The payment_method_table won't have connectir_mandate_details ``` <img width="1725" alt="Screenshot 2024-10-17 at 2 48 01 PM" src="https://github.com/user-attachments/assets/c361f388-0c64-4b57-b5ff-ae8b4d5a3881"> - Make a 3ds payment successful, then only it will be populated in the payment_method ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: dev_5SpseUd7WAhIwgQeMpoCKwEeaPjmduquAv3Qu4VxdRkSBkilsq5arTZa6nXoPokw' \ --data-raw '{ "amount": 8500, "currency": "USD", "confirm": false, "customer_id": "CustomerX777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` ``` Confirm curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: dev_5SpseUd7WAhIwgQeMpoCKwEeaPjmduquAv3Qu4VxdRkSBkilsq5arTZa6nXoPokw' \ --data-raw '{ "amount": 8500, "currency": "USD", "confirm": false, "customer_id": "CustomerX777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` ``` response { "payment_id": "pay_m59xmko152RMgzTqgUeP", "merchant_id": "merchant_1729155606", "status": "succeeded", "amount": 8500, "net_amount": 8500, "amount_capturable": 0, "amount_received": 8500, "connector": "stripe", "client_secret": "pay_m59xmko152RMgzTqgUeP_secret_m8J1xt82aJYVaK4o4vNs", "created": "2024-10-17T09:18:18.049Z", "currency": "USD", "customer_id": "CustomerX777", "customer": { "id": "CustomerX777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "06", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3QApqiD5R7gDAGff1ykvxYD0", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pi_3QApqiD5R7gDAGff1ykvxYD0", "payment_link": null, "profile_id": "pro_OYE7Iv9nauJb3HXYFB1u", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_LKJi6vdC2IEQwbEaVJQP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-17T09:33:18.049Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_9ahIWQWjvWNTYCi1myPc", "payment_method_status": "active", "updated": "2024-10-17T09:18:35.865Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` The payment_method would have a connector_mandate_id with it <img width="1725" alt="Screenshot 2024-10-17 at 2 54 03 PM" src="https://github.com/user-attachments/assets/847ad97b-2cd0-4f48-a00f-8b833967df37"> - If another CIT mandate payment is made it wouldn't be populated anymore - Make a complete authorise mandate payment , it should be saved in the payment_method, for that mca_id - Make a external 3ds mandate payment , it should be saved in the payment_method, for that mca_id
962afbd084458e9afb11a0278a8210edd9226a3d
- Configure a MA and a MCA - Make a 3ds mandate failed payment, it would be populated in the payment_attempt, but not in the payment_method table ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: dev_5SpseUd7WAhIwgQeMpoCKwEeaPjmduquAv3Qu4VxdRkSBkilsq5arTZa6nXoPokw' \ --data-raw '{ "amount": 8500, "currency": "USD", "confirm": false, "customer_id": "CustomerX777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` ``` Confirm curl --location 'http://localhost:8080/payments/pay_v7bENZR0bgPe0g6ThobF/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: pk_dev_07feea3d36ed4f8da3cd844b07b8e3e9' \ --data '{ "confirm": true, "client_secret":"pay_v7bENZR0bgPe0g6ThobF_secret_d792ajlpJ4z6XlS9esjK", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4000008400001629", "card_exp_month": "06", "card_exp_year": "2030", "card_holder_name": "John T", "card_cvc": "737" } } }' ``` ``` Response { "payment_id": "pay_v7bENZR0bgPe0g6ThobF", "merchant_id": "merchant_1729155606", "status": "requires_customer_action", "amount": 8500, "net_amount": 8500, "amount_capturable": 8500, "amount_received": 0, "connector": "stripe", "client_secret": "pay_v7bENZR0bgPe0g6ThobF_secret_d792ajlpJ4z6XlS9esjK", "created": "2024-10-17T09:01:29.364Z", "currency": "USD", "customer_id": "CustomerX777", "customer": { "id": "CustomerX777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1629", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "06", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_v7bENZR0bgPe0g6ThobF/merchant_1729155606/pay_v7bENZR0bgPe0g6ThobF_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "pi_3QApaRD5R7gDAGff0khxOUA8", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pi_3QApaRD5R7gDAGff0khxOUA8", "payment_link": null, "profile_id": "pro_OYE7Iv9nauJb3HXYFB1u", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_LKJi6vdC2IEQwbEaVJQP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-17T09:16:29.364Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_PxUXcAinbE62hBE1mAg2", "payment_method_status": "inactive", "updated": "2024-10-17T09:01:39.749Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "pm_1QApaRD5R7gDAGffKM5cG6sU" } ``` ``` The payment_method_table won't have connectir_mandate_details ``` <img width="1725" alt="Screenshot 2024-10-17 at 2 48 01 PM" src="https://github.com/user-attachments/assets/c361f388-0c64-4b57-b5ff-ae8b4d5a3881"> - Make a 3ds payment successful, then only it will be populated in the payment_method ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: dev_5SpseUd7WAhIwgQeMpoCKwEeaPjmduquAv3Qu4VxdRkSBkilsq5arTZa6nXoPokw' \ --data-raw '{ "amount": 8500, "currency": "USD", "confirm": false, "customer_id": "CustomerX777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` ``` Confirm curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: dev_5SpseUd7WAhIwgQeMpoCKwEeaPjmduquAv3Qu4VxdRkSBkilsq5arTZa6nXoPokw' \ --data-raw '{ "amount": 8500, "currency": "USD", "confirm": false, "customer_id": "CustomerX777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` ``` response { "payment_id": "pay_m59xmko152RMgzTqgUeP", "merchant_id": "merchant_1729155606", "status": "succeeded", "amount": 8500, "net_amount": 8500, "amount_capturable": 0, "amount_received": 8500, "connector": "stripe", "client_secret": "pay_m59xmko152RMgzTqgUeP_secret_m8J1xt82aJYVaK4o4vNs", "created": "2024-10-17T09:18:18.049Z", "currency": "USD", "customer_id": "CustomerX777", "customer": { "id": "CustomerX777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "06", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3QApqiD5R7gDAGff1ykvxYD0", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pi_3QApqiD5R7gDAGff1ykvxYD0", "payment_link": null, "profile_id": "pro_OYE7Iv9nauJb3HXYFB1u", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_LKJi6vdC2IEQwbEaVJQP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-17T09:33:18.049Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_9ahIWQWjvWNTYCi1myPc", "payment_method_status": "active", "updated": "2024-10-17T09:18:35.865Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` The payment_method would have a connector_mandate_id with it <img width="1725" alt="Screenshot 2024-10-17 at 2 54 03 PM" src="https://github.com/user-attachments/assets/847ad97b-2cd0-4f48-a00f-8b833967df37"> - If another CIT mandate payment is made it wouldn't be populated anymore - Make a complete authorise mandate payment , it should be saved in the payment_method, for that mca_id - Make a external 3ds mandate payment , it should be saved in the payment_method, for that mca_id
[ "crates/common_enums/src/enums.rs", "crates/diesel_models/src/payment_attempt.rs", "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/schema_v2.rs", "crates/diesel_models/src/user/sample_data.rs", "crates/hyperswitch_domain_models/src/payments/payment_attempt.rs", "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/operations/payment_confirm.rs", "crates/router/src/core/payments/operations/payment_create.rs", "crates/router/src/core/payments/operations/payment_response.rs", "crates/router/src/core/payments/retry.rs", "crates/router/src/core/payments/tokenization.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/core/webhooks/incoming.rs", "crates/router/src/types/storage/payment_attempt.rs", "crates/router/src/types/storage/payment_method.rs", "crates/router/src/utils/user/sample_data.rs", "crates/storage_impl/src/mock_db/payment_attempt.rs", "crates/storage_impl/src/payments/payment_attempt.rs", "migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/down.sql", "migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/up.sql" ]
juspay/hyperswitch
juspay__hyperswitch-6336
Bug: Create an id type for API Key ID Currently `key_id` is a String. We need to create an `id_type` for it and migrate all occurrences accordingly
diff --git a/.typos.toml b/.typos.toml index 79c86a39c6b..d2ffb8a5b10 100644 --- a/.typos.toml +++ b/.typos.toml @@ -1,5 +1,8 @@ [default] check-filename = true +extend-ignore-identifiers-re = [ + "UE_[0-9]{3,4}", # Unified error codes +] [default.extend-identifiers] ABD = "ABD" # Aberdeenshire, UK ISO 3166-2 code @@ -38,7 +41,6 @@ ws2ipdef = "ws2ipdef" # WinSock Extension ws2tcpip = "ws2tcpip" # WinSock Extension ZAR = "ZAR" # South African Rand currency code JOD = "JOD" # Jordan currency code -UE_000 = "UE_000" #default unified error code [default.extend-words] diff --git a/crates/api_models/src/api_keys.rs b/crates/api_models/src/api_keys.rs index 65cc6b9a25a..d25cd989b0f 100644 --- a/crates/api_models/src/api_keys.rs +++ b/crates/api_models/src/api_keys.rs @@ -29,8 +29,8 @@ pub struct CreateApiKeyRequest { #[derive(Debug, Serialize, ToSchema)] pub struct CreateApiKeyResponse { /// The identifier for the API Key. - #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX")] - pub key_id: String, + #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] + pub key_id: common_utils::id_type::ApiKeyId, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] @@ -72,8 +72,8 @@ pub struct CreateApiKeyResponse { #[derive(Debug, Serialize, ToSchema)] pub struct RetrieveApiKeyResponse { /// The identifier for the API Key. - #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX")] - pub key_id: String, + #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] + pub key_id: common_utils::id_type::ApiKeyId, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] @@ -131,7 +131,8 @@ pub struct UpdateApiKeyRequest { pub expiration: Option<ApiKeyExpiration>, #[serde(skip_deserializing)] - pub key_id: String, + #[schema(value_type = String)] + pub key_id: common_utils::id_type::ApiKeyId, #[serde(skip_deserializing)] #[schema(value_type = String)] @@ -146,8 +147,8 @@ pub struct RevokeApiKeyResponse { pub merchant_id: common_utils::id_type::MerchantId, /// The identifier for the API Key. - #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX")] - pub key_id: String, + #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] + pub key_id: common_utils::id_type::ApiKeyId, /// Indicates whether the API key was revoked or not. #[schema(example = "true")] pub revoked: bool, diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 2b1571617e8..ffeff7f2f2a 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -40,6 +40,9 @@ pub enum ApiEventsType { BusinessProfile { profile_id: id_type::ProfileId, }, + ApiKey { + key_id: id_type::ApiKeyId, + }, User { user_id: String, }, @@ -124,10 +127,6 @@ impl_api_event_type!( ( String, id_type::MerchantId, - (id_type::MerchantId, String), - (id_type::MerchantId, &String), - (&id_type::MerchantId, &String), - (&String, &String), (Option<i64>, Option<i64>, String), (Option<i64>, Option<i64>, id_type::MerchantId), bool diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index 78e3841690a..c256559fc1c 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -3,6 +3,7 @@ use std::{borrow::Cow, fmt::Debug}; +mod api_key; mod customer; mod merchant; mod merchant_connector_account; @@ -14,6 +15,7 @@ mod routing; #[cfg(feature = "v2")] mod global_id; +pub use api_key::ApiKeyId; pub use customer::CustomerId; use diesel::{ backend::Backend, diff --git a/crates/common_utils/src/id_type/api_key.rs b/crates/common_utils/src/id_type/api_key.rs new file mode 100644 index 00000000000..f252846e6ac --- /dev/null +++ b/crates/common_utils/src/id_type/api_key.rs @@ -0,0 +1,46 @@ +crate::id_type!( + ApiKeyId, + "A type for key_id that can be used for API key IDs" +); +crate::impl_id_type_methods!(ApiKeyId, "key_id"); + +// This is to display the `ApiKeyId` as ApiKeyId(abcd) +crate::impl_debug_id_type!(ApiKeyId); +crate::impl_try_from_cow_str_id_type!(ApiKeyId, "key_id"); + +crate::impl_serializable_secret_id_type!(ApiKeyId); +crate::impl_queryable_id_type!(ApiKeyId); +crate::impl_to_sql_from_sql_id_type!(ApiKeyId); + +impl ApiKeyId { + /// Generate Api Key Id from prefix + pub fn generate_key_id(prefix: &'static str) -> Self { + Self(crate::generate_ref_id_with_default_length(prefix)) + } +} + +impl crate::events::ApiEventMetric for ApiKeyId { + fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { + Some(crate::events::ApiEventsType::ApiKey { + key_id: self.clone(), + }) + } +} + +impl crate::events::ApiEventMetric for (super::MerchantId, ApiKeyId) { + fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { + Some(crate::events::ApiEventsType::ApiKey { + key_id: self.1.clone(), + }) + } +} + +impl crate::events::ApiEventMetric for (&super::MerchantId, &ApiKeyId) { + fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { + Some(crate::events::ApiEventsType::ApiKey { + key_id: self.1.clone(), + }) + } +} + +crate::impl_default_id_type!(ApiKeyId, "key"); diff --git a/crates/diesel_models/src/api_keys.rs b/crates/diesel_models/src/api_keys.rs index 1781e65cded..7076bf597e0 100644 --- a/crates/diesel_models/src/api_keys.rs +++ b/crates/diesel_models/src/api_keys.rs @@ -9,7 +9,7 @@ use crate::schema::api_keys; )] #[diesel(table_name = api_keys, primary_key(key_id), check_for_backend(diesel::pg::Pg))] pub struct ApiKey { - pub key_id: String, + pub key_id: common_utils::id_type::ApiKeyId, pub merchant_id: common_utils::id_type::MerchantId, pub name: String, pub description: Option<String>, @@ -23,7 +23,7 @@ pub struct ApiKey { #[derive(Debug, Insertable)] #[diesel(table_name = api_keys)] pub struct ApiKeyNew { - pub key_id: String, + pub key_id: common_utils::id_type::ApiKeyId, pub merchant_id: common_utils::id_type::MerchantId, pub name: String, pub description: Option<String>, @@ -141,7 +141,7 @@ mod diesel_impl { // Tracking data by process_tracker #[derive(Default, Debug, Deserialize, Serialize, Clone)] pub struct ApiKeyExpiryTrackingData { - pub key_id: String, + pub key_id: common_utils::id_type::ApiKeyId, pub merchant_id: common_utils::id_type::MerchantId, pub api_key_name: String, pub prefix: String, diff --git a/crates/diesel_models/src/query/api_keys.rs b/crates/diesel_models/src/query/api_keys.rs index 5dd14501025..479e226c1d3 100644 --- a/crates/diesel_models/src/query/api_keys.rs +++ b/crates/diesel_models/src/query/api_keys.rs @@ -18,7 +18,7 @@ impl ApiKey { pub async fn update_by_merchant_id_key_id( conn: &PgPooledConn, merchant_id: common_utils::id_type::MerchantId, - key_id: String, + key_id: common_utils::id_type::ApiKeyId, api_key_update: ApiKeyUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< @@ -57,7 +57,7 @@ impl ApiKey { pub async fn revoke_by_merchant_id_key_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - key_id: &str, + key_id: &common_utils::id_type::ApiKeyId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, @@ -71,7 +71,7 @@ impl ApiKey { pub async fn find_optional_by_merchant_id_key_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - key_id: &str, + key_id: &common_utils::id_type::ApiKeyId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index 6e907dbd91b..de4a8931c78 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -13,7 +13,6 @@ use crate::{ routes::{metrics, SessionState}, services::{authentication, ApplicationResponse}, types::{api, storage, transformers::ForeignInto}, - utils, }; #[cfg(feature = "email")] @@ -63,9 +62,9 @@ impl PlaintextApiKey { Self(format!("{env}_{key}").into()) } - pub fn new_key_id() -> String { + pub fn new_key_id() -> common_utils::id_type::ApiKeyId { let env = router_env::env::prefix_for_env(); - utils::generate_id(consts::ID_LENGTH, env) + common_utils::id_type::ApiKeyId::generate_key_id(env) } pub fn prefix(&self) -> String { @@ -223,7 +222,7 @@ pub async fn add_api_key_expiry_task( expiry_reminder_days: expiry_reminder_days.clone(), }; - let process_tracker_id = generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str()); + let process_tracker_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, API_KEY_EXPIRY_NAME, @@ -241,7 +240,7 @@ pub async fn add_api_key_expiry_task( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( - "Failed while inserting API key expiry reminder to process_tracker: api_key_id: {}", + "Failed while inserting API key expiry reminder to process_tracker: {:?}", api_key.key_id ) })?; @@ -258,11 +257,11 @@ pub async fn add_api_key_expiry_task( pub async fn retrieve_api_key( state: SessionState, merchant_id: common_utils::id_type::MerchantId, - key_id: &str, + key_id: common_utils::id_type::ApiKeyId, ) -> RouterResponse<api::RetrieveApiKeyResponse> { let store = state.store.as_ref(); let api_key = store - .find_api_key_by_merchant_id_key_id_optional(&merchant_id, key_id) + .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable("Failed to retrieve API key")? @@ -388,7 +387,7 @@ pub async fn update_api_key_expiry_task( } } - let task_id = generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str()); + let task_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id); let task_ids = vec![task_id.clone()]; @@ -430,7 +429,7 @@ pub async fn update_api_key_expiry_task( pub async fn revoke_api_key( state: SessionState, merchant_id: &common_utils::id_type::MerchantId, - key_id: &str, + key_id: &common_utils::id_type::ApiKeyId, ) -> RouterResponse<api::RevokeApiKeyResponse> { let store = state.store.as_ref(); @@ -496,7 +495,7 @@ pub async fn revoke_api_key( #[instrument(skip_all)] pub async fn revoke_api_key_expiry_task( store: &dyn crate::db::StorageInterface, - key_id: &str, + key_id: &common_utils::id_type::ApiKeyId, ) -> Result<(), errors::ProcessTrackerError> { let task_id = generate_task_id_for_api_key_expiry_workflow(key_id); let task_ids = vec![task_id]; @@ -535,8 +534,13 @@ pub async fn list_api_keys( } #[cfg(feature = "email")] -fn generate_task_id_for_api_key_expiry_workflow(key_id: &str) -> String { - format!("{API_KEY_EXPIRY_RUNNER}_{API_KEY_EXPIRY_NAME}_{key_id}") +fn generate_task_id_for_api_key_expiry_workflow( + key_id: &common_utils::id_type::ApiKeyId, +) -> String { + format!( + "{API_KEY_EXPIRY_RUNNER}_{API_KEY_EXPIRY_NAME}_{}", + key_id.get_string_repr() + ) } impl From<&str> for PlaintextApiKey { diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs index 62d261aa3c4..0d3ec5dc8c2 100644 --- a/crates/router/src/db/api_keys.rs +++ b/crates/router/src/db/api_keys.rs @@ -20,20 +20,20 @@ pub trait ApiKeyInterface { async fn update_api_key( &self, merchant_id: common_utils::id_type::MerchantId, - key_id: String, + key_id: common_utils::id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError>; async fn revoke_api_key( &self, merchant_id: &common_utils::id_type::MerchantId, - key_id: &str, + key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError>; async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &common_utils::id_type::MerchantId, - key_id: &str, + key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>; async fn find_api_key_by_hash_optional( @@ -67,7 +67,7 @@ impl ApiKeyInterface for Store { async fn update_api_key( &self, merchant_id: common_utils::id_type::MerchantId, - key_id: String, + key_id: common_utils::id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; @@ -99,7 +99,8 @@ impl ApiKeyInterface for Store { .await .map_err(|error| report!(errors::StorageError::from(error)))? .ok_or(report!(errors::StorageError::ValueNotFound(format!( - "ApiKey of {_key_id} not found" + "ApiKey of {} not found", + _key_id.get_string_repr() ))))?; cache::publish_and_redact( @@ -115,7 +116,7 @@ impl ApiKeyInterface for Store { async fn revoke_api_key( &self, merchant_id: &common_utils::id_type::MerchantId, - key_id: &str, + key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let delete_call = || async { @@ -141,7 +142,8 @@ impl ApiKeyInterface for Store { .await .map_err(|error| report!(errors::StorageError::from(error)))? .ok_or(report!(errors::StorageError::ValueNotFound(format!( - "ApiKey of {key_id} not found" + "ApiKey of {} not found", + key_id.get_string_repr() ))))?; cache::publish_and_redact( @@ -157,7 +159,7 @@ impl ApiKeyInterface for Store { async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &common_utils::id_type::MerchantId, - key_id: &str, + key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::ApiKey::find_optional_by_merchant_id_key_id(&conn, merchant_id, key_id) @@ -240,7 +242,7 @@ impl ApiKeyInterface for MockDb { async fn update_api_key( &self, merchant_id: common_utils::id_type::MerchantId, - key_id: String, + key_id: common_utils::id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let mut locked_api_keys = self.api_keys.lock().await; @@ -282,13 +284,13 @@ impl ApiKeyInterface for MockDb { async fn revoke_api_key( &self, merchant_id: &common_utils::id_type::MerchantId, - key_id: &str, + key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError> { let mut locked_api_keys = self.api_keys.lock().await; // find the key to remove, if it exists if let Some(pos) = locked_api_keys .iter() - .position(|k| k.merchant_id == *merchant_id && k.key_id == key_id) + .position(|k| k.merchant_id == *merchant_id && k.key_id == *key_id) { // use `remove` instead of `swap_remove` so we have a consistent order, which might // matter to someone using limit/offset in `list_api_keys_by_merchant_id` @@ -302,14 +304,14 @@ impl ApiKeyInterface for MockDb { async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &common_utils::id_type::MerchantId, - key_id: &str, + key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { Ok(self .api_keys .lock() .await .iter() - .find(|k| k.merchant_id == *merchant_id && k.key_id == key_id) + .find(|k| k.merchant_id == *merchant_id && k.key_id == *key_id) .cloned()) } @@ -397,9 +399,16 @@ mod tests { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant1")).unwrap(); + let key_id1 = common_utils::id_type::ApiKeyId::try_from(Cow::from("key_id1")).unwrap(); + + let key_id2 = common_utils::id_type::ApiKeyId::try_from(Cow::from("key_id2")).unwrap(); + + let non_existent_key_id = + common_utils::id_type::ApiKeyId::try_from(Cow::from("does_not_exist")).unwrap(); + let key1 = mockdb .insert_api_key(storage::ApiKeyNew { - key_id: "key_id1".into(), + key_id: key_id1.clone(), merchant_id: merchant_id.clone(), name: "Key 1".into(), description: None, @@ -414,7 +423,7 @@ mod tests { mockdb .insert_api_key(storage::ApiKeyNew { - key_id: "key_id2".into(), + key_id: key_id2.clone(), merchant_id: merchant_id.clone(), name: "Key 2".into(), description: None, @@ -428,13 +437,13 @@ mod tests { .unwrap(); let found_key1 = mockdb - .find_api_key_by_merchant_id_key_id_optional(&merchant_id, "key_id1") + .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id1) .await .unwrap() .unwrap(); assert_eq!(found_key1.key_id, key1.key_id); assert!(mockdb - .find_api_key_by_merchant_id_key_id_optional(&merchant_id, "does_not_exist") + .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &non_existent_key_id) .await .unwrap() .is_none()); @@ -442,7 +451,7 @@ mod tests { mockdb .update_api_key( merchant_id.clone(), - "key_id1".into(), + key_id1.clone(), storage::ApiKeyUpdate::LastUsedUpdate { last_used: datetime!(2023-02-04 1:11), }, @@ -450,7 +459,7 @@ mod tests { .await .unwrap(); let updated_key1 = mockdb - .find_api_key_by_merchant_id_key_id_optional(&merchant_id, "key_id1") + .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id1) .await .unwrap() .unwrap(); @@ -464,10 +473,7 @@ mod tests { .len(), 2 ); - mockdb - .revoke_api_key(&merchant_id, "key_id1") - .await - .unwrap(); + mockdb.revoke_api_key(&merchant_id, &key_id1).await.unwrap(); assert_eq!( mockdb .list_api_keys_by_merchant_id(&merchant_id, None, None) @@ -495,8 +501,10 @@ mod tests { .await .unwrap(); + let test_key = common_utils::id_type::ApiKeyId::try_from(Cow::from("test_ey")).unwrap(); + let api = storage::ApiKeyNew { - key_id: "test_key".into(), + key_id: test_key.clone(), merchant_id: merchant_id.clone(), name: "My test key".into(), description: None, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 6e9daeedc59..208cd8d5f97 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -226,7 +226,7 @@ impl ApiKeyInterface for KafkaStore { async fn update_api_key( &self, merchant_id: id_type::MerchantId, - key_id: String, + key_id: id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { self.diesel_store @@ -237,7 +237,7 @@ impl ApiKeyInterface for KafkaStore { async fn revoke_api_key( &self, merchant_id: &id_type::MerchantId, - key_id: &str, + key_id: &id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store.revoke_api_key(merchant_id, key_id).await } @@ -245,7 +245,7 @@ impl ApiKeyInterface for KafkaStore { async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &id_type::MerchantId, - key_id: &str, + key_id: &id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { self.diesel_store .find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id) diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 047e0d9b886..bbecaae9e80 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -79,7 +79,7 @@ pub async fn api_key_create( pub async fn api_key_retrieve( state: web::Data<AppState>, req: HttpRequest, - path: web::Path<String>, + path: web::Path<common_utils::id_type::ApiKeyId>, ) -> impl Responder { let flow = Flow::ApiKeyRetrieve; let key_id = path.into_inner(); @@ -93,7 +93,7 @@ pub async fn api_key_retrieve( api_keys::retrieve_api_key( state, auth_data.merchant_account.get_id().to_owned(), - key_id, + key_id.to_owned(), ) }, auth::auth_type( @@ -114,7 +114,10 @@ pub async fn api_key_retrieve( pub async fn api_key_retrieve( state: web::Data<AppState>, req: HttpRequest, - path: web::Path<(common_utils::id_type::MerchantId, String)>, + path: web::Path<( + common_utils::id_type::MerchantId, + common_utils::id_type::ApiKeyId, + )>, ) -> impl Responder { let flow = Flow::ApiKeyRetrieve; let (merchant_id, key_id) = path.into_inner(); @@ -123,7 +126,7 @@ pub async fn api_key_retrieve( flow, state, &req, - (merchant_id.clone(), &key_id), + (merchant_id.clone(), key_id.clone()), |state, _, (merchant_id, key_id), _| api_keys::retrieve_api_key(state, merchant_id, key_id), auth::auth_type( &auth::AdminApiAuth, @@ -144,7 +147,10 @@ pub async fn api_key_retrieve( pub async fn api_key_update( state: web::Data<AppState>, req: HttpRequest, - path: web::Path<(common_utils::id_type::MerchantId, String)>, + path: web::Path<( + common_utils::id_type::MerchantId, + common_utils::id_type::ApiKeyId, + )>, json_payload: web::Json<api_types::UpdateApiKeyRequest>, ) -> impl Responder { let flow = Flow::ApiKeyUpdate; @@ -177,7 +183,7 @@ pub async fn api_key_update( pub async fn api_key_update( state: web::Data<AppState>, req: HttpRequest, - key_id: web::Path<String>, + key_id: web::Path<common_utils::id_type::ApiKeyId>, json_payload: web::Json<api_types::UpdateApiKeyRequest>, ) -> impl Responder { let flow = Flow::ApiKeyUpdate; @@ -212,7 +218,10 @@ pub async fn api_key_update( pub async fn api_key_revoke( state: web::Data<AppState>, req: HttpRequest, - path: web::Path<(common_utils::id_type::MerchantId, String)>, + path: web::Path<( + common_utils::id_type::MerchantId, + common_utils::id_type::ApiKeyId, + )>, ) -> impl Responder { let flow = Flow::ApiKeyRevoke; let (merchant_id, key_id) = path.into_inner(); @@ -242,7 +251,10 @@ pub async fn api_key_revoke( pub async fn api_key_revoke( state: web::Data<AppState>, req: HttpRequest, - path: web::Path<(common_utils::id_type::MerchantId, String)>, + path: web::Path<( + common_utils::id_type::MerchantId, + common_utils::id_type::ApiKeyId, + )>, ) -> impl Responder { let flow = Flow::ApiKeyRevoke; let (merchant_id, key_id) = path.into_inner(); diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 3731d8ee081..9be4c493874 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -82,7 +82,7 @@ pub struct AuthenticationDataWithUser { pub enum AuthenticationType { ApiKey { merchant_id: id_type::MerchantId, - key_id: String, + key_id: id_type::ApiKeyId, }, AdminApiKey, AdminApiAuthWithMerchantId { diff --git a/crates/router/src/services/authentication/decision.rs b/crates/router/src/services/authentication/decision.rs index d665b0caaf4..c31a4696bc9 100644 --- a/crates/router/src/services/authentication/decision.rs +++ b/crates/router/src/services/authentication/decision.rs @@ -67,7 +67,7 @@ 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: String, + 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 }, @@ -80,7 +80,7 @@ pub async fn add_api_key( state: &SessionState, api_key: Secret<String>, merchant_id: common_utils::id_type::MerchantId, - key_id: String, + key_id: common_utils::id_type::ApiKeyId, expiry: Option<u64>, ) -> CustomResult<(), ApiClientError> { let decision_config = if let Some(config) = &state.conf.decision { diff --git a/crates/router/src/services/authentication/detached.rs b/crates/router/src/services/authentication/detached.rs index af373d3e559..9d77d2b1f07 100644 --- a/crates/router/src/services/authentication/detached.rs +++ b/crates/router/src/services/authentication/detached.rs @@ -1,7 +1,10 @@ use std::{borrow::Cow, string::ToString}; use actix_web::http::header::HeaderMap; -use common_utils::{crypto::VerifySignature, id_type::MerchantId}; +use common_utils::{ + crypto::VerifySignature, + id_type::{ApiKeyId, MerchantId}, +}; use error_stack::ResultExt; use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; @@ -16,7 +19,7 @@ const HEADER_CHECKSUM: &str = "x-checksum"; pub struct ExtractedPayload { pub payload_type: PayloadType, pub merchant_id: Option<MerchantId>, - pub key_id: Option<String>, + pub key_id: Option<ApiKeyId>, } #[derive(strum::EnumString, strum::Display, PartialEq, Debug)] @@ -61,13 +64,19 @@ impl ExtractedPayload { 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: headers - .get(HEADER_KEY_ID) - .and_then(|v| v.to_str().ok()) - .map(|v| v.to_string()), + key_id, }) } @@ -95,7 +104,7 @@ impl ExtractedPayload { &self .merchant_id .as_ref() - .map(|inner| append_option(inner.get_string_repr(), &self.key_id)), + .map(|inner| append_api_key(inner.get_string_repr(), &self.key_id)), ) } } @@ -107,3 +116,11 @@ fn append_option(prefix: &str, data: &Option<String>) -> String { 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(), + } +}
2024-10-15T12:16:41Z
## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1a. Create API key ``` curl --location 'http://localhost:8080/api_keys/merchant_1729063721' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "API Key 1", "description": null, "expiration": "2038-01-19T03:14:08.000Z" }' ``` 1b. Response ```json { "key_id": "dev_ZfucbDHJm7pbcFjsoq5I", "merchant_id": "merchant_1729063721", "name": "API Key 1", "description": null, "api_key": "dev_sNyAhsbOkEYtuuUvMOzlTIMpTZ3Kd9AC5sboxRuQOMX5xKyqTDn0oG9Vaq4XGwN1", "created": "2024-10-16T07:28:44.906Z", "expiration": "2038-01-19T03:14:08.000Z" } ``` 2a. Update API Key ``` curl --location 'http://localhost:8080/api_keys/merchant_1729063721/dev_ZfucbDHJm7pbcFjsoq5I' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": null, "description": "My very awesome API key", "expiration": null }' ``` 2b. Reponse ```json { "key_id": "dev_ZfucbDHJm7pbcFjsoq5I", "merchant_id": "merchant_1729063721", "name": "API Key 1", "description": "My very awesome API key", "prefix": "dev_sNyAhsbO", "created": "2024-10-16T07:28:44.906Z", "expiration": "2038-01-19T03:14:08.000Z" } ``` 3a. Retrieve API Key ``` curl --location 'http://localhost:8080/api_keys/merchant_1729063721/dev_ZfucbDHJm7pbcFjsoq5I' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` 3b. Response ```json { "key_id": "dev_ZfucbDHJm7pbcFjsoq5I", "merchant_id": "merchant_1729063721", "name": "API Key 1", "description": "My very awesome API key", "prefix": "dev_sNyAhsbO", "created": "2024-10-16T07:28:44.906Z", "expiration": "2038-01-19T03:14:08.000Z" } ``` 4a. Delete API Key ``` curl --location --request DELETE 'http://localhost:8080/api_keys/merchant_1729063721/dev_ZfucbDHJm7pbcFjsoq5I' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` 4b. Response ```json { "merchant_id": "merchant_1729063721", "key_id": "dev_ZfucbDHJm7pbcFjsoq5I", "revoked": true } ``` 5a. List API Keys ``` curl --location 'http://localhost:8080/api_keys/merchant_1729063721/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` 5b. Response ```json [ { "key_id": "dev_kKu6dWq8k3ZwWOfsS3fi", "merchant_id": "merchant_1729063721", "name": "API Key 1", "description": null, "prefix": "dev_6gvWcG7g", "created": "2024-10-16T07:32:48.698Z", "expiration": "2038-01-19T03:14:08.000Z" }, { "key_id": "dev_f1PMFHmWHi2v0fmZp7t2", "merchant_id": "merchant_1729063721", "name": "API Key 2", "description": null, "prefix": "dev_jSU9qvIU", "created": "2024-10-16T07:32:54.057Z", "expiration": "2038-01-19T03:14:08.000Z" } ] ```
899ec23565f99daaad821c1ec1482b4c0cc408c5
1a. Create API key ``` curl --location 'http://localhost:8080/api_keys/merchant_1729063721' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "API Key 1", "description": null, "expiration": "2038-01-19T03:14:08.000Z" }' ``` 1b. Response ```json { "key_id": "dev_ZfucbDHJm7pbcFjsoq5I", "merchant_id": "merchant_1729063721", "name": "API Key 1", "description": null, "api_key": "dev_sNyAhsbOkEYtuuUvMOzlTIMpTZ3Kd9AC5sboxRuQOMX5xKyqTDn0oG9Vaq4XGwN1", "created": "2024-10-16T07:28:44.906Z", "expiration": "2038-01-19T03:14:08.000Z" } ``` 2a. Update API Key ``` curl --location 'http://localhost:8080/api_keys/merchant_1729063721/dev_ZfucbDHJm7pbcFjsoq5I' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": null, "description": "My very awesome API key", "expiration": null }' ``` 2b. Reponse ```json { "key_id": "dev_ZfucbDHJm7pbcFjsoq5I", "merchant_id": "merchant_1729063721", "name": "API Key 1", "description": "My very awesome API key", "prefix": "dev_sNyAhsbO", "created": "2024-10-16T07:28:44.906Z", "expiration": "2038-01-19T03:14:08.000Z" } ``` 3a. Retrieve API Key ``` curl --location 'http://localhost:8080/api_keys/merchant_1729063721/dev_ZfucbDHJm7pbcFjsoq5I' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` 3b. Response ```json { "key_id": "dev_ZfucbDHJm7pbcFjsoq5I", "merchant_id": "merchant_1729063721", "name": "API Key 1", "description": "My very awesome API key", "prefix": "dev_sNyAhsbO", "created": "2024-10-16T07:28:44.906Z", "expiration": "2038-01-19T03:14:08.000Z" } ``` 4a. Delete API Key ``` curl --location --request DELETE 'http://localhost:8080/api_keys/merchant_1729063721/dev_ZfucbDHJm7pbcFjsoq5I' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` 4b. Response ```json { "merchant_id": "merchant_1729063721", "key_id": "dev_ZfucbDHJm7pbcFjsoq5I", "revoked": true } ``` 5a. List API Keys ``` curl --location 'http://localhost:8080/api_keys/merchant_1729063721/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` 5b. Response ```json [ { "key_id": "dev_kKu6dWq8k3ZwWOfsS3fi", "merchant_id": "merchant_1729063721", "name": "API Key 1", "description": null, "prefix": "dev_6gvWcG7g", "created": "2024-10-16T07:32:48.698Z", "expiration": "2038-01-19T03:14:08.000Z" }, { "key_id": "dev_f1PMFHmWHi2v0fmZp7t2", "merchant_id": "merchant_1729063721", "name": "API Key 2", "description": null, "prefix": "dev_jSU9qvIU", "created": "2024-10-16T07:32:54.057Z", "expiration": "2038-01-19T03:14:08.000Z" } ] ```
[ ".typos.toml", "crates/api_models/src/api_keys.rs", "crates/common_utils/src/events.rs", "crates/common_utils/src/id_type.rs", "crates/common_utils/src/id_type/api_key.rs", "crates/diesel_models/src/api_keys.rs", "crates/diesel_models/src/query/api_keys.rs", "crates/router/src/core/api_keys.rs", "crates/router/src/db/api_keys.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/routes/api_keys.rs", "crates/router/src/services/authentication.rs", "crates/router/src/services/authentication/decision.rs", "crates/router/src/services/authentication/detached.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6321
Bug: [BUG] Various errors in `rust_locker_open_api_spec.yml` ### Bug Description The two identical files [`api-reference/rust_locker_open_api_spec.yml`](https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference/rust_locker_open_api_spec.yml) and [`api-reference-v2/rust_locker_open_api_spec.yml`](https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference-v2/rust_locker_open_api_spec.yml) contain some mistakes and errors. ### Expected Behavior The documentation should be clear. ### Actual Behavior The documentation contains some errors. ### Steps To Reproduce Not relevant. ### Context For The Bug Some examples: https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference/rust_locker_open_api_spec.yml#L5 https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference/rust_locker_open_api_spec.yml#L12 https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference/rust_locker_open_api_spec.yml#L14 https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference/rust_locker_open_api_spec.yml#L42 ### Environment Not relevant. ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/rust_locker_open_api_spec.yml b/api-reference-v2/rust_locker_open_api_spec.yml index 729886d9cd0..17a19fec44d 100644 --- a/api-reference-v2/rust_locker_open_api_spec.yml +++ b/api-reference-v2/rust_locker_open_api_spec.yml @@ -2,16 +2,16 @@ openapi: "3.0.2" info: title: Tartarus - OpenAPI 3.0 description: |- - This the the open API 3.0 specification for the card locker. + This is the OpenAPI 3.0 specification for the card locker. This is used by the [hyperswitch](https://github.com/juspay/hyperswitch) for storing card information securely. version: "1.0" tags: - name: Key Custodian description: API used to initialize the locker after deployment. - name: Data - description: CRUD APIs to for working with data to be stored in the locker + description: CRUD APIs for working with data to be stored in the locker - name: Cards - description: CRUD APIs to for working with cards data to be stored in the locker (deprecated) + description: CRUD APIs for working with cards data to be stored in the locker (deprecated) paths: /custodian/key1: post: @@ -39,7 +39,7 @@ paths: tags: - Key Custodian summary: Provide Key 2 - description: Provide the first key to unlock the locker + description: Provide the second key to unlock the locker operationId: setKey2 requestBody: description: Provide key 2 to unlock the locker
2024-10-15T10:54:46Z
## Description <!-- Describe your changes in detail --> Improved wording in the edit files. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #6321. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manually inspected the changed files.
e5710fa084ed5b0a4969a63b14a7f8e3433a3c64
Manually inspected the changed files.
[ "api-reference-v2/rust_locker_open_api_spec.yml" ]
juspay/hyperswitch
juspay__hyperswitch-6318
Bug: docs: Adding Unified error codes to the API - Ref Adding Unified error codes to the API - Ref
2024-10-15T10:13:17Z
## Description <!-- Describe your changes in detail --> Helps closing - #6318 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
d06d19fc96e1a74d20e2fe3613f86d541947e0ae
[]
juspay/hyperswitch
juspay__hyperswitch-6314
Bug: [FEAT] add a macro to derive ToEncryptable trait
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index eb196a72074..4f6411a42cd 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -1,12 +1,5 @@ -use common_utils::{ - crypto, custom_serde, - encryption::Encryption, - id_type, - pii::{self, EmailStrategy}, - types::{keymanager::ToEncryptable, Description}, -}; -use masking::{ExposeInterface, Secret, SwitchStrategy}; -use rustc_hash::FxHashMap; +use common_utils::{crypto, custom_serde, id_type, pii, types::Description}; +use masking::Secret; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -129,85 +122,6 @@ impl CustomerRequest { } } -pub struct CustomerRequestWithEmail { - pub name: Option<Secret<String>>, - pub email: Option<pii::Email>, - pub phone: Option<Secret<String>>, -} - -pub struct CustomerRequestWithEncryption { - pub name: Option<Encryption>, - pub phone: Option<Encryption>, - pub email: Option<Encryption>, -} - -pub struct EncryptableCustomer { - pub name: crypto::OptionalEncryptableName, - pub phone: crypto::OptionalEncryptablePhone, - pub email: crypto::OptionalEncryptableEmail, -} - -impl ToEncryptable<EncryptableCustomer, Secret<String>, Encryption> - for CustomerRequestWithEncryption -{ - fn to_encryptable(self) -> FxHashMap<String, Encryption> { - let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default()); - self.name.map(|x| map.insert("name".to_string(), x)); - self.phone.map(|x| map.insert("phone".to_string(), x)); - self.email.map(|x| map.insert("email".to_string(), x)); - map - } - - fn from_encryptable( - mut hashmap: FxHashMap<String, crypto::Encryptable<Secret<String>>>, - ) -> common_utils::errors::CustomResult<EncryptableCustomer, common_utils::errors::ParsingError> - { - Ok(EncryptableCustomer { - name: hashmap.remove("name"), - phone: hashmap.remove("phone"), - email: hashmap.remove("email").map(|email| { - let encryptable: crypto::Encryptable<Secret<String, EmailStrategy>> = - crypto::Encryptable::new( - email.clone().into_inner().switch_strategy(), - email.into_encrypted(), - ); - encryptable - }), - }) - } -} - -impl ToEncryptable<EncryptableCustomer, Secret<String>, Secret<String>> - for CustomerRequestWithEmail -{ - fn to_encryptable(self) -> FxHashMap<String, Secret<String>> { - let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default()); - self.name.map(|x| map.insert("name".to_string(), x)); - self.phone.map(|x| map.insert("phone".to_string(), x)); - self.email - .map(|x| map.insert("email".to_string(), x.expose().switch_strategy())); - map - } - - fn from_encryptable( - mut hashmap: FxHashMap<String, crypto::Encryptable<Secret<String>>>, - ) -> common_utils::errors::CustomResult<EncryptableCustomer, common_utils::errors::ParsingError> - { - Ok(EncryptableCustomer { - name: hashmap.remove("name"), - email: hashmap.remove("email").map(|email| { - let encryptable: crypto::Encryptable<Secret<String, EmailStrategy>> = - crypto::Encryptable::new( - email.clone().into_inner().switch_strategy(), - email.into_encrypted(), - ); - encryptable - }), - phone: hashmap.remove("phone"), - }) - } -} - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct CustomerResponse { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 2e31c0ba258..4efc2e8d960 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -12,13 +12,12 @@ use common_utils::{ ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, - pii::{self, Email, EmailStrategy}, - types::{keymanager::ToEncryptable, MinorUnit, StringMajorUnit}, + pii::{self, Email}, + types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; -use masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy, WithType}; +use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; -use rustc_hash::FxHashMap; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; @@ -3763,54 +3762,6 @@ pub struct EncryptableAddressDetails { pub email: crypto::OptionalEncryptableEmail, } -impl ToEncryptable<EncryptableAddressDetails, Secret<String>, Secret<String>> - for AddressDetailsWithPhone -{ - fn from_encryptable( - mut hashmap: FxHashMap<String, crypto::Encryptable<Secret<String>>>, - ) -> common_utils::errors::CustomResult< - EncryptableAddressDetails, - common_utils::errors::ParsingError, - > { - Ok(EncryptableAddressDetails { - line1: hashmap.remove("line1"), - line2: hashmap.remove("line2"), - line3: hashmap.remove("line3"), - state: hashmap.remove("state"), - zip: hashmap.remove("zip"), - first_name: hashmap.remove("first_name"), - last_name: hashmap.remove("last_name"), - phone_number: hashmap.remove("phone_number"), - email: hashmap.remove("email").map(|x| { - let inner: Secret<String, EmailStrategy> = x.clone().into_inner().switch_strategy(); - crypto::Encryptable::new(inner, x.into_encrypted()) - }), - }) - } - - fn to_encryptable(self) -> FxHashMap<String, Secret<String>> { - let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default()); - self.address.map(|address| { - address.line1.map(|x| map.insert("line1".to_string(), x)); - address.line2.map(|x| map.insert("line2".to_string(), x)); - address.line3.map(|x| map.insert("line3".to_string(), x)); - address.state.map(|x| map.insert("state".to_string(), x)); - address.zip.map(|x| map.insert("zip".to_string(), x)); - address - .first_name - .map(|x| map.insert("first_name".to_string(), x)); - address - .last_name - .map(|x| map.insert("last_name".to_string(), x)); - }); - self.email - .map(|x| map.insert("email".to_string(), x.expose().switch_strategy())); - self.phone_number - .map(|x| map.insert("phone_number".to_string(), x)); - map - } -} - #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number diff --git a/crates/diesel_models/src/address.rs b/crates/diesel_models/src/address.rs index a1cfb668716..06b82cb2c20 100644 --- a/crates/diesel_models/src/address.rs +++ b/crates/diesel_models/src/address.rs @@ -1,12 +1,5 @@ -use common_utils::{ - crypto::{self, Encryptable}, - encryption::Encryption, - pii::EmailStrategy, - types::keymanager::ToEncryptable, -}; +use common_utils::{crypto, encryption::Encryption}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; -use masking::{Secret, SwitchStrategy}; -use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -74,48 +67,6 @@ pub struct EncryptableAddress { pub email: crypto::OptionalEncryptableEmail, } -impl ToEncryptable<EncryptableAddress, Secret<String>, Encryption> for Address { - fn to_encryptable(self) -> FxHashMap<String, Encryption> { - let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default()); - self.line1.map(|x| map.insert("line1".to_string(), x)); - self.line2.map(|x| map.insert("line2".to_string(), x)); - self.line3.map(|x| map.insert("line3".to_string(), x)); - self.zip.map(|x| map.insert("zip".to_string(), x)); - self.state.map(|x| map.insert("state".to_string(), x)); - self.first_name - .map(|x| map.insert("first_name".to_string(), x)); - self.last_name - .map(|x| map.insert("last_name".to_string(), x)); - self.phone_number - .map(|x| map.insert("phone_number".to_string(), x)); - self.email.map(|x| map.insert("email".to_string(), x)); - map - } - - fn from_encryptable( - mut hashmap: FxHashMap<String, Encryptable<Secret<String>>>, - ) -> common_utils::errors::CustomResult<EncryptableAddress, common_utils::errors::ParsingError> - { - Ok(EncryptableAddress { - line1: hashmap.remove("line1"), - line2: hashmap.remove("line2"), - line3: hashmap.remove("line3"), - zip: hashmap.remove("zip"), - state: hashmap.remove("state"), - first_name: hashmap.remove("first_name"), - last_name: hashmap.remove("last_name"), - phone_number: hashmap.remove("phone_number"), - email: hashmap.remove("email").map(|email| { - let encryptable: Encryptable<Secret<String, EmailStrategy>> = Encryptable::new( - email.clone().into_inner().switch_strategy(), - email.into_encrypted(), - ); - encryptable - }), - }) - } -} - #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = address)] pub struct AddressUpdateInternal { diff --git a/crates/diesel_models/src/events.rs b/crates/diesel_models/src/events.rs index b6c5efe0fd1..82b2b58f80b 100644 --- a/crates/diesel_models/src/events.rs +++ b/crates/diesel_models/src/events.rs @@ -1,11 +1,7 @@ -use common_utils::{ - crypto::OptionalEncryptableSecretString, custom_serde, encryption::Encryption, - types::keymanager::ToEncryptable, -}; +use common_utils::{custom_serde, encryption::Encryption}; use diesel::{ expression::AsExpression, AsChangeset, Identifiable, Insertable, Queryable, Selectable, }; -use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -63,38 +59,6 @@ pub struct Event { pub metadata: Option<EventMetadata>, } -pub struct EventWithEncryption { - pub request: Option<Encryption>, - pub response: Option<Encryption>, -} - -pub struct EncryptableEvent { - pub request: OptionalEncryptableSecretString, - pub response: OptionalEncryptableSecretString, -} - -impl ToEncryptable<EncryptableEvent, Secret<String>, Encryption> for EventWithEncryption { - fn to_encryptable(self) -> rustc_hash::FxHashMap<String, Encryption> { - let mut map = rustc_hash::FxHashMap::default(); - self.request.map(|x| map.insert("request".to_string(), x)); - self.response.map(|x| map.insert("response".to_string(), x)); - map - } - - fn from_encryptable( - mut hashmap: rustc_hash::FxHashMap< - String, - common_utils::crypto::Encryptable<Secret<String>>, - >, - ) -> common_utils::errors::CustomResult<EncryptableEvent, common_utils::errors::ParsingError> - { - Ok(EncryptableEvent { - request: hashmap.remove("request"), - response: hashmap.remove("response"), - }) - } -} - #[derive(Clone, Debug, Deserialize, Serialize, AsExpression, diesel::FromSqlRow)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub enum EventMetadata { diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs index 9f079f1312e..71cb4ebc2f9 100644 --- a/crates/hyperswitch_domain_models/src/customer.rs +++ b/crates/hyperswitch_domain_models/src/customer.rs @@ -1,8 +1,8 @@ -use api_models::customers::CustomerRequestWithEncryption; #[cfg(all(feature = "v2", feature = "customer_v2"))] use common_enums::DeleteStatus; use common_utils::{ - crypto, date_time, + crypto::{self, Encryptable}, + date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, id_type, pii, @@ -13,19 +13,23 @@ use common_utils::{ }; use diesel_models::customers::CustomerUpdateInternal; use error_stack::ResultExt; -use masking::{PeekInterface, Secret}; +use masking::{PeekInterface, Secret, SwitchStrategy}; +use rustc_hash::FxHashMap; use time::PrimitiveDateTime; use crate::type_encryption as types; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] -#[derive(Clone, Debug)] +#[derive(Clone, Debug, router_derive::ToEncryption)] pub struct Customer { pub customer_id: id_type::CustomerId, pub merchant_id: id_type::MerchantId, - pub name: crypto::OptionalEncryptableName, - pub email: crypto::OptionalEncryptableEmail, - pub phone: crypto::OptionalEncryptablePhone, + #[encrypt] + pub name: Option<Encryptable<Secret<String>>>, + #[encrypt] + pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>, + #[encrypt] + pub phone: Option<Encryptable<Secret<String>>>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, @@ -39,12 +43,15 @@ pub struct Customer { } #[cfg(all(feature = "v2", feature = "customer_v2"))] -#[derive(Clone, Debug)] +#[derive(Clone, Debug, router_derive::ToEncryption)] pub struct Customer { pub merchant_id: id_type::MerchantId, - pub name: crypto::OptionalEncryptableName, - pub email: crypto::OptionalEncryptableEmail, - pub phone: crypto::OptionalEncryptablePhone, + #[encrypt] + pub name: Option<Encryptable<Secret<String>>>, + #[encrypt] + pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>, + #[encrypt] + pub phone: Option<Encryptable<Secret<String>>>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, @@ -98,8 +105,8 @@ impl super::behaviour::Conversion for Customer { let decrypted = types::crypto_operation( state, common_utils::type_name!(Self::DstType), - types::CryptoOperation::BatchDecrypt(CustomerRequestWithEncryption::to_encryptable( - CustomerRequestWithEncryption { + types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable( + EncryptedCustomer { name: item.name.clone(), phone: item.phone.clone(), email: item.email.clone(), @@ -113,16 +120,23 @@ impl super::behaviour::Conversion for Customer { .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), })?; - let encryptable_customer = CustomerRequestWithEncryption::from_encryptable(decrypted) - .change_context(ValidationError::InvalidValue { + let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context( + ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), - })?; + }, + )?; Ok(Self { customer_id: item.customer_id, merchant_id: item.merchant_id, name: encryptable_customer.name, - email: encryptable_customer.email, + email: encryptable_customer.email.map(|email| { + let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), phone: encryptable_customer.phone, phone_country_code: item.phone_country_code, description: item.description, @@ -198,8 +212,8 @@ impl super::behaviour::Conversion for Customer { let decrypted = types::crypto_operation( state, common_utils::type_name!(Self::DstType), - types::CryptoOperation::BatchDecrypt(CustomerRequestWithEncryption::to_encryptable( - CustomerRequestWithEncryption { + types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable( + EncryptedCustomer { name: item.name.clone(), phone: item.phone.clone(), email: item.email.clone(), @@ -213,17 +227,24 @@ impl super::behaviour::Conversion for Customer { .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), })?; - let encryptable_customer = CustomerRequestWithEncryption::from_encryptable(decrypted) - .change_context(ValidationError::InvalidValue { + let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context( + ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), - })?; + }, + )?; Ok(Self { id: item.id, merchant_reference_id: item.merchant_reference_id, merchant_id: item.merchant_id, name: encryptable_customer.name, - email: encryptable_customer.email, + email: encryptable_customer.email.map(|email| { + let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), phone: encryptable_customer.phone, phone_country_code: item.phone_country_code, description: item.description, diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs index 9418f6f8f1e..0d730be203b 100644 --- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs @@ -10,16 +10,18 @@ use diesel_models::{enums, merchant_connector_account::MerchantConnectorAccountU use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use rustc_hash::FxHashMap; +use serde_json::Value; use super::behaviour; use crate::type_encryption::{crypto_operation, CryptoOperation}; #[cfg(feature = "v1")] -#[derive(Clone, Debug)] +#[derive(Clone, Debug, router_derive::ToEncryption)] pub struct MerchantConnectorAccount { pub merchant_id: id_type::MerchantId, pub connector_name: String, - pub connector_account_details: Encryptable<pii::SecretSerdeValue>, + #[encrypt] + pub connector_account_details: Encryptable<Secret<Value>>, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: id_type::MerchantConnectorAccountId, @@ -38,8 +40,10 @@ pub struct MerchantConnectorAccount { pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: enums::ConnectorStatus, - pub connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>, - pub additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>, + #[encrypt] + pub connector_wallets_details: Option<Encryptable<Secret<Value>>>, + #[encrypt] + pub additional_merchant_data: Option<Encryptable<Secret<Value>>>, pub version: common_enums::ApiVersion, } @@ -51,12 +55,13 @@ impl MerchantConnectorAccount { } #[cfg(feature = "v2")] -#[derive(Clone, Debug)] +#[derive(Clone, Debug, router_derive::ToEncryption)] pub struct MerchantConnectorAccount { pub id: id_type::MerchantConnectorAccountId, pub merchant_id: id_type::MerchantId, pub connector_name: String, - pub connector_account_details: Encryptable<pii::SecretSerdeValue>, + #[encrypt] + pub connector_account_details: Encryptable<Secret<Value>>, pub disabled: Option<bool>, pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, pub connector_type: enums::ConnectorType, @@ -70,8 +75,10 @@ pub struct MerchantConnectorAccount { pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: enums::ConnectorStatus, - pub connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>, - pub additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>, + #[encrypt] + pub connector_wallets_details: Option<Encryptable<Secret<Value>>>, + #[encrypt] + pub additional_merchant_data: Option<Encryptable<Secret<Value>>>, pub version: common_enums::ApiVersion, } @@ -179,11 +186,13 @@ impl behaviour::Conversion for MerchantConnectorAccount { let decrypted_data = crypto_operation( state, type_name!(Self::DstType), - CryptoOperation::BatchDecrypt(EncryptedMca::to_encryptable(EncryptedMca { - connector_account_details: other.connector_account_details, - additional_merchant_data: other.additional_merchant_data, - connector_wallets_details: other.connector_wallets_details, - })), + CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable( + EncryptedMerchantConnectorAccount { + connector_account_details: other.connector_account_details, + additional_merchant_data: other.additional_merchant_data, + connector_wallets_details: other.connector_wallets_details, + }, + )), identifier.clone(), key.peek(), ) @@ -193,11 +202,10 @@ impl behaviour::Conversion for MerchantConnectorAccount { message: "Failed while decrypting connector account details".to_string(), })?; - let decrypted_data = EncryptedMca::from_encryptable(decrypted_data).change_context( - ValidationError::InvalidValue { + let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data) + .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector account details".to_string(), - }, - )?; + })?; Ok(Self { merchant_id: other.merchant_id, @@ -308,11 +316,13 @@ impl behaviour::Conversion for MerchantConnectorAccount { let decrypted_data = crypto_operation( state, type_name!(Self::DstType), - CryptoOperation::BatchDecrypt(EncryptedMca::to_encryptable(EncryptedMca { - connector_account_details: other.connector_account_details, - additional_merchant_data: other.additional_merchant_data, - connector_wallets_details: other.connector_wallets_details, - })), + CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable( + EncryptedMerchantConnectorAccount { + connector_account_details: other.connector_account_details, + additional_merchant_data: other.additional_merchant_data, + connector_wallets_details: other.connector_wallets_details, + }, + )), identifier.clone(), key.peek(), ) @@ -322,11 +332,10 @@ impl behaviour::Conversion for MerchantConnectorAccount { message: "Failed while decrypting connector account details".to_string(), })?; - let decrypted_data = EncryptedMca::from_encryptable(decrypted_data).change_context( - ValidationError::InvalidValue { + let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data) + .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector account details".to_string(), - }, - )?; + })?; Ok(Self { id: other.id, @@ -502,121 +511,3 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte } } } - -pub struct McaFromRequestfromUpdate { - pub connector_account_details: Option<pii::SecretSerdeValue>, - pub connector_wallets_details: Option<pii::SecretSerdeValue>, - pub additional_merchant_data: Option<pii::SecretSerdeValue>, -} -pub struct McaFromRequest { - pub connector_account_details: pii::SecretSerdeValue, - pub connector_wallets_details: Option<pii::SecretSerdeValue>, - pub additional_merchant_data: Option<pii::SecretSerdeValue>, -} - -pub struct DecryptedMca { - pub connector_account_details: Encryptable<pii::SecretSerdeValue>, - pub connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>, - pub additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>, -} - -pub struct EncryptedMca { - pub connector_account_details: Encryption, - pub connector_wallets_details: Option<Encryption>, - pub additional_merchant_data: Option<Encryption>, -} - -pub struct DecryptedUpdateMca { - pub connector_account_details: Option<Encryptable<pii::SecretSerdeValue>>, - pub connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>, - pub additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>, -} - -impl ToEncryptable<DecryptedMca, Secret<serde_json::Value>, Encryption> for EncryptedMca { - fn from_encryptable( - mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>, - ) -> CustomResult<DecryptedMca, common_utils::errors::ParsingError> { - Ok(DecryptedMca { - connector_account_details: hashmap.remove("connector_account_details").ok_or( - error_stack::report!(common_utils::errors::ParsingError::EncodeError( - "Unable to convert from HashMap to DecryptedMca", - )), - )?, - connector_wallets_details: hashmap.remove("connector_wallets_details"), - additional_merchant_data: hashmap.remove("additional_merchant_data"), - }) - } - - fn to_encryptable(self) -> FxHashMap<String, Encryption> { - let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default()); - - map.insert( - "connector_account_details".to_string(), - self.connector_account_details, - ); - self.connector_wallets_details - .map(|s| map.insert("connector_wallets_details".to_string(), s)); - self.additional_merchant_data - .map(|s| map.insert("additional_merchant_data".to_string(), s)); - map - } -} - -impl ToEncryptable<DecryptedUpdateMca, Secret<serde_json::Value>, Secret<serde_json::Value>> - for McaFromRequestfromUpdate -{ - fn from_encryptable( - mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>, - ) -> CustomResult<DecryptedUpdateMca, common_utils::errors::ParsingError> { - Ok(DecryptedUpdateMca { - connector_account_details: hashmap.remove("connector_account_details"), - connector_wallets_details: hashmap.remove("connector_wallets_details"), - additional_merchant_data: hashmap.remove("additional_merchant_data"), - }) - } - - fn to_encryptable(self) -> FxHashMap<String, Secret<serde_json::Value>> { - let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default()); - - self.connector_account_details - .map(|cad| map.insert("connector_account_details".to_string(), cad)); - - self.connector_wallets_details - .map(|s| map.insert("connector_wallets_details".to_string(), s)); - self.additional_merchant_data - .map(|s| map.insert("additional_merchant_data".to_string(), s)); - map - } -} - -impl ToEncryptable<DecryptedMca, Secret<serde_json::Value>, Secret<serde_json::Value>> - for McaFromRequest -{ - fn from_encryptable( - mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>, - ) -> CustomResult<DecryptedMca, common_utils::errors::ParsingError> { - Ok(DecryptedMca { - connector_account_details: hashmap.remove("connector_account_details").ok_or( - error_stack::report!(common_utils::errors::ParsingError::EncodeError( - "Unable to convert from HashMap to DecryptedMca", - )), - )?, - connector_wallets_details: hashmap.remove("connector_wallets_details"), - additional_merchant_data: hashmap.remove("additional_merchant_data"), - }) - } - - fn to_encryptable(self) -> FxHashMap<String, Secret<serde_json::Value>> { - let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default()); - - map.insert( - "connector_account_details".to_string(), - self.connector_account_details, - ); - self.connector_wallets_details - .map(|s| map.insert("connector_wallets_details".to_string(), s)); - self.additional_merchant_data - .map(|s| map.insert("additional_merchant_data".to_string(), s)); - map - } -} diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 933c13416f2..cd41458dfbf 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -5,11 +5,21 @@ use std::marker::PhantomData; use api_models::payments::Address; #[cfg(feature = "v2")] use api_models::payments::OrderDetailsWithAmount; -use common_utils::{self, crypto::Encryptable, id_type, pii, types::MinorUnit}; +use common_utils::{ + self, + crypto::Encryptable, + encryption::Encryption, + errors::CustomResult, + id_type, pii, + types::{keymanager::ToEncryptable, MinorUnit}, +}; use diesel_models::payment_intent::TaxDetails; #[cfg(feature = "v2")] use error_stack::ResultExt; use masking::Secret; +use router_derive::ToEncryption; +use rustc_hash::FxHashMap; +use serde_json::Value; use time::PrimitiveDateTime; pub mod payment_attempt; @@ -25,7 +35,7 @@ use crate::{business_profile, merchant_account}; use crate::{errors, payment_method_data, ApiModelToDieselModelConvertor}; #[cfg(feature = "v1")] -#[derive(Clone, Debug, PartialEq, serde::Serialize)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)] pub struct PaymentIntent { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, @@ -37,7 +47,7 @@ pub struct PaymentIntent { pub customer_id: Option<id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, - pub metadata: Option<serde_json::Value>, + pub metadata: Option<Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, @@ -56,9 +66,9 @@ pub struct PaymentIntent { pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, - pub allowed_payment_method_types: Option<serde_json::Value>, - pub connector_metadata: Option<serde_json::Value>, - pub feature_metadata: Option<serde_json::Value>, + pub allowed_payment_method_types: Option<Value>, + pub connector_metadata: Option<Value>, + pub feature_metadata: Option<Value>, pub attempt_count: i16, pub profile_id: Option<id_type::ProfileId>, pub payment_link_id: Option<String>, @@ -78,10 +88,13 @@ pub struct PaymentIntent { pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, - pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, - pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>, + #[encrypt] + pub customer_details: Option<Encryptable<Secret<Value>>>, + #[encrypt] + pub billing_details: Option<Encryptable<Secret<Value>>>, pub merchant_order_reference_id: Option<String>, - pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>, + #[encrypt] + pub shipping_details: Option<Encryptable<Secret<Value>>>, pub is_payment_processor_token_flow: Option<bool>, pub organization_id: id_type::OrganizationId, pub tax_details: Option<TaxDetails>, @@ -225,7 +238,7 @@ impl AmountDetails { } #[cfg(feature = "v2")] -#[derive(Clone, Debug, PartialEq, serde::Serialize)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)] pub struct PaymentIntent { /// The global identifier for the payment intent. This is generated by the system. /// The format of the global id is `{cell_id:5}_pay_{time_ordered_uuid:32}`. @@ -292,19 +305,22 @@ pub struct PaymentIntent { /// Metadata related to fraud and risk management pub frm_metadata: Option<pii::SecretSerdeValue>, /// The details of the customer in a denormalized form. Only a subset of fields are stored. - pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>, + #[encrypt] + pub customer_details: Option<Encryptable<Secret<Value>>>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The billing address for the order in a denormalized form. + #[encrypt(ty = Value)] pub billing_address: Option<Encryptable<Secret<Address>>>, /// The shipping address for the order in a denormalized form. + #[encrypt(ty = Value)] pub shipping_address: Option<Encryptable<Secret<Address>>>, /// Capture method for the payment pub capture_method: storage_enums::CaptureMethod, /// Authentication type that is requested by the merchant for this payment. pub authentication_type: common_enums::AuthenticationType, /// This contains the pre routing results that are done when routing is done during listing the payment methods. - pub prerouting_algorithm: Option<serde_json::Value>, + pub prerouting_algorithm: Option<Value>, /// The organization id for the payment. This is derived from the merchant account pub organization_id: id_type::OrganizationId, /// Denotes the request by the merchant whether to enable a payment link for this payment. @@ -323,7 +339,7 @@ pub struct PaymentIntent { impl PaymentIntent { fn get_request_incremental_authorization_value( request: &api_models::payments::PaymentsCreateIntentRequest, - ) -> common_utils::errors::CustomResult< + ) -> CustomResult< common_enums::RequestIncrementalAuthorization, errors::api_error_response::ApiErrorResponse, > { @@ -364,8 +380,7 @@ impl PaymentIntent { request: api_models::payments::PaymentsCreateIntentRequest, billing_address: Option<Encryptable<Secret<Address>>>, shipping_address: Option<Encryptable<Secret<Address>>>, - ) -> common_utils::errors::CustomResult<Self, errors::api_error_response::ApiErrorResponse> - { + ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let allowed_payment_method_types = request .get_allowed_payment_method_types_as_value() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index f1e4de499e6..c9f7a5e2ae5 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -3,7 +3,7 @@ use common_enums as storage_enums; use common_utils::ext_traits::{Encode, ValueExt}; use common_utils::{ consts::{PAYMENTS_LIST_MAX_LIMIT_V1, PAYMENTS_LIST_MAX_LIMIT_V2}, - crypto::{self, Encryptable}, + crypto::Encryptable, encryption::Encryption, errors::{CustomResult, ValidationError}, id_type, @@ -21,7 +21,6 @@ use error_stack::ResultExt; #[cfg(feature = "v2")] use masking::ExposeInterface; use masking::{Deserialize, PeekInterface, Secret}; -use rustc_hash::FxHashMap; use serde::Serialize; use time::PrimitiveDateTime; @@ -1241,10 +1240,10 @@ impl behaviour::Conversion for PaymentIntent { let decrypted_data = crypto_operation( state, type_name!(Self::DstType), - CryptoOperation::BatchDecrypt(EncryptedPaymentIntentAddress::to_encryptable( - EncryptedPaymentIntentAddress { - billing: storage_model.billing_address, - shipping: storage_model.shipping_address, + CryptoOperation::BatchDecrypt(super::EncryptedPaymentIntent::to_encryptable( + super::EncryptedPaymentIntent { + billing_address: storage_model.billing_address, + shipping_address: storage_model.shipping_address, customer_details: storage_model.customer_details, }, )), @@ -1254,7 +1253,7 @@ impl behaviour::Conversion for PaymentIntent { .await .and_then(|val| val.try_into_batchoperation())?; - let data = EncryptedPaymentIntentAddress::from_encryptable(decrypted_data) + let data = super::EncryptedPaymentIntent::from_encryptable(decrypted_data) .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Invalid batch operation data")?; @@ -1275,7 +1274,7 @@ impl behaviour::Conversion for PaymentIntent { }; let billing_address = data - .billing + .billing_address .map(|billing| { billing.deserialize_inner_value(|value| value.parse_value("Address")) }) @@ -1284,7 +1283,7 @@ impl behaviour::Conversion for PaymentIntent { .attach_printable("Error while deserializing Address")?; let shipping_address = data - .shipping + .shipping_address .map(|shipping| { shipping.deserialize_inner_value(|value| value.parse_value("Address")) }) @@ -1513,10 +1512,10 @@ impl behaviour::Conversion for PaymentIntent { let decrypted_data = crypto_operation( state, type_name!(Self::DstType), - CryptoOperation::BatchDecrypt(EncryptedPaymentIntentAddress::to_encryptable( - EncryptedPaymentIntentAddress { - billing: storage_model.billing_details, - shipping: storage_model.shipping_details, + CryptoOperation::BatchDecrypt(super::EncryptedPaymentIntent::to_encryptable( + super::EncryptedPaymentIntent { + billing_details: storage_model.billing_details, + shipping_details: storage_model.shipping_details, customer_details: storage_model.customer_details, }, )), @@ -1526,7 +1525,7 @@ impl behaviour::Conversion for PaymentIntent { .await .and_then(|val| val.try_into_batchoperation())?; - let data = EncryptedPaymentIntentAddress::from_encryptable(decrypted_data) + let data = super::EncryptedPaymentIntent::from_encryptable(decrypted_data) .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Invalid batch operation data")?; @@ -1578,9 +1577,9 @@ impl behaviour::Conversion for PaymentIntent { shipping_cost: storage_model.shipping_cost, tax_details: storage_model.tax_details, customer_details: data.customer_details, - billing_details: data.billing, + billing_details: data.billing_details, merchant_order_reference_id: storage_model.merchant_order_reference_id, - shipping_details: data.shipping, + shipping_details: data.shipping_details, is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow, organization_id: storage_model.organization_id, skip_external_tax_calculation: storage_model.skip_external_tax_calculation, @@ -1649,73 +1648,3 @@ impl behaviour::Conversion for PaymentIntent { }) } } - -pub struct EncryptedPaymentIntentAddress { - pub shipping: Option<Encryption>, - pub billing: Option<Encryption>, - pub customer_details: Option<Encryption>, -} - -pub struct PaymentAddressFromRequest { - pub shipping: Option<Secret<serde_json::Value>>, - pub billing: Option<Secret<serde_json::Value>>, - pub customer_details: Option<Secret<serde_json::Value>>, -} - -pub struct DecryptedPaymentIntentAddress { - pub shipping: crypto::OptionalEncryptableValue, - pub billing: crypto::OptionalEncryptableValue, - pub customer_details: crypto::OptionalEncryptableValue, -} - -impl ToEncryptable<DecryptedPaymentIntentAddress, Secret<serde_json::Value>, Encryption> - for EncryptedPaymentIntentAddress -{ - fn from_encryptable( - mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>, - ) -> CustomResult<DecryptedPaymentIntentAddress, common_utils::errors::ParsingError> { - Ok(DecryptedPaymentIntentAddress { - shipping: hashmap.remove("shipping"), - billing: hashmap.remove("billing"), - customer_details: hashmap.remove("customer_details"), - }) - } - - fn to_encryptable(self) -> FxHashMap<String, Encryption> { - let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default()); - - self.shipping.map(|s| map.insert("shipping".to_string(), s)); - self.billing.map(|s| map.insert("billing".to_string(), s)); - self.customer_details - .map(|s| map.insert("customer_details".to_string(), s)); - map - } -} - -impl - ToEncryptable< - DecryptedPaymentIntentAddress, - Secret<serde_json::Value>, - Secret<serde_json::Value>, - > for PaymentAddressFromRequest -{ - fn from_encryptable( - mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>, - ) -> CustomResult<DecryptedPaymentIntentAddress, common_utils::errors::ParsingError> { - Ok(DecryptedPaymentIntentAddress { - shipping: hashmap.remove("shipping"), - billing: hashmap.remove("billing"), - customer_details: hashmap.remove("customer_details"), - }) - } - - fn to_encryptable(self) -> FxHashMap<String, Secret<serde_json::Value>> { - let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default()); - - self.shipping.map(|s| map.insert("shipping".to_string(), s)); - self.billing.map(|s| map.insert("billing".to_string(), s)); - self.customer_details - .map(|s| map.insert("customer_details".to_string(), s)); - map - } -} diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index f49f4096340..cffb8267bff 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -15,7 +15,7 @@ use diesel_models::configs; use diesel_models::organization::OrganizationBridge; use error_stack::{report, FutureExt, ResultExt}; use hyperswitch_domain_models::merchant_connector_account::{ - McaFromRequest, McaFromRequestfromUpdate, + FromRequestEncryptableMerchantConnectorAccount, UpdateEncryptableMerchantConnectorAccount, }; use masking::{ExposeInterface, PeekInterface, Secret}; use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types}; @@ -2095,18 +2095,20 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), - domain_types::CryptoOperation::BatchEncrypt(McaFromRequestfromUpdate::to_encryptable( - McaFromRequestfromUpdate { - connector_account_details: self.connector_account_details, - connector_wallets_details: - helpers::get_connector_wallets_details_with_apple_pay_certificates( - &self.metadata, - &self.connector_wallets_details, - ) - .await?, - additional_merchant_data: merchant_recipient_data.map(Secret::new), - }, - )), + domain_types::CryptoOperation::BatchEncrypt( + UpdateEncryptableMerchantConnectorAccount::to_encryptable( + UpdateEncryptableMerchantConnectorAccount { + connector_account_details: self.connector_account_details, + connector_wallets_details: + helpers::get_connector_wallets_details_with_apple_pay_certificates( + &self.metadata, + &self.connector_wallets_details, + ) + .await?, + additional_merchant_data: merchant_recipient_data.map(Secret::new), + }, + ), + ), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.peek(), ) @@ -2115,9 +2117,10 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; - let encrypted_data = McaFromRequestfromUpdate::from_encryptable(encrypted_data) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while decrypting connector account details")?; + let encrypted_data = + UpdateEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details")?; Ok(storage::MerchantConnectorAccountUpdate::Update { connector_type: Some(self.connector_type), @@ -2262,18 +2265,20 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), - domain_types::CryptoOperation::BatchEncrypt(McaFromRequestfromUpdate::to_encryptable( - McaFromRequestfromUpdate { - connector_account_details: self.connector_account_details, - connector_wallets_details: - helpers::get_connector_wallets_details_with_apple_pay_certificates( - &self.metadata, - &self.connector_wallets_details, - ) - .await?, - additional_merchant_data: merchant_recipient_data.map(Secret::new), - }, - )), + domain_types::CryptoOperation::BatchEncrypt( + UpdateEncryptableMerchantConnectorAccount::to_encryptable( + UpdateEncryptableMerchantConnectorAccount { + connector_account_details: self.connector_account_details, + connector_wallets_details: + helpers::get_connector_wallets_details_with_apple_pay_certificates( + &self.metadata, + &self.connector_wallets_details, + ) + .await?, + additional_merchant_data: merchant_recipient_data.map(Secret::new), + }, + ), + ), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.peek(), ) @@ -2282,9 +2287,10 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; - let encrypted_data = McaFromRequestfromUpdate::from_encryptable(encrypted_data) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while decrypting connector account details")?; + let encrypted_data = + UpdateEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details")?; Ok(storage::MerchantConnectorAccountUpdate::Update { connector_type: Some(self.connector_type), @@ -2404,22 +2410,24 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), - domain_types::CryptoOperation::BatchEncrypt(McaFromRequest::to_encryptable( - McaFromRequest { - connector_account_details: self.connector_account_details.ok_or( - errors::ApiErrorResponse::MissingRequiredField { - field_name: "connector_account_details", - }, - )?, - connector_wallets_details: - helpers::get_connector_wallets_details_with_apple_pay_certificates( - &self.metadata, - &self.connector_wallets_details, - ) - .await?, - additional_merchant_data: merchant_recipient_data.map(Secret::new), - }, - )), + domain_types::CryptoOperation::BatchEncrypt( + FromRequestEncryptableMerchantConnectorAccount::to_encryptable( + FromRequestEncryptableMerchantConnectorAccount { + connector_account_details: self.connector_account_details.ok_or( + errors::ApiErrorResponse::MissingRequiredField { + field_name: "connector_account_details", + }, + )?, + connector_wallets_details: + helpers::get_connector_wallets_details_with_apple_pay_certificates( + &self.metadata, + &self.connector_wallets_details, + ) + .await?, + additional_merchant_data: merchant_recipient_data.map(Secret::new), + }, + ), + ), identifier.clone(), key_store.key.peek(), ) @@ -2428,9 +2436,10 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; - let encrypted_data = McaFromRequest::from_encryptable(encrypted_data) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while decrypting connector account details")?; + let encrypted_data = + FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details")?; Ok(domain::MerchantConnectorAccount { merchant_id: business_profile.merchant_id.clone(), @@ -2573,22 +2582,24 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), - domain_types::CryptoOperation::BatchEncrypt(McaFromRequest::to_encryptable( - McaFromRequest { - connector_account_details: self.connector_account_details.ok_or( - errors::ApiErrorResponse::MissingRequiredField { - field_name: "connector_account_details", - }, - )?, - connector_wallets_details: - helpers::get_connector_wallets_details_with_apple_pay_certificates( - &self.metadata, - &self.connector_wallets_details, - ) - .await?, - additional_merchant_data: merchant_recipient_data.map(Secret::new), - }, - )), + domain_types::CryptoOperation::BatchEncrypt( + FromRequestEncryptableMerchantConnectorAccount::to_encryptable( + FromRequestEncryptableMerchantConnectorAccount { + connector_account_details: self.connector_account_details.ok_or( + errors::ApiErrorResponse::MissingRequiredField { + field_name: "connector_account_details", + }, + )?, + connector_wallets_details: + helpers::get_connector_wallets_details_with_apple_pay_certificates( + &self.metadata, + &self.connector_wallets_details, + ) + .await?, + additional_merchant_data: merchant_recipient_data.map(Secret::new), + }, + ), + ), identifier.clone(), key_store.key.peek(), ) @@ -2597,9 +2608,10 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; - let encrypted_data = McaFromRequest::from_encryptable(encrypted_data) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while decrypting connector account details")?; + let encrypted_data = + FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details")?; Ok(domain::MerchantConnectorAccount { merchant_id: business_profile.merchant_id.clone(), diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 18cc8682eee..6d47ac174f3 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -1,16 +1,15 @@ -use api_models::customers::CustomerRequestWithEmail; use common_utils::{ crypto::Encryptable, errors::ReportSwitchExt, ext_traits::{AsyncExt, OptionExt}, - id_type, type_name, + id_type, pii, type_name, types::{ keymanager::{Identifier, KeyManagerState, ToEncryptable}, Description, }, }; use error_stack::{report, ResultExt}; -use masking::{Secret, SwitchStrategy}; +use masking::{ExposeInterface, Secret, SwitchStrategy}; use router_env::{instrument, tracing}; #[cfg(all(feature = "v2", feature = "customer_v2"))] @@ -145,13 +144,15 @@ impl CustomerCreateBridge for customers::CustomerRequest { let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), - types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable( - CustomerRequestWithEmail { - name: self.name.clone(), - email: self.email.clone(), - phone: self.phone.clone(), - }, - )), + types::CryptoOperation::BatchEncrypt( + domain::FromRequestEncryptableCustomer::to_encryptable( + domain::FromRequestEncryptableCustomer { + name: self.name.clone(), + email: self.email.clone().map(|a| a.expose().switch_strategy()), + phone: self.phone.clone(), + }, + ), + ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) @@ -160,8 +161,9 @@ impl CustomerCreateBridge for customers::CustomerRequest { .switch() .attach_printable("Failed while encrypting Customer")?; - let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data) - .change_context(errors::CustomersErrorResponse::InternalServerError)?; + let encryptable_customer = + domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) + .change_context(errors::CustomersErrorResponse::InternalServerError)?; Ok(domain::Customer { customer_id: merchant_reference_id @@ -169,7 +171,13 @@ impl CustomerCreateBridge for customers::CustomerRequest { .ok_or(errors::CustomersErrorResponse::InternalServerError)?, merchant_id: merchant_id.to_owned(), name: encryptable_customer.name, - email: encryptable_customer.email, + email: encryptable_customer.email.map(|email| { + let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), phone: encryptable_customer.phone, description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), @@ -234,13 +242,15 @@ impl CustomerCreateBridge for customers::CustomerRequest { let encrypted_data = types::crypto_operation( key_state, type_name!(domain::Customer), - types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable( - CustomerRequestWithEmail { - name: Some(self.name.clone()), - email: Some(self.email.clone()), - phone: self.phone.clone(), - }, - )), + types::CryptoOperation::BatchEncrypt( + domain::FromRequestEncryptableCustomer::to_encryptable( + domain::FromRequestEncryptableCustomer { + name: Some(self.name.clone()), + email: Some(self.email.clone().expose().switch_strategy()), + phone: self.phone.clone(), + }, + ), + ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) @@ -249,15 +259,22 @@ impl CustomerCreateBridge for customers::CustomerRequest { .switch() .attach_printable("Failed while encrypting Customer")?; - let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data) - .change_context(errors::CustomersErrorResponse::InternalServerError)?; + let encryptable_customer = + domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) + .change_context(errors::CustomersErrorResponse::InternalServerError)?; Ok(domain::Customer { id: common_utils::generate_time_ordered_id("cus"), merchant_reference_id: merchant_reference_id.to_owned(), merchant_id, name: encryptable_customer.name, - email: encryptable_customer.email, + email: encryptable_customer.email.map(|email| { + let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), phone: encryptable_customer.phone, description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), @@ -1174,13 +1191,18 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), - types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable( - CustomerRequestWithEmail { - name: self.name.clone(), - email: self.email.clone(), - phone: self.phone.clone(), - }, - )), + types::CryptoOperation::BatchEncrypt( + domain::FromRequestEncryptableCustomer::to_encryptable( + domain::FromRequestEncryptableCustomer { + name: self.name.clone(), + email: self + .email + .as_ref() + .map(|a| a.clone().expose().switch_strategy()), + phone: self.phone.clone(), + }, + ), + ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) @@ -1188,8 +1210,9 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { .and_then(|val| val.try_into_batchoperation()) .switch()?; - let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data) - .change_context(errors::CustomersErrorResponse::InternalServerError)?; + let encryptable_customer = + domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) + .change_context(errors::CustomersErrorResponse::InternalServerError)?; let response = db .update_customer_by_customer_id_merchant_id( @@ -1199,7 +1222,14 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { domain_customer.to_owned(), storage::CustomerUpdate::Update { name: encryptable_customer.name, - email: encryptable_customer.email, + email: encryptable_customer.email.map(|email| { + let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = + Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), phone: Box::new(encryptable_customer.phone), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), @@ -1266,13 +1296,18 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), - types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable( - CustomerRequestWithEmail { - name: self.name.clone(), - email: self.email.clone(), - phone: self.phone.clone(), - }, - )), + types::CryptoOperation::BatchEncrypt( + domain::FromRequestEncryptableCustomer::to_encryptable( + domain::FromRequestEncryptableCustomer { + name: self.name.clone(), + email: self + .email + .as_ref() + .map(|a| a.clone().expose().switch_strategy()), + phone: self.phone.clone(), + }, + ), + ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) @@ -1280,8 +1315,9 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { .and_then(|val| val.try_into_batchoperation()) .switch()?; - let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data) - .change_context(errors::CustomersErrorResponse::InternalServerError)?; + let encryptable_customer = + domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) + .change_context(errors::CustomersErrorResponse::InternalServerError)?; let response = db .update_customer_by_global_id( @@ -1291,7 +1327,14 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { merchant_account.get_id(), storage::CustomerUpdate::Update { name: encryptable_customer.name, - email: Box::new(encryptable_customer.email), + email: Box::new(encryptable_customer.email.map(|email| { + let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = + Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + })), phone: Box::new(encryptable_customer.phone), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 1f67e8066c9..ea7af3c7578 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1,12 +1,9 @@ use std::{borrow::Cow, str::FromStr}; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] -use api_models::customers::CustomerRequestWithEmail; use api_models::{ mandates::RecurringDetails, payments::{ - additional_info as payment_additional_types, AddressDetailsWithPhone, PaymentChargeRequest, - RequestSurchargeDetails, + additional_info as payment_additional_types, PaymentChargeRequest, RequestSurchargeDetails, }, }; use base64::Engine; @@ -39,7 +36,7 @@ use hyperswitch_domain_models::{ }; use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}; use josekit::jwe; -use masking::{ExposeInterface, PeekInterface}; +use masking::{ExposeInterface, PeekInterface, SwitchStrategy}; use openssl::{ derive::Deriver, pkey::PKey, @@ -126,16 +123,33 @@ pub async fn create_or_update_address_for_payment_by_request( let encrypted_data = types::crypto_operation( &session_state.into(), type_name!(domain::Address), - types::CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable( - AddressDetailsWithPhone { - address: address.address.clone(), - phone_number: address - .phone - .as_ref() - .and_then(|phone| phone.number.clone()), - email: address.email.clone(), - }, - )), + types::CryptoOperation::BatchEncrypt( + domain::FromRequestEncryptableAddress::to_encryptable( + domain::FromRequestEncryptableAddress { + line1: address.address.as_ref().and_then(|a| a.line1.clone()), + line2: address.address.as_ref().and_then(|a| a.line2.clone()), + line3: address.address.as_ref().and_then(|a| a.line3.clone()), + state: address.address.as_ref().and_then(|a| a.state.clone()), + first_name: address + .address + .as_ref() + .and_then(|a| a.first_name.clone()), + last_name: address + .address + .as_ref() + .and_then(|a| a.last_name.clone()), + zip: address.address.as_ref().and_then(|a| a.zip.clone()), + phone_number: address + .phone + .as_ref() + .and_then(|phone| phone.number.clone()), + email: address + .email + .as_ref() + .map(|a| a.clone().expose().switch_strategy()), + }, + ), + ), Identifier::Merchant(merchant_key_store.merchant_id.clone()), key, ) @@ -143,9 +157,10 @@ pub async fn create_or_update_address_for_payment_by_request( .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address")?; - let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while encrypting address")?; + let encryptable_address = + domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encrypting address")?; let address_update = storage::AddressUpdate::Update { city: address .address @@ -165,7 +180,14 @@ pub async fn create_or_update_address_for_payment_by_request( .as_ref() .and_then(|value| value.country_code.clone()), updated_by: storage_scheme.to_string(), - email: encryptable_address.email, + email: encryptable_address.email.map(|email| { + let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = + Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), }; let address = db .find_address_by_merchant_id_payment_id_address_id( @@ -317,23 +339,35 @@ pub async fn get_domain_address( let encrypted_data = types::crypto_operation( &session_state.into(), type_name!(domain::Address), - types::CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable( - AddressDetailsWithPhone { - address: address_details.cloned(), - phone_number: address - .phone - .as_ref() - .and_then(|phone| phone.number.clone()), - email: address.email.clone(), - }, - )), + types::CryptoOperation::BatchEncrypt( + domain::FromRequestEncryptableAddress::to_encryptable( + domain::FromRequestEncryptableAddress { + line1: address.address.as_ref().and_then(|a| a.line1.clone()), + line2: address.address.as_ref().and_then(|a| a.line2.clone()), + line3: address.address.as_ref().and_then(|a| a.line3.clone()), + state: address.address.as_ref().and_then(|a| a.state.clone()), + first_name: address.address.as_ref().and_then(|a| a.first_name.clone()), + last_name: address.address.as_ref().and_then(|a| a.last_name.clone()), + zip: address.address.as_ref().and_then(|a| a.zip.clone()), + phone_number: address + .phone + .as_ref() + .and_then(|phone| phone.number.clone()), + email: address + .email + .as_ref() + .map(|a| a.clone().expose().switch_strategy()), + }, + ), + ), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; - let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) - .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + let encryptable_address = + domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(domain::Address { phone_number: encryptable_address.phone_number, country_code: address.phone.as_ref().and_then(|a| a.country_code.clone()), @@ -351,7 +385,14 @@ pub async fn get_domain_address( modified_at: common_utils::date_time::now(), zip: encryptable_address.zip, updated_by: storage_scheme.to_string(), - email: encryptable_address.email, + email: encryptable_address.email.map(|email| { + let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = + Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), }) } .await @@ -1589,13 +1630,18 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>( let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), - types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable( - CustomerRequestWithEmail { - name: request_customer_details.name.clone(), - email: request_customer_details.email.clone(), - phone: request_customer_details.phone.clone(), - }, - )), + types::CryptoOperation::BatchEncrypt( + domain::FromRequestEncryptableCustomer::to_encryptable( + domain::FromRequestEncryptableCustomer { + name: request_customer_details.name.clone(), + email: request_customer_details + .email + .as_ref() + .map(|e| e.clone().expose().switch_strategy()), + phone: request_customer_details.phone.clone(), + }, + ), + ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) @@ -1603,9 +1649,10 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>( .and_then(|val| val.try_into_batchoperation()) .change_context(errors::StorageError::SerializationFailed) .attach_printable("Failed while encrypting Customer while Update")?; - let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data) - .change_context(errors::StorageError::SerializationFailed) - .attach_printable("Failed while encrypting Customer while Update")?; + let encryptable_customer = + domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) + .change_context(errors::StorageError::SerializationFailed) + .attach_printable("Failed while encrypting Customer while Update")?; Some(match customer_data { Some(c) => { // Update the customer data if new data is passed in the request @@ -1616,7 +1663,15 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>( { let customer_update = Update { name: encryptable_customer.name, - email: encryptable_customer.email, + email: encryptable_customer.email.map(|email| { + let encryptable: Encryptable< + masking::Secret<String, pii::EmailStrategy>, + > = Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), phone: Box::new(encryptable_customer.phone), phone_country_code: request_customer_details.phone_country_code, description: None, @@ -1644,7 +1699,15 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>( customer_id, merchant_id: merchant_id.to_owned(), name: encryptable_customer.name, - email: encryptable_customer.email, + email: encryptable_customer.email.map(|email| { + let encryptable: Encryptable< + masking::Secret<String, pii::EmailStrategy>, + > = Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), phone: encryptable_customer.phone, phone_country_code: request_customer_details.phone_country_code.clone(), description: None, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 696bd1468e4..13c589c11cc 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -18,8 +18,8 @@ use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ mandates::{MandateData, MandateDetails}, payments::{ - payment_attempt::PaymentAttempt, - payment_intent::{CustomerData, PaymentAddressFromRequest}, + payment_attempt::PaymentAttempt, payment_intent::CustomerData, + FromRequestEncryptablePaymentIntent, }, }; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -1340,11 +1340,13 @@ impl PaymentCreate { &key_manager_state, type_name!(storage::PaymentIntent), domain::types::CryptoOperation::BatchEncrypt( - PaymentAddressFromRequest::to_encryptable(PaymentAddressFromRequest { - shipping: shipping_details_encoded, - billing: billing_details_encoded, - customer_details: customer_details_encoded, - }), + FromRequestEncryptablePaymentIntent::to_encryptable( + FromRequestEncryptablePaymentIntent { + shipping_details: shipping_details_encoded, + billing_details: billing_details_encoded, + customer_details: customer_details_encoded, + }, + ), ), identifier.clone(), key, @@ -1354,7 +1356,7 @@ impl PaymentCreate { .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt data")?; - let encrypted_data = PaymentAddressFromRequest::from_encryptable(encrypted_data) + let encrypted_data = FromRequestEncryptablePaymentIntent::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt the payment intent data")?; @@ -1407,10 +1409,10 @@ impl PaymentCreate { .request_external_three_ds_authentication, charges, frm_metadata: request.frm_metadata.clone(), - billing_details: encrypted_data.billing, + billing_details: encrypted_data.billing_details, customer_details: encrypted_data.customer_details, merchant_order_reference_id: request.merchant_order_reference_id.clone(), - shipping_details: encrypted_data.shipping, + shipping_details: encrypted_data.shipping_details, is_payment_processor_token_flow, organization_id: merchant_account.organization_id.clone(), shipping_cost: request.shipping_cost, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 46f45905448..49b18e53a0c 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1,11 +1,10 @@ -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] -use api_models::customers::CustomerRequestWithEmail; use api_models::{enums, payment_methods::Card, payouts}; use common_utils::{ + crypto::Encryptable, encryption::Encryption, errors::CustomResult, ext_traits::{AsyncExt, StringExt}, - fp_utils, id_type, payout_method_utils as payout_additional, type_name, + fp_utils, id_type, payout_method_utils as payout_additional, pii, type_name, types::{ keymanager::{Identifier, KeyManagerState}, MinorUnit, UnifiedCode, UnifiedMessage, @@ -15,7 +14,7 @@ use common_utils::{ use common_utils::{generate_customer_id_of_default_length, types::keymanager::ToEncryptable}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy}; use router_env::logger; use super::PayoutData; @@ -696,13 +695,18 @@ pub(super) async fn get_or_create_customer_details( let encrypted_data = crypto_operation( &state.into(), type_name!(domain::Customer), - CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable( - CustomerRequestWithEmail { - name: customer_details.name.clone(), - email: customer_details.email.clone(), - phone: customer_details.phone.clone(), - }, - )), + CryptoOperation::BatchEncrypt( + domain::FromRequestEncryptableCustomer::to_encryptable( + domain::FromRequestEncryptableCustomer { + name: customer_details.name.clone(), + email: customer_details + .email + .clone() + .map(|a| a.expose().switch_strategy()), + phone: customer_details.phone.clone(), + }, + ), + ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) @@ -711,7 +715,7 @@ pub(super) async fn get_or_create_customer_details( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt customer")?; let encryptable_customer = - CustomerRequestWithEmail::from_encryptable(encrypted_data) + domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form EncryptableCustomer")?; @@ -719,7 +723,14 @@ pub(super) async fn get_or_create_customer_details( customer_id: customer_id.clone(), merchant_id: merchant_id.to_owned().clone(), name: encryptable_customer.name, - email: encryptable_customer.email, + email: encryptable_customer.email.map(|email| { + let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = + Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), phone: encryptable_customer.phone, description: None, phone_country_code: customer_details.phone_country_code.to_owned(), diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs index 5d9af527cd4..2d1e98ec1b8 100644 --- a/crates/router/src/types/domain/address.rs +++ b/crates/router/src/types/domain/address.rs @@ -4,30 +4,38 @@ use common_utils::{ date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, - id_type, type_name, + id_type, pii, type_name, types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, }; use diesel_models::{address::AddressUpdateInternal, enums}; use error_stack::ResultExt; -use masking::{PeekInterface, Secret}; +use masking::{PeekInterface, Secret, SwitchStrategy}; use rustc_hash::FxHashMap; use time::{OffsetDateTime, PrimitiveDateTime}; use super::{behaviour, types}; -#[derive(Clone, Debug, serde::Serialize)] +#[derive(Clone, Debug, serde::Serialize, router_derive::ToEncryption)] pub struct Address { pub address_id: String, pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, - pub line1: crypto::OptionalEncryptableSecretString, - pub line2: crypto::OptionalEncryptableSecretString, - pub line3: crypto::OptionalEncryptableSecretString, - pub state: crypto::OptionalEncryptableSecretString, - pub zip: crypto::OptionalEncryptableSecretString, - pub first_name: crypto::OptionalEncryptableSecretString, - pub last_name: crypto::OptionalEncryptableSecretString, - pub phone_number: crypto::OptionalEncryptableSecretString, + #[encrypt] + pub line1: Option<Encryptable<Secret<String>>>, + #[encrypt] + pub line2: Option<Encryptable<Secret<String>>>, + #[encrypt] + pub line3: Option<Encryptable<Secret<String>>>, + #[encrypt] + pub state: Option<Encryptable<Secret<String>>>, + #[encrypt] + pub zip: Option<Encryptable<Secret<String>>>, + #[encrypt] + pub first_name: Option<Encryptable<Secret<String>>>, + #[encrypt] + pub last_name: Option<Encryptable<Secret<String>>>, + #[encrypt] + pub phone_number: Option<Encryptable<Secret<String>>>, pub country_code: Option<String>, #[serde(skip_serializing)] #[serde(with = "custom_serde::iso8601")] @@ -37,7 +45,8 @@ pub struct Address { pub modified_at: PrimitiveDateTime, pub merchant_id: id_type::MerchantId, pub updated_by: String, - pub email: crypto::OptionalEncryptableEmail, + #[encrypt] + pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>, } /// Based on the flow, appropriate address has to be used @@ -191,8 +200,18 @@ impl behaviour::Conversion for Address { let decrypted: FxHashMap<String, Encryptable<Secret<String>>> = types::crypto_operation( state, type_name!(Self::DstType), - types::CryptoOperation::BatchDecrypt(diesel_models::Address::to_encryptable( - other.clone(), + types::CryptoOperation::BatchDecrypt(EncryptedAddress::to_encryptable( + EncryptedAddress { + line1: other.line1, + line2: other.line2, + line3: other.line3, + state: other.state, + zip: other.zip, + first_name: other.first_name, + last_name: other.last_name, + phone_number: other.phone_number, + email: other.email, + }, )), identifier.clone(), key.peek(), @@ -202,10 +221,11 @@ impl behaviour::Conversion for Address { .change_context(ValidationError::InvalidValue { message: "Failed while decrypting".to_string(), })?; - let encryptable_address = diesel_models::Address::from_encryptable(decrypted) - .change_context(ValidationError::InvalidValue { + let encryptable_address = EncryptedAddress::from_encryptable(decrypted).change_context( + ValidationError::InvalidValue { message: "Failed while decrypting".to_string(), - })?; + }, + )?; Ok(Self { address_id: other.address_id, city: other.city, @@ -223,7 +243,13 @@ impl behaviour::Conversion for Address { modified_at: other.modified_at, updated_by: other.updated_by, merchant_id: other.merchant_id, - email: encryptable_address.email, + email: encryptable_address.email.map(|email| { + let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), }) } diff --git a/crates/router/src/types/domain/event.rs b/crates/router/src/types/domain/event.rs index badbb9df7b4..db2d7530164 100644 --- a/crates/router/src/types/domain/event.rs +++ b/crates/router/src/types/domain/event.rs @@ -1,22 +1,23 @@ use common_utils::{ - crypto::OptionalEncryptableSecretString, + crypto::{Encryptable, OptionalEncryptableSecretString}, + encryption::Encryption, type_name, types::keymanager::{KeyManagerState, ToEncryptable}, }; use diesel_models::{ enums::{EventClass, EventObjectType, EventType, WebhookDeliveryAttempt}, events::{EventMetadata, EventUpdateInternal}, - EventWithEncryption, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; +use rustc_hash::FxHashMap; use crate::{ errors::{CustomResult, ValidationError}, types::domain::types, }; -#[derive(Clone, Debug)] +#[derive(Clone, Debug, router_derive::ToEncryption)] pub struct Event { pub event_id: String, pub event_type: EventType, @@ -30,8 +31,10 @@ pub struct Event { pub primary_object_created_at: Option<time::PrimitiveDateTime>, pub idempotent_event_id: Option<String>, pub initial_attempt_id: Option<String>, - pub request: OptionalEncryptableSecretString, - pub response: OptionalEncryptableSecretString, + #[encrypt] + pub request: Option<Encryptable<Secret<String>>>, + #[encrypt] + pub response: Option<Encryptable<Secret<String>>>, pub delivery_attempt: Option<WebhookDeliveryAttempt>, pub metadata: Option<EventMetadata>, } @@ -96,12 +99,10 @@ impl super::behaviour::Conversion for Event { let decrypted = types::crypto_operation( state, type_name!(Self::DstType), - types::CryptoOperation::BatchDecrypt(EventWithEncryption::to_encryptable( - EventWithEncryption { - request: item.request.clone(), - response: item.response.clone(), - }, - )), + types::CryptoOperation::BatchDecrypt(EncryptedEvent::to_encryptable(EncryptedEvent { + request: item.request.clone(), + response: item.response.clone(), + })), key_manager_identifier, key.peek(), ) @@ -110,7 +111,7 @@ impl super::behaviour::Conversion for Event { .change_context(ValidationError::InvalidValue { message: "Failed while decrypting event data".to_string(), })?; - let encryptable_event = EventWithEncryption::from_encryptable(decrypted).change_context( + let encryptable_event = EncryptedEvent::from_encryptable(decrypted).change_context( ValidationError::InvalidValue { message: "Failed while decrypting event data".to_string(), }, diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index f56a741dc1a..515c9a94ce8 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -13,8 +13,6 @@ pub mod user_role; pub mod verify_connector; use std::fmt::Debug; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] -use api_models::payments::AddressDetailsWithPhone; use api_models::{ enums, payments::{self}, @@ -22,10 +20,10 @@ use api_models::{ }; use common_utils::types::keymanager::KeyManagerState; pub use common_utils::{ - crypto, + crypto::{self, Encryptable}, ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt}, fp_utils::when, - id_type, + id_type, pii, validation::validate_email, }; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] @@ -38,6 +36,7 @@ pub use hyperswitch_connectors::utils::QrImage; use hyperswitch_domain_models::payments::PaymentIntent; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; +use masking::{ExposeInterface, SwitchStrategy}; use nanoid::nanoid; use router_env::metrics::add_attributes; use serde::de::DeserializeOwned; @@ -779,20 +778,32 @@ impl CustomerAddress for api_models::customers::CustomerRequest { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), - CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable( - AddressDetailsWithPhone { - address: Some(address_details.clone()), + CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( + domain::FromRequestEncryptableAddress { + line1: address_details.line1.clone(), + line2: address_details.line2.clone(), + line3: address_details.line3.clone(), + state: address_details.state.clone(), + first_name: address_details.first_name.clone(), + last_name: address_details.last_name.clone(), + zip: address_details.zip.clone(), phone_number: self.phone.clone(), - email: self.email.clone(), + email: self + .email + .as_ref() + .map(|a| a.clone().expose().switch_strategy()), }, )), - Identifier::Merchant(merchant_id), + Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; - let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) - .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + + let encryptable_address = + domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + Ok(storage::AddressUpdate::Update { city: address_details.city, country: address_details.country, @@ -806,7 +817,14 @@ impl CustomerAddress for api_models::customers::CustomerRequest { phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), - email: encryptable_address.email, + email: encryptable_address.email.map(|email| { + let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = + Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), }) } @@ -822,11 +840,20 @@ impl CustomerAddress for api_models::customers::CustomerRequest { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), - CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable( - AddressDetailsWithPhone { - address: Some(address_details.clone()), + CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( + domain::FromRequestEncryptableAddress { + line1: address_details.line1.clone(), + line2: address_details.line2.clone(), + line3: address_details.line3.clone(), + state: address_details.state.clone(), + first_name: address_details.first_name.clone(), + last_name: address_details.last_name.clone(), + zip: address_details.zip.clone(), phone_number: self.phone.clone(), - email: self.email.clone(), + email: self + .email + .as_ref() + .map(|a| a.clone().expose().switch_strategy()), }, )), Identifier::Merchant(merchant_id.to_owned()), @@ -834,8 +861,11 @@ impl CustomerAddress for api_models::customers::CustomerRequest { ) .await .and_then(|val| val.try_into_batchoperation())?; - let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) - .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + + let encryptable_address = + domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + let address = domain::Address { city: address_details.city, country: address_details.country, @@ -853,7 +883,14 @@ impl CustomerAddress for api_models::customers::CustomerRequest { created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), updated_by: storage_scheme.to_string(), - email: encryptable_address.email, + email: encryptable_address.email.map(|email| { + let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = + Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), }; Ok(domain::CustomerAddress { @@ -877,20 +914,31 @@ impl CustomerAddress for api_models::customers::CustomerUpdateRequest { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), - CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable( - AddressDetailsWithPhone { - address: Some(address_details.clone()), + CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( + domain::FromRequestEncryptableAddress { + line1: address_details.line1.clone(), + line2: address_details.line2.clone(), + line3: address_details.line3.clone(), + state: address_details.state.clone(), + first_name: address_details.first_name.clone(), + last_name: address_details.last_name.clone(), + zip: address_details.zip.clone(), phone_number: self.phone.clone(), - email: self.email.clone(), + email: self + .email + .as_ref() + .map(|a| a.clone().expose().switch_strategy()), }, )), - Identifier::Merchant(merchant_id), + Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; - let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) - .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + + let encryptable_address = + domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(storage::AddressUpdate::Update { city: address_details.city, country: address_details.country, @@ -904,7 +952,14 @@ impl CustomerAddress for api_models::customers::CustomerUpdateRequest { phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), - email: encryptable_address.email, + email: encryptable_address.email.map(|email| { + let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = + Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), }) } @@ -920,11 +975,20 @@ impl CustomerAddress for api_models::customers::CustomerUpdateRequest { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), - CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable( - AddressDetailsWithPhone { - address: Some(address_details.clone()), + CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( + domain::FromRequestEncryptableAddress { + line1: address_details.line1.clone(), + line2: address_details.line2.clone(), + line3: address_details.line3.clone(), + state: address_details.state.clone(), + first_name: address_details.first_name.clone(), + last_name: address_details.last_name.clone(), + zip: address_details.zip.clone(), phone_number: self.phone.clone(), - email: self.email.clone(), + email: self + .email + .as_ref() + .map(|a| a.clone().expose().switch_strategy()), }, )), Identifier::Merchant(merchant_id.to_owned()), @@ -932,8 +996,10 @@ impl CustomerAddress for api_models::customers::CustomerUpdateRequest { ) .await .and_then(|val| val.try_into_batchoperation())?; - let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) - .change_context(common_utils::errors::CryptoError::EncodingFailed)?; + + let encryptable_address = + domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) + .change_context(common_utils::errors::CryptoError::EncodingFailed)?; let address = domain::Address { city: address_details.city, country: address_details.country, @@ -951,7 +1017,14 @@ impl CustomerAddress for api_models::customers::CustomerUpdateRequest { created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), updated_by: storage_scheme.to_string(), - email: encryptable_address.email, + email: encryptable_address.email.map(|email| { + let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = + Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ); + encryptable + }), }; Ok(domain::CustomerAddress { diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index 69865512a37..33edd5e215e 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -644,6 +644,7 @@ pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::Token /// ("address.zip", "941222"), /// ("email", "test@example.com"), /// ] +/// #[proc_macro_derive(FlatStruct)] pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as syn::DeriveInput); @@ -749,3 +750,18 @@ pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenSt pub fn generate_permissions(input: proc_macro::TokenStream) -> proc_macro::TokenStream { macros::generate_permissions_inner(input) } + +/// Generates the ToEncryptable trait for a type +/// +/// This macro generates the temporary structs which has the fields that needs to be encrypted +/// +/// fn to_encryptable: Convert the temp struct to a hashmap that can be sent over the network +/// fn from_encryptable: Convert the hashmap back to temp struct +#[proc_macro_derive(ToEncryption, attributes(encrypt))] +pub fn derive_to_encryption_attr(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as syn::DeriveInput); + + macros::derive_to_encryption(input) + .unwrap_or_else(|err| err.into_compile_error()) + .into() +} diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rs index 32e6c213ca6..e227c6533e9 100644 --- a/crates/router_derive/src/macros.rs +++ b/crates/router_derive/src/macros.rs @@ -4,6 +4,7 @@ pub(crate) mod generate_permissions; pub(crate) mod generate_schema; pub(crate) mod misc; pub(crate) mod operation; +pub(crate) mod to_encryptable; pub(crate) mod try_get_enum; mod helpers; @@ -17,6 +18,7 @@ pub(crate) use self::{ diesel::{diesel_enum_derive_inner, diesel_enum_text_derive_inner}, generate_permissions::generate_permissions_inner, generate_schema::polymorphic_macro_derive_inner, + to_encryptable::derive_to_encryption, }; pub(crate) fn debug_as_display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { diff --git a/crates/router_derive/src/macros/to_encryptable.rs b/crates/router_derive/src/macros/to_encryptable.rs new file mode 100644 index 00000000000..dfcfb72169b --- /dev/null +++ b/crates/router_derive/src/macros/to_encryptable.rs @@ -0,0 +1,326 @@ +use std::iter::Iterator; + +use quote::{format_ident, quote}; +use syn::{parse::Parse, punctuated::Punctuated, token::Comma, Field, Ident, Type as SynType}; + +use crate::macros::{helpers::get_struct_fields, misc::get_field_type}; + +pub struct FieldMeta { + _meta_type: Ident, + pub value: Ident, +} + +impl Parse for FieldMeta { + fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { + let _meta_type: Ident = input.parse()?; + input.parse::<syn::Token![=]>()?; + let value: Ident = input.parse()?; + Ok(Self { _meta_type, value }) + } +} + +impl quote::ToTokens for FieldMeta { + fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { + self.value.to_tokens(tokens); + } +} + +fn get_encryption_ty_meta(field: &Field) -> Option<FieldMeta> { + let attrs = &field.attrs; + + attrs + .iter() + .flat_map(|s| s.parse_args::<FieldMeta>()) + .find(|s| s._meta_type.eq("ty")) +} + +fn get_inner_type(path: &syn::TypePath) -> syn::Result<syn::TypePath> { + path.path + .segments + .last() + .and_then(|segment| match &segment.arguments { + syn::PathArguments::AngleBracketed(args) => args.args.first(), + _ => None, + }) + .and_then(|arg| match arg { + syn::GenericArgument::Type(SynType::Path(path)) => Some(path.clone()), + _ => None, + }) + .ok_or_else(|| { + syn::Error::new( + proc_macro2::Span::call_site(), + "Only path fields are supported", + ) + }) +} + +/// This function returns the inner most type recursively +/// For example: +/// +/// In the case of `Encryptable<Secret<String>>> this returns String +fn get_inner_most_type(ty: SynType) -> syn::Result<Ident> { + fn get_inner_type_recursive(path: syn::TypePath) -> syn::Result<syn::TypePath> { + match get_inner_type(&path) { + Ok(inner_path) => get_inner_type_recursive(inner_path), + Err(_) => Ok(path), + } + } + + match ty { + SynType::Path(path) => { + let inner_path = get_inner_type_recursive(path)?; + inner_path + .path + .segments + .last() + .map(|last_segment| last_segment.ident.to_owned()) + .ok_or_else(|| { + syn::Error::new( + proc_macro2::Span::call_site(), + "At least one ident must be specified", + ) + }) + } + _ => Err(syn::Error::new( + proc_macro2::Span::call_site(), + "Only path fields are supported", + )), + } +} + +/// This returns the field which implement #[encrypt] attribute +fn get_encryptable_fields(fields: Punctuated<Field, Comma>) -> Vec<Field> { + fields + .into_iter() + .filter(|field| { + field + .attrs + .iter() + .any(|attr| attr.path().is_ident("encrypt")) + }) + .collect() +} + +/// This function returns the inner most type of a field +fn get_field_and_inner_types(fields: &[Field]) -> Vec<(Field, Ident)> { + fields + .iter() + .flat_map(|field| { + get_inner_most_type(field.ty.clone()).map(|field_name| (field.to_owned(), field_name)) + }) + .collect() +} + +/// The type of the struct for which the batch encryption/decryption needs to be implemented +#[derive(PartialEq, Copy, Clone)] +enum StructType { + Encrypted, + Decrypted, + DecryptedUpdate, + FromRequest, + Updated, +} + +impl StructType { + /// Generates the fields for temporary structs which consists of the fields that should be + /// encrypted/decrypted + fn generate_struct_fields(&self, fields: &[(Field, Ident)]) -> Vec<proc_macro2::TokenStream> { + fields + .iter() + .map(|(field, inner_ty)| { + let provided_ty = get_encryption_ty_meta(field); + let is_option = get_field_type(field.ty.clone()) + .map(|f| f.eq("Option")) + .unwrap_or_default(); + let ident = &field.ident; + let inner_ty = if let Some(ref ty) = provided_ty { + &ty.value + } else { + inner_ty + }; + match (self, is_option) { + (Self::Encrypted, true) => quote! { pub #ident: Option<Encryption> }, + (Self::Encrypted, false) => quote! { pub #ident: Encryption }, + (Self::Decrypted, true) => { + quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> } + } + (Self::Decrypted, false) => { + quote! { pub #ident: Encryptable<Secret<#inner_ty>> } + } + (Self::DecryptedUpdate, _) => { + quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> } + } + (Self::FromRequest, true) => { + quote! { pub #ident: Option<Secret<#inner_ty>> } + } + (Self::FromRequest, false) => quote! { pub #ident: Secret<#inner_ty> }, + (Self::Updated, _) => quote! { pub #ident: Option<Secret<#inner_ty>> }, + } + }) + .collect() + } + + /// Generates the ToEncryptable trait implementation + fn generate_impls( + &self, + gen1: proc_macro2::TokenStream, + gen2: proc_macro2::TokenStream, + gen3: proc_macro2::TokenStream, + impl_st: proc_macro2::TokenStream, + inner: &[Field], + ) -> proc_macro2::TokenStream { + let map_length = inner.len(); + + let to_encryptable_impl = inner.iter().flat_map(|field| { + get_field_type(field.ty.clone()).map(|field_ty| { + let is_option = field_ty.eq("Option"); + let field_ident = &field.ident; + let field_ident_string = field_ident.as_ref().map(|s| s.to_string()); + + if is_option || *self == Self::Updated { + quote! { self.#field_ident.map(|s| map.insert(#field_ident_string.to_string(), s)) } + } else { + quote! { map.insert(#field_ident_string.to_string(), self.#field_ident) } + } + }) + }); + + let from_encryptable_impl = inner.iter().flat_map(|field| { + get_field_type(field.ty.clone()).map(|field_ty| { + let is_option = field_ty.eq("Option"); + let field_ident = &field.ident; + let field_ident_string = field_ident.as_ref().map(|s| s.to_string()); + + if is_option || *self == Self::Updated { + quote! { #field_ident: map.remove(#field_ident_string) } + } else { + quote! { + #field_ident: map.remove(#field_ident_string).ok_or( + error_stack::report!(common_utils::errors::ParsingError::EncodeError( + "Unable to convert from HashMap", + )) + )? + } + } + }) + }); + + quote! { + impl ToEncryptable<#gen1, #gen2, #gen3> for #impl_st { + fn to_encryptable(self) -> FxHashMap<String, #gen3> { + let mut map = FxHashMap::with_capacity_and_hasher(#map_length, Default::default()); + #(#to_encryptable_impl;)* + map + } + + fn from_encryptable( + mut map: FxHashMap<String, Encryptable<#gen2>>, + ) -> CustomResult<#gen1, common_utils::errors::ParsingError> { + Ok(#gen1 { + #(#from_encryptable_impl,)* + }) + } + } + } + } +} + +/// This function generates the temporary struct and ToEncryptable impls for the temporary structs +fn generate_to_encryptable( + struct_name: Ident, + fields: Vec<Field>, +) -> syn::Result<proc_macro2::TokenStream> { + let struct_types = [ + // The first two are to be used as return types we do not need to implement ToEncryptable + // on it + ("Decrypted", StructType::Decrypted), + ("DecryptedUpdate", StructType::DecryptedUpdate), + ("FromRequestEncryptable", StructType::FromRequest), + ("Encrypted", StructType::Encrypted), + ("UpdateEncryptable", StructType::Updated), + ]; + + let inner_types = get_field_and_inner_types(&fields); + + let inner_type = inner_types.first().map(|(_, ty)| ty).ok_or_else(|| { + syn::Error::new( + proc_macro2::Span::call_site(), + "Please use the macro with attribute #[encrypt] on the fields you want to encrypt", + ) + })?; + + let structs = struct_types.iter().map(|(prefix, struct_type)| { + let name = format_ident!("{}{}", prefix, struct_name); + let temp_fields = struct_type.generate_struct_fields(&inner_types); + quote! { + pub struct #name { + #(#temp_fields,)* + } + } + }); + + // These implementations shouldn't be implemented Decrypted and DecryptedUpdate temp structs + // So skip the first two entries in the list + let impls = struct_types + .iter() + .skip(2) + .map(|(prefix, struct_type)| { + let name = format_ident!("{}{}", prefix, struct_name); + + let impl_block = if *struct_type != StructType::DecryptedUpdate + || *struct_type != StructType::Decrypted + { + let (gen1, gen2, gen3) = match struct_type { + StructType::FromRequest => { + let decrypted_name = format_ident!("Decrypted{}", struct_name); + ( + quote! { #decrypted_name }, + quote! { Secret<#inner_type> }, + quote! { Secret<#inner_type> }, + ) + } + StructType::Encrypted => { + let decrypted_name = format_ident!("Decrypted{}", struct_name); + ( + quote! { #decrypted_name }, + quote! { Secret<#inner_type> }, + quote! { Encryption }, + ) + } + StructType::Updated => { + let decrypted_update_name = format_ident!("DecryptedUpdate{}", struct_name); + ( + quote! { #decrypted_update_name }, + quote! { Secret<#inner_type> }, + quote! { Secret<#inner_type> }, + ) + } + //Unreachable statement + _ => (quote! {}, quote! {}, quote! {}), + }; + + struct_type.generate_impls(gen1, gen2, gen3, quote! { #name }, &fields) + } else { + quote! {} + }; + + Ok(quote! { + #impl_block + }) + }) + .collect::<syn::Result<Vec<_>>>()?; + + Ok(quote! { + #(#structs)* + #(#impls)* + }) +} + +pub fn derive_to_encryption( + input: syn::DeriveInput, +) -> Result<proc_macro2::TokenStream, syn::Error> { + let struct_name = input.ident; + let fields = get_encryptable_fields(get_struct_fields(input.data)?); + + generate_to_encryptable(struct_name, fields) +}
2024-10-14T17:27:37Z
## Description <!-- Describe your changes in detail --> This PR adds a macro to generate ToEncryptable trait on different types ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This PR removes the effort of repetitively implementing ToEncryptable trait which is used for batch encryption/decryption in the encryption service by adding a macro which generates code upon deriving it ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **THIS CANNOT BE TESTED ON SANDBOX** - Compiler guided. Since this does not change any core flow - Basic test of MerchantCreate and Payments for sanity
98567569c1c61648eebf0ad7a1ab58bba967b427
**THIS CANNOT BE TESTED ON SANDBOX** - Compiler guided. Since this does not change any core flow - Basic test of MerchantCreate and Payments for sanity
[ "crates/api_models/src/customers.rs", "crates/api_models/src/payments.rs", "crates/diesel_models/src/address.rs", "crates/diesel_models/src/events.rs", "crates/hyperswitch_domain_models/src/customer.rs", "crates/hyperswitch_domain_models/src/merchant_connector_account.rs", "crates/hyperswitch_domain_models/src/payments.rs", "crates/hyperswitch_domain_models/src/payments/payment_intent.rs", "crates/router/src/core/admin.rs", "crates/router/src/core/customers.rs", "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/operations/payment_create.rs", "crates/router/src/core/payouts/helpers.rs", "crates/router/src/types/domain/address.rs", "crates/router/src/types/domain/event.rs", "crates/router/src/utils.rs", "crates/router_derive/src/lib.rs", "crates/router_derive/src/macros.rs", "crates/router_derive/src/macros/to_encryptable.rs" ]
juspay/hyperswitch
juspay__hyperswitch-6312
Bug: replace underscore by hyphen in Samsung pay session call replace underscore by hyphen in Samsung pay session call as it is passed to samsung pay as `order_number`. And Samsung pay does not accept underscore
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 1785eee87c5..053c9b8fb0a 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -567,13 +567,15 @@ fn create_samsung_pay_session_token( })?, }; + let formatted_payment_id = router_data.payment_id.replace("_", "-"); + Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::SamsungPay(Box::new( payment_types::SamsungPaySessionTokenResponse { version: "2".to_string(), service_id: samsung_pay_wallet_details.service_id, - order_number: router_data.payment_id.clone(), + order_number: formatted_payment_id, merchant_payment_information: payment_types::SamsungPayMerchantPaymentInformation { name: samsung_pay_wallet_details.merchant_display_name,
2024-10-14T14:59:59Z
## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a connector with samsung pay enabled -> Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:' \ --data '{ "amount": 100000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1728548597" }' ``` ``` { "payment_id": "pay_mJFt25nBNl0ZKeW122Eu", "merchant_id": "merchant_1728917453", "status": "requires_payment_method", "amount": 100000, "net_amount": 100000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_mJFt25nBNl0ZKeW122Eu_secret_ssXacvSHe4w7Q6smAWOQ", "created": "2024-10-14T14:51:05.156Z", "currency": "USD", "customer_id": "cu_1728548597", "customer": { "id": "cu_1728548597", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1728548597", "created_at": 1728917465, "expires": 1728921065, "secret": "epk_cd0634f3e55a456aab914f0715a37cbd" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_a54a9pfTV5Yf5U2wboZ2", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-14T15:06:05.156Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-14T14:51:05.213Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> session call ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'x-client-platform: web' \ --header 'x-merchant-domain: sdk-test-app.netlify.app' \ --header 'api-key: pk_dev_f89f808cd23b4b53ba1f84d1ae675e3c' \ --data '{ "payment_id": "pay_mJFt25nBNl0ZKeW122Eu", "wallets": [], "client_secret": "pay_mJFt25nBNl0ZKeW122Eu_secret_ssXacvSHe4w7Q6smAWOQ" }' ``` ``` { "payment_id": "pay_mJFt25nBNl0ZKeW122Eu", "client_secret": "pay_mJFt25nBNl0ZKeW122Eu_secret_ssXacvSHe4w7Q6smAWOQ", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-mJFt25nBNl0ZKeW122Eu", "merchant": { "name": "Hyperswitch", "url": "sdk-test-app.netlify.app", "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "1000.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ```
df280f2574ac701a5e32b9bcae90c87cab7bc5aa
-> Create a connector with samsung pay enabled -> Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:' \ --data '{ "amount": 100000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1728548597" }' ``` ``` { "payment_id": "pay_mJFt25nBNl0ZKeW122Eu", "merchant_id": "merchant_1728917453", "status": "requires_payment_method", "amount": 100000, "net_amount": 100000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_mJFt25nBNl0ZKeW122Eu_secret_ssXacvSHe4w7Q6smAWOQ", "created": "2024-10-14T14:51:05.156Z", "currency": "USD", "customer_id": "cu_1728548597", "customer": { "id": "cu_1728548597", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1728548597", "created_at": 1728917465, "expires": 1728921065, "secret": "epk_cd0634f3e55a456aab914f0715a37cbd" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_a54a9pfTV5Yf5U2wboZ2", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-14T15:06:05.156Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-14T14:51:05.213Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> session call ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'x-client-platform: web' \ --header 'x-merchant-domain: sdk-test-app.netlify.app' \ --header 'api-key: pk_dev_f89f808cd23b4b53ba1f84d1ae675e3c' \ --data '{ "payment_id": "pay_mJFt25nBNl0ZKeW122Eu", "wallets": [], "client_secret": "pay_mJFt25nBNl0ZKeW122Eu_secret_ssXacvSHe4w7Q6smAWOQ" }' ``` ``` { "payment_id": "pay_mJFt25nBNl0ZKeW122Eu", "client_secret": "pay_mJFt25nBNl0ZKeW122Eu_secret_ssXacvSHe4w7Q6smAWOQ", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-mJFt25nBNl0ZKeW122Eu", "merchant": { "name": "Hyperswitch", "url": "sdk-test-app.netlify.app", "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "1000.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ```
[ "crates/router/src/core/payments/flows/session_flow.rs" ]